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.

fix(agent-core): match job files to their call instance, never the clock (#2393)

Call Whitece169436cf9e
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.md
index 8db390bb4..02fa1cce3 100644
--- a/core/agent_core/agent/README.md
+++ b/core/agent_core/agent/README.md
@@ -215,7 +215,9 @@ Watch integration is a later layer.
- Input rendering/environment deltas, delivery outbox, actual Session forking,
job-to-call lookup, Watch implementation, and output governance belong to the
adapter or tools. Recovery's renderer receives `(call, job_id, status, watch_id)`
- and returns a governed `ToolResult`; job keys include the original Session.
+ and returns a governed `ToolResult`; jobs are keyed by call instance (the
+ owning response, in the original Session for a fork's inherited call, plus
+ the call id).
The adapter serializes recovery with active runs. `JobHost.hand_over` must
reuse a job's existing Watch when recovery retries an interrupted commit.
- A stream error may persist its partial response as non-final evidence, but no
diff --git a/core/agent_core/agent/jobs.py b/core/agent_core/agent/jobs.py
index 5d5b86f53..4d687fbcc 100644
--- a/core/agent_core/agent/jobs.py
+++ b/core/agent_core/agent/jobs.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
from typing import Mapping, Optional
-from core.agent_core.tools.base import JobHost, JobStatus
+from core.agent_core.tools.base import CallInstance, JobHost, JobStatus
class ForegroundCleanupError(RuntimeError):
@@ -22,7 +22,7 @@ class TrackingJobHost:
def __init__(self, host: JobHost) -> None:
self.host = host
- self._foreground: dict[str, tuple[str, str]] = {}
+ self._foreground: dict[str, CallInstance] = {}
async def start(
self,
@@ -31,26 +31,16 @@ class TrackingJobHost:
cwd: str,
env: Mapping[str, str],
timeout_s: Optional[float],
- session_id: str,
- tool_call_id: str,
+ call: CallInstance,
) -> str:
- task = asyncio.create_task(
- self.host.start(
- command,
- cwd=cwd,
- env=env,
- timeout_s=timeout_s,
- session_id=session_id,
- tool_call_id=tool_call_id,
- )
- )
+ task = asyncio.create_task(self.host.start(command, cwd=cwd, env=env, timeout_s=timeout_s, call=call))
try:
job_id = await asyncio.shield(task)
except asyncio.CancelledError:
job_id = await task
- self._foreground[job_id] = (session_id, tool_call_id)
+ self._foreground[job_id] = call
raise
- self._foreground[job_id] = (session_id, tool_call_id)
+ self._foreground[job_id] = call
return job_id
def status(self, job_id: str) -> JobStatus:
@@ -93,8 +83,8 @@ class TrackingJobHost:
self, session_id: str, *, tool_call_id: Optional[str] = None, reason: str = "killed"
) -> None:
failures = []
- for job_id, (owner, call) in list(self._foreground.items()):
- if owner != session_id or (tool_call_id is not None and call != tool_call_id):
+ for job_id, call in list(self._foreground.items()):
+ if call.session_id != session_id or (tool_call_id is not None and call.tool_call_id != tool_call_id):
continue
try:
if self.status(job_id).state == "running":
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index 4db506ed2..5185e9df8 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -126,7 +126,7 @@ from core.agent_core.messages import (
text,
usage_to_dict,
)
-from core.agent_core.tools.base import JobHost, Tool, ToolContext, ToolResult
+from core.agent_core.tools.base import CallInstance, JobHost, Tool, ToolContext, ToolResult
from core.agent_core.tools.paths import to_thread_joined
T = TypeVar("T")
@@ -817,8 +817,11 @@ class Agent:
}
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."""
+ async def _commit_model_message(
+ self, message: AssistantMessage, emit: Callable[..., Awaitable[None]]
+ ) -> tuple[ContextEntry, bool]:
+ """Commit the response: its row, and whether it is final. Finality and queued-input admission share one lock
+ with the commit."""
pending: list[tuple[AgentInput, bool]] = []
consumed: list[tuple[AgentInput, bool]] = []
failed = message.stop_reason in {"error", "aborted"}
@@ -843,7 +846,7 @@ class Agent:
for item, is_steer in consumed:
if is_steer:
await emit(SteerApplied, message_id=item.message_id)
- return final
+ return row, final
async def _loop(self, system: str, emit: Callable[..., Awaitable[None]], selected: ModelSelection) -> RunEndReason:
first_selection: Optional[ModelSelection] = selected
@@ -885,7 +888,7 @@ class Agent:
"local" if aborted else "source",
cause=decided,
)
- final = await self._commit_model_message(message, emit)
+ response, final = await self._commit_model_message(message, emit)
empty_reply = final and not any(
isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content
)
@@ -919,6 +922,7 @@ class Agent:
self._scope.check()
await self._tool(
call,
+ response,
tools,
True,
emit,
@@ -964,7 +968,7 @@ class Agent:
terminate = False
for call in message.tool_calls:
self._scope.check()
- result, step_end = await self._tool(call, tools, skip or end, emit)
+ result, step_end = await self._tool(call, response, tools, skip or end, emit)
terminate = terminate or result.terminate
end = end or step_end
if end:
@@ -1004,6 +1008,7 @@ class Agent:
async def _tool(
self,
original: ToolCallBlock,
+ response: ContextEntry,
tools: Mapping[str, Tool],
skip: bool,
emit: Callable[..., Awaitable[None]],
@@ -1028,7 +1033,8 @@ class Agent:
if tool is None:
result = ToolResult((text(f"Tool {call.name} is not available."),), is_error=True)
else:
- result = await self._execute(tool, call, emit)
+ instance = CallInstance(response.session_id, response.row_id, response.context_seq, call.id)
+ result = await self._execute(tool, call, instance, emit)
if not end and not skip:
for hook in self.hooks:
decision = await self._hook(lambda: hook.after_tool(call, result, self._ctx))
@@ -1054,7 +1060,13 @@ class Agent:
)
return result, end
- async def _execute(self, tool: Tool, call: ToolCallBlock, emit: Callable[..., Awaitable[None]]) -> ToolResult:
+ async def _execute(
+ self,
+ tool: Tool,
+ call: ToolCallBlock,
+ instance: Optional[CallInstance],
+ emit: Callable[..., Awaitable[None]],
+ ) -> ToolResult:
# Progress is a latest-tail value, not an unbounded buffer of tool output.
updates: asyncio.Queue[str] = asyncio.Queue(maxsize=1)
@@ -1066,6 +1078,7 @@ class Agent:
ctx = ToolContext(
self.session_id,
call.id,
+ instance,
self.cwd,
dict(self.env),
self._ctx.cancel,
@@ -1651,7 +1664,8 @@ class Agent:
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)
+ # A checkpoint turn's call has no committed response, so no instance: it starts no job.
+ result = await self._execute(tool, call, None, _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)
diff --git a/core/agent_core/agent/recovery.py b/core/agent_core/agent/recovery.py
index 22725e11f..c0c0bdc36 100644
--- a/core/agent_core/agent/recovery.py
+++ b/core/agent_core/agent/recovery.py
@@ -13,7 +13,7 @@ from typing import Awaitable, Callable, Mapping, Optional
from core.agent_core.harness.projection import interrupted_result, open_tool_calls, validate_message_append
from core.agent_core.harness.store import ContextEntry, TranscriptStore
from core.agent_core.messages import ToolCallBlock, ToolResultMessage, text
-from core.agent_core.tools.base import JobHost, JobStatus, ToolResult
+from core.agent_core.tools.base import CallInstance, JobHost, JobStatus, ToolResult
#: ``None`` means the job holds no result for the call (it never ran, or ended for an unrecorded reason).
RecoveryRenderer = Callable[[ToolCallBlock, str, JobStatus, Optional[str]], Awaitable[Optional[ToolResult]]]
@@ -29,14 +29,14 @@ async def settle_open_calls(
session_id: str,
store: TranscriptStore,
jobs: JobHost,
- job_ids: Mapping[tuple[str, str], str],
+ job_ids: Mapping[CallInstance, str],
render_result: RecoveryRenderer,
) -> tuple[ContextEntry, ...]:
"""Commit one result per open call, using original-owner job lookup.
- ``job_ids`` is keyed by (response's session_id, tool_call_id), so a fork can
- find an inherited call's job. The adapter supplies bash's output-governance
- renderer; it receives (call, job_id, status, watch_id). ``JobHost.hand_over``
+ ``job_ids`` is keyed by call instance, whose response may be one a fork
+ inherited. The adapter supplies bash's output-governance renderer; it
+ receives (call, job_id, status, watch_id). ``JobHost.hand_over``
must reuse a job's existing Watch when recovery retries after an interrupted
commit. The job host owns the launch-handshake reconciliation behind status.
@@ -51,7 +51,7 @@ async def settle_open_calls(
committed: list[ContextEntry] = []
rows = list(await store.load(session_id))
for owner, call in open_tool_calls(rows):
- job_id = job_ids.get((owner.session_id, call.id))
+ job_id = job_ids.get(CallInstance(owner.session_id, owner.row_id, owner.context_seq, call.id))
message = interrupted_result(call)
details = {RECOVERED: True}
if job_id is None:
diff --git a/core/agent_core/tools/base.py b/core/agent_core/tools/base.py
index 5abe3c637..6054603af 100644
--- a/core/agent_core/tools/base.py
+++ b/core/agent_core/tools/base.py
@@ -26,10 +26,29 @@ class ToolSpec:
input_schema: Mapping[str, Any]
+@dataclass(frozen=True)
+class CallInstance:
+ """A tool call's identity: the committed response that made it, plus the call id.
+
+ Providers reuse call ids, so an id alone names no call. ``response_id`` is the
+ response's row (``messages.id``) and ``response_seq`` its ``context_seq`` in
+ ``session_id``; the call's result is the first ``tool_result`` with its id after
+ that response, in context order (C-5).
+ """
+
+ session_id: str
+ response_id: str
+ response_seq: int
+ tool_call_id: str
+
+
@dataclass(frozen=True)
class ToolContext:
session_id: str
tool_call_id: str
+ #: The call's instance when a committed response made it; ``None`` for a checkpoint turn's call (C-9),
+ #: which starts no job.
+ call: Optional[CallInstance]
cwd: str
env: Mapping[str, str]
cancel: CancelToken
@@ -74,8 +93,7 @@ class JobHost(Protocol):
cwd: str,
env: Mapping[str, str],
timeout_s: Optional[float],
- session_id: str,
- tool_call_id: str,
+ call: CallInstance,
) -> str: ...
def status(self, job_id: str) -> JobStatus: ...
diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.py
index 3ed8ff5ed..8504ea10f 100644
--- a/core/agent_core/tools/bash.py
+++ b/core/agent_core/tools/bash.py
@@ -26,7 +26,16 @@ from core.agent_core.tools.args import (
str_arg,
text_result,
)
-from core.agent_core.tools.base import MAX_BYTES, MAX_LINES, JobHost, JobStatus, ToolContext, ToolResult, ToolSpec
+from core.agent_core.tools.base import (
+ MAX_BYTES,
+ MAX_LINES,
+ CallInstance,
+ JobHost,
+ JobStatus,
+ ToolContext,
+ ToolResult,
+ ToolSpec,
+)
from core.agent_core.tools.jobs import (
STOP_ABORTED,
STOP_TIMEOUT,
@@ -163,9 +172,9 @@ async def recovered_result(
return await stopped_result(output, line) if line else None
-async def settle_bash_call(jobs: LocalJobHost, session_id: str, tool_call_id: str) -> Optional[ToolResult]:
+async def settle_bash_call(jobs: LocalJobHost, call: CallInstance) -> Optional[ToolResult]:
"""The durable result for a ``bash`` call left open by a crash; a running job is handed to Watch first."""
- job_id = jobs.find_job(session_id, tool_call_id)
+ job_id = jobs.find_job(call)
if job_id is None:
return None
await jobs.enforce_deadline(job_id)
@@ -201,6 +210,9 @@ class BashTool:
return error_result(f"Working directory is not accessible: {ctx.cwd}\nCannot execute bash commands.")
if ctx.cancel.cancelled:
return error_result("Command aborted")
+ if ctx.call is None:
+ # A job is keyed by its call instance; a checkpoint turn's call has none (its policy denies bash first).
+ return error_result("Commands cannot run in this turn.")
# The job host enforces the timeout (its wrapper decides timeout versus exit); bash only reports
# the recorded reason.
@@ -210,8 +222,7 @@ class BashTool:
cwd=ctx.cwd,
env=ctx.env,
timeout_s=timeout,
- session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id,
+ call=ctx.call,
)
except JobStartError as exc:
return error_result(str(exc))
diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.py
index 22f684b16..fc619dc42 100644
--- a/core/agent_core/tools/jobs.py
+++ b/core/agent_core/tools/jobs.py
@@ -51,7 +51,7 @@ from typing import Any, Awaitable, Callable, Mapping, Optional
import psutil
-from core.agent_core.tools.base import JobStatus
+from core.agent_core.tools.base import CallInstance, JobStatus
from core.agent_core.tools.paths import os_reason, run_to_end
from core.process_isolation import (
DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
@@ -121,27 +121,6 @@ def _iso(moment: datetime) -> str:
return moment.isoformat(timespec="milliseconds").replace("+00:00", "Z")
-def instant_text(moment: datetime) -> str:
- """A UTC instant at full microsecond precision, the form job and transcript times compare in."""
- return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
-
-
-def instant(value: object) -> Optional[datetime]:
- """Parse a recorded UTC time (``...Z`` or an offset) at full precision, or ``None``.
-
- The one parser for every time the job and recovery paths compare: a job's
- ``created_at``, a response's commit, a tool result's commit.
- """
- text = str(value or "").strip()
- if not text:
- return None
- try:
- moment = datetime.fromisoformat(text[:-1] + "+00:00" if text.endswith("Z") else text)
- except ValueError:
- return None
- return moment if moment.tzinfo is not None else moment.replace(tzinfo=timezone.utc)
-
-
def _ceil_ms(moment: datetime) -> datetime:
"""Round up to the millisecond ``_iso`` keeps, so a recorded deadline is never early."""
rest = moment.microsecond % 1000
@@ -183,6 +162,17 @@ def _read_text(path: str) -> Optional[str]:
return None
+def call_instance(meta: Mapping[str, Any]) -> Optional[CallInstance]:
+ """The call instance that started a job, from its ``meta.json``; ``None`` if the record names none."""
+ session_id, response_id = meta.get("session_id"), meta.get("response_id")
+ response_seq, tool_call_id = meta.get("response_seq"), meta.get("tool_call_id")
+ if not all(isinstance(value, str) for value in (session_id, response_id, tool_call_id)):
+ return None
+ if not isinstance(response_seq, int) or isinstance(response_seq, bool):
+ return None
+ return CallInstance(session_id, response_id, response_seq, tool_call_id)
+
+
class LocalJobHost:
"""Job handles under ``jobs_dir`` (``<state>/agent_core/jobs``).
@@ -234,30 +224,19 @@ class LocalJobHost:
def _write_meta(self, job_id: str, meta: Mapping[str, Any]) -> None:
_write_atomic(self._path(job_id, "meta.json"), _meta_text(meta))
- def find_job(
- self, session_id: str, tool_call_id: str, *, created_since: Optional[datetime] = None
- ) -> Optional[str]:
- """The job started for a tool call, for settling it at resume.
+ def find_job(self, call: CallInstance) -> Optional[str]:
+ """The job a call instance started, for settling the call at resume; it starts at most one.
- A provider may reuse a tool-call id in a later response, so several jobs can
- match: the newest is returned. ``created_since``, the commit time of the
- response that made the call, excludes jobs an earlier call with the same id
- started.
+ Matched on the whole instance, never the call id alone: a provider may reuse an id in a later response.
"""
- newest: Optional[tuple[datetime, str]] = None
for name in self._job_ids():
try:
meta = self.meta(name)
except (KeyError, ValueError, OSError):
continue
- if meta.get("session_id") != session_id or meta.get("tool_call_id") != tool_call_id:
- continue
- created = instant(meta.get("created_at"))
- if created is None or (created_since is not None and created < created_since):
- continue
- if newest is None or created > newest[0]:
- newest = (created, name)
- return newest[1] if newest is not None else None
+ if call_instance(meta) == call:
+ return name
+ return None
def _job_ids(self) -> list[str]:
try:
@@ -312,10 +291,9 @@ class LocalJobHost:
cwd: str,
env: Mapping[str, str],
timeout_s: Optional[float],
- session_id: str,
- tool_call_id: str,
+ call: CallInstance,
) -> str:
- """Start ``command`` with ``env`` as its whole environment; return once it may run.
+ """Start ``command`` for ``call`` with ``env`` as its whole environment; return once it may run.
Raises ``JobStartError`` when the command did not start.
"""
@@ -325,7 +303,7 @@ class LocalJobHost:
raise JobStartError("No Python interpreter is available to run the command.")
# The host's own steps are small and synchronous, so the only await is the wait for the pid: a cancel
# can land nowhere else, and never between publishing ``go`` and returning the job id.
- job_id, proc, marker, meta = self._spawn(command, cwd, env, timeout_s, session_id, tool_call_id)
+ job_id, proc, marker, meta = self._spawn(command, cwd, env, timeout_s, call)
try:
identity = await self._await_pid(job_id, proc, marker)
except asyncio.CancelledError:
@@ -343,8 +321,7 @@ class LocalJobHost:
cwd: str,
env: Mapping[str, str],
timeout_s: Optional[float],
- session_id: str,
- tool_call_id: str,
+ call: CallInstance,
) -> tuple[str, subprocess.Popen, str, dict[str, Any]]:
"""The job directory, ``meta.json``, and the wrapper, which waits for the decision (J1)."""
job_id = f"job_{secrets.token_hex(8)}"
@@ -354,15 +331,15 @@ class LocalJobHost:
meta: dict[str, Any] = {
"version": 1,
"job_id": job_id,
- "session_id": session_id,
- "tool_call_id": tool_call_id,
+ "session_id": call.session_id,
+ "response_id": call.response_id,
+ "response_seq": call.response_seq,
+ "tool_call_id": call.tool_call_id,
"backend": "pipe",
"command": command,
"cwd": cwd,
"timeout_s": timeout_s,
- # Full precision: recovery tells apart jobs a reused tool-call id started
- # within one millisecond (``find_job``).
- "created_at": instant_text(created),
+ "created_at": _iso(created),
"state_dir": job_dir,
"process": None,
"terminal": None,
diff --git a/docs/plans/agent-core-contracts/job.schema.json b/docs/plans/agent-core-contracts/job.schema.json
index 0971fbb0f..577efee8c 100644
--- a/docs/plans/agent-core-contracts/job.schema.json
+++ b/docs/plans/agent-core-contracts/job.schema.json
@@ -8,6 +8,8 @@
"version",
"job_id",
"session_id",
+ "response_id",
+ "response_seq",
"tool_call_id",
"backend",
"command",
@@ -28,6 +30,14 @@
"session_id": {
"type": "string"
},
+ "response_id": {
+ "type": "string",
+ "description": "`messages.id` of the committed response that made the call. With `session_id`, `response_seq`, and `tool_call_id`, the call instance that started the job (`CallInstance`, `ToolContext.call`): providers reuse call ids, so T2's job lookup, J5's settled check, and the hand-over's owning Turn match a job to its call by the whole instance, never by time."
+ },
+ "response_seq": {
+ "type": "integer",
+ "description": "That response's `context_seq` in `session_id`. The call's result is the first `tool_result` with its id after it, in context order."
+ },
"tool_call_id": {
"type": "string"
},
@@ -53,7 +63,7 @@
"created_at": {
"type": "string",
"format": "date-time",
- "description": "UTC creation time at full microsecond precision; recovery compares it with a response's commit time to tell apart jobs a reused tool-call id started."
+ "description": "UTC creation time, from which a job Watch reports the elapsed time. Never compared with a row's time: the wall clock can step back."
},
"state_dir": {
"type": "string",
@@ -123,12 +133,14 @@
"version": 1,
"job_id": "job_31c",
"session_id": "ses7k2m9p4q1x",
+ "response_id": "msg_0640b3c1f2a9e8d47c1e9a2b",
+ "response_seq": 42,
"tool_call_id": "toolu_01AbC",
"backend": "pipe",
"command": "pytest -q",
"cwd": "/work/repo",
"timeout_s": null,
- "created_at": "2026-10-02T04:12:09.512345Z",
+ "created_at": "2026-10-02T04:12:09.512Z",
"state_dir": "/home/u/.avibe/state/agent_core/jobs/job_31c",
"process": {
"pid": 48211,
diff --git a/docs/plans/agent-core-contracts/recovery.md b/docs/plans/agent-core-contracts/recovery.md
index 744f61309..fe6d1cc34 100644
--- a/docs/plans/agent-core-contracts/recovery.md
+++ b/docs/plans/agent-core-contracts/recovery.md
@@ -16,7 +16,7 @@ at-least-once, and that is stated where it applies.
| J2 | Before a command can run, the job record holds an identity that distinguishes its process tree from a recycled pid, so recovery can inspect and kill exactly that tree. | kill and inspect after a simulated pid reuse |
| J3 | A `timeout` holds across handover and vibe restarts: the deadline is absolute and recorded with the job, and whichever component owns the job when it passes kills the tree. | timeout shorter than the foreground window with `watch: true`, and with a restart in between |
| J4 | Output on disk is bounded per job (head and tail kept, middle dropped beyond a fixed cap), and every result or follow-up built from a truncated log says so. | a command producing more than the cap |
-| J5 | Job files are kept until the owning tool call has a durable `tool_result` and the Watch that owns the job, if any, has settled. | an exited job whose call is unsettled is never removed |
+| J5 | Job files are kept until the call instance that started the job has a durable `tool_result` and the Watch that owns the job, if any, has settled. An earlier call's result never settles a later call that reuses its id. | an exited job whose call is unsettled is never removed, including after a reused id and a wall clock that stepped back |
| J6 | Handover is idempotent per job: one job has at most one Watch, whatever crashes in between. | crash between Watch creation and committing the handover result, then recovery |
## Tool calls (`loop` lane)
@@ -24,7 +24,7 @@ at-least-once, and that is stated where it applies.
| ID | Invariant | Proof |
| --- | --- | --- |
| T1 | `project()` reads only committed rows; the same rows always produce the same request. | projection before and after job state changes |
-| T2 | At resume, before the first projection, and when a run ends without completing (a Stop), every tool call without a committed `tool_result` gets exactly one, chosen from its job state (exited: the output; running: handover; stopped with a recorded reason: that result; never ran: the interrupted result). A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice, and neither do concurrent writers: the store's `append_tool_result` returns the result already committed for the call instance instead of writing a second. | crash between settlement steps, then resume twice |
+| T2 | At resume, before the first projection, and when a run ends without completing (a Stop), every tool call without a committed `tool_result` gets exactly one, chosen from the state of the job its call instance started (exited: the output; running: handover; stopped with a recorded reason: that result; never ran: the interrupted result). A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice, and neither do concurrent writers: the store's `append_tool_result` returns the result already committed for the call instance instead of writing a second. | crash between settlement steps, then resume twice |
| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context, including after a crash. They belong to the Turn that accepted them and are never re-queued as a new P3 Turn. A run that ended by design runs again for them within its Turn; after a stop, an error, or a crash they are admitted into the context (at the end of the run, or at the Session's resume) and share the Turn's outcome. | a terminating tool while a steer is queued; a crash before consumption |
| T4 | An unsettled Turn found at startup is settled as interrupted after T2; the agent never continues it on its own (a hook `end`, an abort, or a crash all leave the same safe state). The user's next message starts a new Turn with the full context. When T2 handed the Turn's running commands to Watches, its notice names them and offers no Retry, because a resend would run them twice. | crash after an `end` hook and after a mid-turn commit |
@@ -43,7 +43,10 @@ notice, and the committed reply stays in the Workbench transcript with its commi
The only cross-lane shapes recovery adds:
- `meta.json` (`job.schema.json`): `deadline_at` (absolute, nullable), and `process` with the identity fields of
- `PersistedProcessIdentity` (`core/process_isolation.py`), recorded before the command can run (J2).
+ `PersistedProcessIdentity` (`core/process_isolation.py`), recorded before the command can run (J2). `session_id`,
+ `response_id`, `response_seq`, and `tool_call_id` are the call instance that started the job. T2's job lookup,
+ J5's settled check, and the hand-over's owning Turn all match on it, in context order; none compares a job's
+ `created_at` with a row's time.
- `tool_result` `details.recovered`: `true` on every result T2 commits, so T4 tells the Watches recovery created for
the Turn's running commands from those the Turn handed over itself (`storage.agent_transcript.recovered_watch_ids`).
- Watch `job` target: keyed by `job_id`, created by adopt-or-create (J6). The hand-over takes the Watch's Agent and
diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.md
index 04c66164b..3ffed88cf 100644
--- a/docs/plans/agent-core-contracts/tools.md
+++ b/docs/plans/agent-core-contracts/tools.md
@@ -178,7 +178,7 @@ backend they are required.
| Operation | v1 | Meaning |
| --- | --- | --- |
-| `start(command, cwd, env, timeout)` → `job_id` | yes | create the job directory and metadata, then spawn the wrapper in its own session |
+| `start(command, cwd, env, timeout, call)` → `job_id` | yes | create the job directory and metadata for the call instance `call`, then spawn the wrapper in its own session |
| `status(job_id)` | yes | `running`, `exited{code}`, or `gone` (ended without an exit code) |
| `wait(job_id, deadline_s)` | yes | until exit, or at most `deadline_s` seconds from now (`None`: until exit) |
| `output_path(job_id)` | yes | absolute path of `output.log`, named in truncated and handover results |
@@ -187,6 +187,11 @@ backend they are required.
| `hand_over(job_id)` → `watch_id` | yes | register a once Watch with target kind `job` |
| `send(job_id, keys)`, `screen(job_id)`, `resize(job_id, cols, rows)`, `attach_info(job_id)` | reserved | `pty` backend (plan §5.4) |
+A job belongs to its call instance (`CallInstance`, the loop's `ToolContext.call`): the committed response that made
+the call, as its row id and `context_seq`, plus the call id. Providers reuse call ids, so every lookup from a call to
+its job matches the whole instance, and none compares a job's time with a row's: the wall clock can step back. A
+checkpoint turn's call has no committed response and starts no job.
+
Job directory: `<state>/agent_core/jobs/<job_id>/` with `meta.json`, `output.log`, and the files the `tools` lane's
launch mechanism needs. The job host meets recovery invariants J1–J6 ([`recovery.md`](recovery.md)): a command starts
at most once and recovery can always decide whether it did; its identity is recorded before it runs; `timeout` is an
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index 34dc57e6c..52ca56ce7 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -389,4 +389,4 @@ contracts and checked against the implementing lane's code before they are close
| 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. |
| Slash commands are actions | `core/session_turns.py`, `storage/message_deliveries.py`, `storage/messages_service.py` (every backend) | A user message that is a slash command (`/model`, `/memory`, … for the native backends) is an ordinary user row today, so each consumer re-parses text: Delivery segmentation can merge it with neighbouring queued messages, and title backfill can take it as the first prompt. Classify once at ingestion (a `metadata.command` marker, one helper as the legacy fallback); a command delivery never merges; titles skip command rows by the marker. Not part of the C-9 wave: the Avibe Agent has no slash command of its own (owner decision, 2026-10-05). |
| 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. |
+| Call-instance identity for job files | `core/agent_core/tools/` (`ToolContext`, job `meta.json`), the adapter | **Done.** A tool call's identity is its instance: the owning response plus the call id, because providers reuse ids. The loop gives every executed call its instance (`ToolContext.call`: the response's row id and `context_seq`), and the job's `meta.json` records it. T2's job lookup (`find_job`), J5's settled check, and the hand-over's owning Turn match on the whole instance in context order; the clock fallback, which assumed a non-decreasing wall clock between a response's commit and its job's start, is gone. |
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index 3efd76026..c4aacbaa3 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -29,7 +29,6 @@ import secrets
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass, field, replace
-from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
from typing import Any, AsyncIterator, Callable, Mapping, Optional, Sequence
@@ -53,7 +52,8 @@ from core.agent_core.agent.recovery import settle_open_calls
from core.agent_core.harness.context import ContextConfig
from core.agent_core.harness.projection import open_tool_calls
from core.agent_core.harness.store import ContextEntry
-from core.agent_core.tools.jobs import instant
+from core.agent_core.tools.base import CallInstance
+from core.agent_core.tools.jobs import call_instance
from core.agent_core.messages import (
IMAGE_MIME_TYPES,
AssistantMessage,
@@ -95,9 +95,9 @@ from storage.agent_transcript import (
INPUT_TYPES,
RESPONSE_TYPES,
SQLiteTranscriptStore,
+ call_instance_result,
final_outcome,
render_text,
- source_tool_result,
)
from storage.db import get_cached_sqlite_engine
from storage.models import agent_events, agent_sessions, message_deliveries, messages, session_turns
@@ -410,28 +410,16 @@ class VibeyAgent(BaseAgent):
logger.exception("Vibey job pruning failed")
def _job_call_settled(self, meta: Any) -> bool:
- """Whether the job's tool call has a durable ``tool_result`` row (the adapter's half of J5).
+ """Whether the job's call instance has a durable ``tool_result`` row (the adapter's half of J5).
- Only a result committed after the job was created counts: a provider may reuse
- a tool-call id, and an earlier call's result does not settle a later one. The
- same rule as T2's job lookup (``_settle_open_calls``).
+ Matched in context order, never by time: a provider may reuse a tool-call id,
+ and an earlier call's result does not settle a later one.
"""
- from sqlalchemy import func
-
- session_id, call_id = str(meta.get("session_id") or ""), str(meta.get("tool_call_id") or "")
- created = instant(meta.get("created_at"))
- if not session_id or not call_id or created is None:
+ call = call_instance(meta)
+ if call is None:
return False
with self._engine.connect() as conn:
- committed = conn.execute(
- select(agent_events.c.created_at).where(
- agent_events.c.session_id == session_id,
- agent_events.c.event_type == "tool_result",
- agent_events.c.context_seq.is_not(None),
- func.json_extract(agent_events.c.content_json, "$.message.tool_call_id") == call_id,
- )
- ).scalars()
- return any((moment := instant(value)) is not None and moment >= created for value in committed)
+ return call_instance_result(conn, call.session_id, call.response_seq, call.tool_call_id) is not None
async def prepare_resume_binding(self, *, base_session_id: str, session_key: str, working_path: str) -> None:
"""Nothing to prepare: the transcript is the Session's own rows, read at the next run."""
@@ -730,24 +718,22 @@ class VibeyAgent(BaseAgent):
return
suite = self._tools()
- def evidence() -> tuple[list[ContextEntry], dict[tuple[str, str], str]]:
+ def evidence() -> tuple[list[ContextEntry], dict[CallInstance, str]]:
# A call is its instance, the owning response plus its id (providers reuse ids).
# A call this Session inherited open takes the result its owner committed, matched
- # in context order. Only a job file falls back to the clock: its job started after
- # the owning response committed (one rule with J5).
- committed = self._committed_at([owner.row_id for owner, _ in open_calls])
+ # in context order; any other call, the job its instance started.
inherited, found = [], {}
with self._engine.connect() as conn:
for owner, call in open_calls:
if owner.session_id != session_id:
- result = source_tool_result(conn, owner.session_id, owner.context_seq, call.id)
+ result = call_instance_result(conn, owner.session_id, owner.context_seq, call.id)
if result is not None:
inherited.append(result)
continue
- since = committed.get(owner.row_id)
- job_id = suite.find_job(owner.session_id, call.id, created_since=since)
+ instance = CallInstance(owner.session_id, owner.row_id, owner.context_seq, call.id)
+ job_id = suite.find_job(instance)
if job_id is not None:
- found[(owner.session_id, call.id)] = job_id
+ found[instance] = job_id
return inherited, found
# Each job lookup lists the jobs directory: one pass, off the event loop.
@@ -777,9 +763,9 @@ class VibeyAgent(BaseAgent):
"""A job Watch's Agent and authorization, from the job's owning Turn (fail closed).
The same rule for every hand-over, in a Turn or at startup: the owning response
- is the latest one carrying the job's call, committed at or before the job's
- creation; its Turn is the one whose input the response answers, and that Turn's
- initial input row carries the principal and its persisted resource snapshot.
+ is the one the job's call instance names; its Turn is the one whose input the
+ response answers, and that Turn's initial input row carries the principal and
+ its persisted resource snapshot.
A remote Turn without a usable snapshot, or a job whose Turn cannot be found, is
handed over as unverifiable: owned, but never followed up.
"""
@@ -790,14 +776,22 @@ class VibeyAgent(BaseAgent):
resource_user_context_from_metadata,
)
- session_id, call_id = str(meta.get("session_id") or ""), str(meta.get("tool_call_id") or "")
- created = instant(meta.get("created_at"))
+ call = call_instance(meta)
+ if call is None:
+ return {"unverifiable_remote": True}
+ session_id = call.session_id
with self._engine.connect() as conn:
- owner = self._owning_response(conn, session_id, call_id, created)
- origin = self._turn_initial_input(conn, session_id, owner["context_seq"]) if owner else None
+ owner = conn.execute(
+ select(messages.c.author_name).where(
+ messages.c.id == call.response_id,
+ messages.c.session_id == session_id,
+ messages.c.context_seq == call.response_seq,
+ )
+ ).first()
+ origin = self._turn_initial_input(conn, session_id, call.response_seq) if owner else None
if owner is None or origin is None:
return {"unverifiable_remote": True}
- route: dict[str, Any] = {"agent_name": owner["author_name"]} if owner["author_name"] else {}
+ route: dict[str, Any] = {"agent_name": owner.author_name} if owner.author_name else {}
metadata = _json_object(origin["metadata_json"])
caller = caller_context_from_platform_payload(
{"agent_session_id": session_id, "platform": origin["platform"], "message_metadata": metadata},
@@ -820,26 +814,6 @@ class VibeyAgent(BaseAgent):
return {**route, "unverifiable_remote": True}
return {**route, "user_context": context}
- @staticmethod
- def _owning_response(conn: Any, session_id: str, call_id: str, created: Optional[datetime]) -> Optional[dict]:
- from sqlalchemy import text as sql_text
-
- rows = conn.execute(
- sql_text(
- "SELECT m.context_seq, m.author_name, m.created_at FROM messages AS m, "
- "json_each(json_extract(m.content_json, '$.model.message.content')) AS block "
- "WHERE m.session_id = :session_id AND m.context_seq IS NOT NULL "
- "AND json_extract(block.value, '$.type') = 'tool_call' AND json_extract(block.value, '$.id') = :call_id "
- "ORDER BY m.context_seq DESC"
- ),
- {"session_id": session_id, "call_id": call_id},
- ).mappings()
- for row in rows:
- committed = instant(row["created_at"])
- if created is None or committed is None or committed <= created:
- return dict(row)
- return None
-
@staticmethod
def _turn_initial_input(conn: Any, session_id: str, before_seq: int) -> Optional[dict]:
"""The initial input row of the Turn whose input precedes ``before_seq``."""
@@ -877,11 +851,6 @@ class VibeyAgent(BaseAgent):
).mappings().first()
return dict(row) if row is not None else None
- def _committed_at(self, row_ids: Sequence[str]) -> dict[str, datetime]:
- with self._engine.connect() as conn:
- rows = conn.execute(select(messages.c.id, messages.c.created_at).where(messages.c.id.in_(set(row_ids))))
- return {row_id: moment for row_id, created in rows if (moment := instant(created)) is not None}
-
def _unconsumed_inputs(self, session_id: str) -> list[tuple[str, str, list[FileAttachment], dict[str, Any]]]:
"""Inputs accepted into a ``vibey`` Turn but never consumed, in acceptance order.
diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.py
index 72a04d606..a77e77003 100644
--- a/modules/agents/vibey/tools.py
+++ b/modules/agents/vibey/tools.py
@@ -3,8 +3,8 @@
``ToolSuite`` is the adapter's whole dependency on ``core.agent_core.tools``:
the job host, the tools built over the loop's tracking wrapper (``Agent.jobs``,
so an abort kills foreground commands), the bash renderer recovery uses for open
-calls (``recovery.md`` T2), the lookup from a tool call to its job, and job
-pruning.
+calls (``recovery.md`` T2), the lookup from a call instance to its job, and
+job pruning.
The job host lives in Watch's ``agent_jobs_dir()``, where ``vibe stop`` and the
job-Watch sweep look, and hands a job over through Watch's own
@@ -20,7 +20,7 @@ from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Mapping, Optional, Sequence
from core.agent_core.agent.recovery import RecoveryRenderer
-from core.agent_core.tools.base import JobHost, Tool
+from core.agent_core.tools.base import CallInstance, JobHost, Tool
ImageSink = Callable[[bytes, str, str], Awaitable[str]]
#: Whether a job's tool call has a durable ``tool_result`` (the adapter's half of J5).
@@ -32,8 +32,8 @@ class ToolSuite:
jobs: JobHost
create_tools: Callable[[JobHost, Optional[ImageSink]], Sequence[Tool]]
render_recovered: RecoveryRenderer
- # ``find_job(session_id, tool_call_id, *, created_since)``: the newest job the call started.
- find_job: Callable[..., Optional[str]]
+ #: The job a call instance started, if any.
+ find_job: Callable[[CallInstance], Optional[str]]
prune: Optional[Callable[[CallSettled], list[str]]] = None
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 44d75980e..241153997 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -594,19 +594,19 @@ def _settled_result(conn: Connection, session_id: str, tool_call_id: str) -> Opt
return _event_entry(first["session_id"], first) if first is not None else None
-def source_tool_result(
+def call_instance_result(
conn: Connection, owner_session_id: str, response_seq: int, tool_call_id: str
) -> Optional[ContextEntry]:
- """The result its owner committed for a call instance a fork inherited open.
+ """The result its owner committed for a call instance, if it has one.
- A fork anchored between a response and its tool results inherits those calls
- open. A call's identity is its instance: the response that carries it
+ A call's identity is its instance: the response that carries it
(``owner_session_id`` at ``response_seq``) plus its id, because providers may
reuse ids. Its result is the first ``tool_result`` for that id after the
response in the owner's own rows, in context order: every call is settled
- before the next model call, so a later reuse of the id comes after it. The
- child settles with that result instead of re-deriving it from job state that
- J5 may since have pruned.
+ before the next model call, so a later reuse of the id comes after it. A fork
+ anchored between a response and its tool results inherits those calls open
+ and settles them with this result instead of re-deriving it from job state
+ that J5 may since have pruned; J5 keeps a job's files until it exists.
"""
row = (
conn.execute(
diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.py
index 961d8b655..37e05ed9b 100644
--- a/tests/agent_core/agent/test_loop.py
+++ b/tests/agent_core/agent/test_loop.py
@@ -49,7 +49,7 @@ 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
+from core.agent_core.tools.base import CallInstance, ToolResult
from tests.agent_core.fakes import (
FakeJobHost,
FakeModelRouter,
@@ -107,8 +107,10 @@ async def test_C1_tool_set_is_captured_per_request_and_unavailable_calls_are_err
release.set()
await run
assert [[spec.name for spec in request.tools] for request in provider.requests] == [["old"], ["new"], ["new"]]
- assert [ctx.tool_call_id for _, ctx in old.calls] == ["a"]
- assert [ctx.tool_call_id for _, ctx in new.calls] == ["c"]
+ # Each call runs as its instance: the committed response that made it, plus its id.
+ first, second, _ = [row for row in await agent.store.load("session") if row.kind == "response"]
+ assert [ctx.call for _, ctx in old.calls] == [CallInstance("session", first.row_id, first.context_seq, "a")]
+ assert [ctx.call for _, ctx in new.calls] == [CallInstance("session", second.row_id, second.context_seq, "c")]
results = [row.message for row in await agent.store.load("session") if row.kind == "tool_result"]
assert [result.tool_call_id for result in results] == ["a", "b", "c", "d"]
assert [(result.is_error, result.content[0].text) for result in (results[1], results[3])] == [
@@ -880,9 +882,7 @@ async def test_abort_kills_foreground_through_JobHost_but_preserves_handed_over_
agent = make_agent(provider, jobs=host)
async def execute(arguments, ctx):
- job = await agent.jobs.start(
- "test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, session_id=ctx.session_id, tool_call_id=ctx.tool_call_id
- )
+ job = await agent.jobs.start("test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, call=ctx.call)
if ctx.tool_call_id == "bg":
watch = await agent.jobs.hand_over(job)
return ToolResult((text("watch"),), details={"watch_id": watch, "job_id": job})
@@ -927,9 +927,7 @@ async def test_abort_during_job_ownership_transition_waits_then_kills_only_foreg
agent = make_agent(provider, jobs=host)
async def execute(arguments, ctx):
- job = await agent.jobs.start(
- "test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, session_id=ctx.session_id, tool_call_id=ctx.tool_call_id
- )
+ job = await agent.jobs.start("test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, call=ctx.call)
if transition == "hand_over":
await agent.jobs.hand_over(job)
await asyncio.Event().wait()
@@ -1307,8 +1305,7 @@ async def test_run_lifecycle_owns_admission_and_releases_every_foreground_job(ph
cwd="/test-owned",
env={},
timeout_s=None,
- session_id=ctx.session_id,
- tool_call_id="cleanup",
+ call=CallInstance(ctx.session_id, "msg_cleanup", 0, "cleanup"),
)
async def stream(request, cancel):
@@ -1323,8 +1320,7 @@ async def test_run_lifecycle_owns_admission_and_releases_every_foreground_job(ph
cwd=ctx.cwd,
env=ctx.env,
timeout_s=None,
- session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id,
+ call=ctx.call,
)
await agent.jobs.hand_over(watched)
await agent.jobs.start(
@@ -1332,8 +1328,7 @@ async def test_run_lifecycle_owns_admission_and_releases_every_foreground_job(ph
cwd=ctx.cwd,
env=ctx.env,
timeout_s=None,
- session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id,
+ call=ctx.call,
)
if phase == "dependency":
raise asyncio.CancelledError()
@@ -1489,8 +1484,7 @@ async def test_failed_foreground_kill_is_reported_and_does_not_skip_other_handle
cwd=ctx.cwd,
env=ctx.env,
timeout_s=None,
- session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id,
+ call=ctx.call,
)
if index == 0:
await agent.jobs.hand_over(job)
diff --git a/tests/agent_core/agent/test_outcomes.py b/tests/agent_core/agent/test_outcomes.py
index 72c235dbe..f556997f0 100644
--- a/tests/agent_core/agent/test_outcomes.py
+++ b/tests/agent_core/agent/test_outcomes.py
@@ -17,7 +17,7 @@ from core.agent_core.agent.models import RetryPolicy
from core.agent_core.ai.provider import Done, ProviderError
from core.agent_core.harness.projection import project
from core.agent_core.messages import LargeRef, TextBlock, ToolCallBlock, UserMessage, text
-from core.agent_core.tools.base import ToolResult
+from core.agent_core.tools.base import CallInstance, ToolResult
from tests.agent_core.fakes import (
FakeJobHost,
FakeModelRouter,
@@ -84,8 +84,7 @@ async def test_primary_outcome_cross_cleanup_keeps_reason_rows_and_event_order(
cwd="/test-owned",
env={},
timeout_s=None,
- session_id=ctx.session_id,
- tool_call_id="cleanup",
+ call=CallInstance(ctx.session_id, "msg_cleanup", 0, "cleanup"),
)
if cleanup == "after_run":
raise RuntimeError("after_run failed")
diff --git a/tests/agent_core/agent/test_recovery.py b/tests/agent_core/agent/test_recovery.py
index 6e27475ac..179f9f076 100644
--- a/tests/agent_core/agent/test_recovery.py
+++ b/tests/agent_core/agent/test_recovery.py
@@ -14,7 +14,7 @@ from core.agent_core.agent.recovery import settle_open_calls
from core.agent_core.ai.provider import Done
from core.agent_core.harness.projection import INTERRUPTED, ProjectionError, project
from core.agent_core.messages import LargeRef, TextBlock, ToolCallBlock, ToolResultMessage, text
-from core.agent_core.tools.base import JobStatus, ToolResult
+from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult
from tests.agent_core.fakes import (
FakeJobHost,
FakeModelRouter,
@@ -26,6 +26,10 @@ from tests.agent_core.fakes import (
)
+def _instance(response, call_id):
+ return CallInstance(response.session_id, response.row_id, response.context_seq, call_id)
+
+
async def _never_rendered(*_args):
pytest.fail("a call without a job must not invoke the renderer")
@@ -69,10 +73,10 @@ async def test_resume_settles_each_job_state_once_and_projection_never_rechecks_
# without job state. The previous bash-only table missed write/edit wording.
store, jobs = InMemoryTranscriptStore(), FakeJobHost()
call = ToolCallBlock("call", tool_name)
- await store.append_response("session", assistant(calls=[call]), final=False)
+ response = await store.append_response("session", assistant(calls=[call]), final=False)
job_ids = {}
if state != "missing":
- job_ids[("session", "call")] = "job_1"
+ job_ids[_instance(response, "call")] = "job_1"
jobs.states["job_1"] = JobStatus(
"gone" if state in {"never-ran", "stopped"} else state, exit_code=7 if state == "exited" else None
)
@@ -133,7 +137,7 @@ async def test_settlement_resume_after_partial_commit_skips_done_calls_and_keeps
return await super().append_tool_result(session_id, message, details=details)
store, jobs = InterruptedStore(), FakeJobHost()
- await store.append_response(
+ response = await store.append_response(
"session",
assistant(
calls=[
@@ -146,7 +150,7 @@ async def test_settlement_resume_after_partial_commit_skips_done_calls_and_keeps
for name in ("a", "b"):
jobs.states[name] = JobStatus("exited", exit_code=0)
jobs.outputs[name] = name.encode()
- ids = {("session", name): name for name in ("a", "b")}
+ ids = {_instance(response, name): name for name in ("a", "b")}
async def render(call, job_id, status, watch_id):
if failure == "unsupported_result" and store.fail and call.id == "b":
@@ -195,7 +199,7 @@ async def test_fork_settlement_uses_parent_job_identity_and_late_rows_project_at
session_id="child",
store=store,
jobs=jobs,
- job_ids={("parent", "a"): "job_a"},
+ job_ids={_instance(response, "a"): "job_a"},
render_result=renderer(jobs),
)
child = project(await store.load("child"))
@@ -226,7 +230,7 @@ async def test_retry_after_handover_commit_failure_reuses_job_identity_without_s
return await super().hand_over(job_id)
store, jobs = InterruptedStore(), Host()
- await store.append_response("session", assistant(calls=[ToolCallBlock("a", "bash")]), final=False)
+ response = await store.append_response("session", assistant(calls=[ToolCallBlock("a", "bash")]), final=False)
jobs.states["job_a"] = JobStatus("running")
jobs.outputs["job_a"] = b""
with pytest.raises(OSError, match="commit interrupted"):
@@ -234,7 +238,7 @@ async def test_retry_after_handover_commit_failure_reuses_job_identity_without_s
session_id="session",
store=store,
jobs=jobs,
- job_ids={("session", "a"): "job_a"},
+ job_ids={_instance(response, "a"): "job_a"},
render_result=renderer(jobs),
)
watch = jobs.watches["job_a"]
@@ -243,7 +247,7 @@ async def test_retry_after_handover_commit_failure_reuses_job_identity_without_s
session_id="session",
store=store,
jobs=jobs,
- job_ids={("session", "a"): "job_a"},
+ job_ids={_instance(response, "a"): "job_a"},
render_result=renderer(jobs),
)
assert len(rows) == 1
@@ -271,7 +275,8 @@ async def test_foreground_release_is_scoped_to_call_then_session_and_never_watch
host = FakeJobHost()
tracked = TrackingJobHost(host)
for session, call in [("one", "a"), ("one", "b"), ("two", "a"), ("one", "a")]:
- await tracked.start("fake", cwd="/test-owned", env={}, timeout_s=None, session_id=session, tool_call_id=call)
+ instance = CallInstance(session, "msg_1", 1, call)
+ await tracked.start("fake", cwd="/test-owned", env={}, timeout_s=None, call=instance)
await tracked.hand_over("job_4")
await tracked.kill_foreground("one", tool_call_id="a")
assert host.killed == ["job_1"]
diff --git a/tests/agent_core/fakes.py b/tests/agent_core/fakes.py
index aa6df8c8d..4e788b14c 100644
--- a/tests/agent_core/fakes.py
+++ b/tests/agent_core/fakes.py
@@ -227,18 +227,10 @@ class FakeJobHost:
self.watches: dict[str, str] = {}
self.changed = asyncio.Event()
- async def start(self, command, *, cwd, env, timeout_s, session_id, tool_call_id) -> str:
+ async def start(self, command, *, cwd, env, timeout_s, call) -> str:
job_id = f"job_{len(self.starts) + 1}"
self.starts.append(
- dict(
- command=command,
- cwd=cwd,
- env=dict(env),
- timeout_s=timeout_s,
- session_id=session_id,
- tool_call_id=tool_call_id,
- job_id=job_id,
- )
+ dict(command=command, cwd=cwd, env=dict(env), timeout_s=timeout_s, call=call, job_id=job_id)
)
self.states[job_id] = JobStatus("running")
self.outputs[job_id] = b""
diff --git a/tests/agent_core/tools/conftest.py b/tests/agent_core/tools/conftest.py
index ebde6f36a..346470e27 100644
--- a/tests/agent_core/tools/conftest.py
+++ b/tests/agent_core/tools/conftest.py
@@ -8,7 +8,12 @@ from typing import Callable, Optional
import pytest
from core.agent_core.cancel import CancelToken
-from core.agent_core.tools.base import ToolContext
+from core.agent_core.tools.base import CallInstance, ToolContext
+
+
+def instance(tool_call_id: str = "toolu_1", *, response_seq: int = 1) -> CallInstance:
+ """A call of the test Session's response at ``response_seq``; providers may reuse ``tool_call_id`` across them."""
+ return CallInstance("ses_test", f"msg_{response_seq}", response_seq, tool_call_id)
@pytest.fixture
@@ -23,6 +28,7 @@ def make_ctx(tmp_path) -> Callable[..., ToolContext]:
return ToolContext(
session_id="ses_test",
tool_call_id=tool_call_id,
+ call=instance(tool_call_id),
cwd=cwd or str(tmp_path),
env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
cancel=cancel or CancelToken(),
diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.py
index 6af8e8c50..06888d7ec 100644
--- a/tests/agent_core/tools/test_bash.py
+++ b/tests/agent_core/tools/test_bash.py
@@ -19,7 +19,7 @@ import core.agent_core.tools.bash as bash_module
from core.agent_core.tools.bash import BashTool, settle_bash_call
import core.agent_core.tools.jobs as jobs_module
from core.agent_core.tools.jobs import LocalJobHost
-from tests.agent_core.tools.conftest import result_text
+from tests.agent_core.tools.conftest import instance, result_text
LABEL = "Output log (first 1.0MB, then the last 2.0MB in tail.log beside it)"
@@ -147,7 +147,7 @@ async def test_only_the_recorded_reason_makes_a_gone_job_a_timeout(tmp_path, mak
job_id = None
while job_id is None or not os.path.exists(os.path.join(host.job_dir(job_id), "pid")):
await asyncio.sleep(0.01)
- job_id = job_id or host.find_job("ses_test", "toolu_1")
+ job_id = job_id or host.find_job(instance())
# The wrapper cannot write its tail snapshot once the head is full, as on a full disk.
wrapper_pid = open(os.path.join(host.job_dir(job_id), "pid")).read().strip()
os.mkdir(os.path.join(host.job_dir(job_id), f"tail.log.{wrapper_pid}.tmp"))
@@ -260,15 +260,14 @@ async def test_only_a_live_wrapper_decides_at_the_deadline(tmp_path, make_ctx, m
job_id = None
while job_id is None:
await asyncio.sleep(0.01)
- job_id = host.find_job("ses_test", "toolu_1")
+ job_id = host.find_job(instance())
else:
job_id = await host.start(
command,
cwd=str(tmp_path),
env={"PATH": os.environ["PATH"]},
timeout_s=60,
- session_id="ses_test",
- tool_call_id="toolu_1",
+ call=instance(),
)
running = asyncio.ensure_future(host.wait(job_id, deadline_s=None))
wrapper_pid = os.path.join(host.job_dir(job_id), "pid")
@@ -353,8 +352,7 @@ async def test_a_handover_shows_the_latest_output_however_much_came_before(tmp_p
cwd=str(tmp_path),
env={"PATH": os.environ["PATH"]},
timeout_s=None,
- session_id="ses_test",
- tool_call_id="toolu_1",
+ call=instance(),
)
tail = os.path.join(host.job_dir(job_id), "tail.log")
try:
@@ -363,7 +361,7 @@ async def test_a_handover_shows_the_latest_output_however_much_came_before(tmp_p
break
await asyncio.sleep(0.02)
- result = await settle_bash_call(host, "ses_test", "toolu_1")
+ result = await settle_bash_call(host, instance())
text = result_text(result)
assert text.startswith("Command is still running and is now Watch wch_1.")
@@ -487,17 +485,17 @@ async def test_settlement_reports_each_job_state(tmp_path, make_ctx):
recovery = LocalJobHost(str(tmp_path / "jobs"), on_hand_over=watches)
- exited = await settle_bash_call(recovery, "ses_test", "exited")
+ exited = await settle_bash_call(recovery, instance("exited"))
assert (result_text(exited), exited.is_error) == (result_text(foreground), True)
- running = await settle_bash_call(recovery, "ses_test", "running")
+ running = await settle_bash_call(recovery, instance("running"))
assert result_text(running).startswith("Command is still running and is now Watch wch_1.")
# Settling again adopts the same Watch. (The output may still be arriving, so only the Watch is compared.)
- again = await settle_bash_call(recovery, "ses_test", "running")
+ again = await settle_bash_call(recovery, instance("running"))
assert result_text(again).startswith("Command is still running and is now Watch wch_1.")
assert again.details["watch_id"] == running.details["watch_id"] == "wch_1"
- assert await settle_bash_call(recovery, "ses_test", "unknown") is None
+ assert await settle_bash_call(recovery, instance("unknown")) is None
await recovery.kill(running.details["job_id"])
- assert await settle_bash_call(recovery, "ses_test", "running") is None
+ assert await settle_bash_call(recovery, instance("running")) is None
async def test_a_timeout_holds_across_handover_and_a_restart(tmp_path, make_ctx):
@@ -522,6 +520,6 @@ async def test_a_timeout_holds_across_handover_and_a_restart(tmp_path, make_ctx)
assert status.state == "gone"
assert restarted.stop_reason(job_id) == "timeout"
- settled = await settle_bash_call(restarted, "ses_test", "toolu_1")
+ settled = await settle_bash_call(restarted, instance())
assert result_text(settled) == "begun\n\n\nCommand timed out after 60 seconds"
assert not os.path.exists(os.path.join(restarted.job_dir(job_id), "exit"))
diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.py
index 1e8c144b5..ca3d1efbd 100644
--- a/tests/agent_core/tools/test_jobs.py
+++ b/tests/agent_core/tools/test_jobs.py
@@ -21,6 +21,7 @@ import pytest
import core.agent_core.tools.jobs as jobs_module
from core.agent_core.tools.jobs import JobStartError, LocalJobHost
+from tests.agent_core.tools.conftest import instance
class Crash(Exception):
@@ -31,9 +32,9 @@ def _env():
return {"PATH": os.environ.get("PATH", "/usr/bin:/bin")}
-async def _start(host, cwd, command, *, tool_call_id="toolu_1", timeout_s=None):
+async def _start(host, cwd, command, *, tool_call_id="toolu_1", response_seq=1, timeout_s=None):
return await host.start(
- command, cwd=str(cwd), env=_env(), timeout_s=timeout_s, session_id="ses_test", tool_call_id=tool_call_id
+ command, cwd=str(cwd), env=_env(), timeout_s=timeout_s, call=instance(tool_call_id, response_seq=response_seq)
)
@@ -115,7 +116,7 @@ async def test_a_crash_at_any_launch_step_runs_the_command_at_most_once(tmp_path
monkeypatch.undo()
recovery = LocalJobHost(str(jobs_dir))
- job_id = recovery.find_job("ses_test", "toolu_1")
+ job_id = recovery.find_job(instance())
assert job_id is not None
may_have_started = recovery.started(job_id)
if crash_point != "after_meta_before_spawn":
@@ -141,39 +142,34 @@ async def test_a_wrapper_left_without_a_decision_abandons_and_a_late_host_cannot
with pytest.raises(JobStartError):
await _start(host, tmp_path, f"echo ran >> {tmp_path / 'counter'}")
- job_id = host.find_job("ses_test", "toolu_1")
+ job_id = host.find_job(instance())
assert _wait_until(lambda: _wrapper_gone(host.job_dir(job_id)))
assert not host.started(job_id)
assert _counter(tmp_path) == 0
-async def test_find_job_tells_apart_jobs_a_reused_call_started_within_one_millisecond(tmp_path, monkeypatch):
- import secrets
-
- # The earlier call's job, the later response's commit, and the later call's job, all inside one
- # millisecond; the earlier job's id sorts first, so a tie would pick it.
+async def test_find_job_matches_the_whole_call_instance_whatever_the_clock_says(tmp_path, monkeypatch):
+ """Two responses reuse one call id, and the wall clock steps back an hour between their jobs."""
moments = iter([
- datetime(2026, 10, 4, 4, 30, 0, 123100, tzinfo=timezone.utc),
- datetime(2026, 10, 4, 4, 30, 0, 123700, tzinfo=timezone.utc),
+ datetime(2026, 10, 4, 4, 30, tzinfo=timezone.utc),
+ datetime(2026, 10, 4, 3, 30, tzinfo=timezone.utc),
])
- real_datetime, token_hex = jobs_module.datetime, secrets.token_hex
- class _Clock(real_datetime):
+ class _Clock(jobs_module.datetime):
@classmethod
def now(cls, tz=None):
return next(moments)
- job_ids = iter(["0" * 16, "f" * 16])
monkeypatch.setattr(jobs_module, "datetime", _Clock)
- monkeypatch.setattr(jobs_module.secrets, "token_hex", lambda n=None: next(job_ids) if n == 8 else token_hex(n))
host = LocalJobHost(str(tmp_path / "jobs"))
- earlier = await _start(host, tmp_path, "true", tool_call_id="call_0")
- later = await _start(host, tmp_path, "true", tool_call_id="call_0")
+ earlier = await _start(host, tmp_path, "true", tool_call_id="call_0", response_seq=2)
+ later = await _start(host, tmp_path, "true", tool_call_id="call_0", response_seq=5)
monkeypatch.undo()
- response_committed = datetime(2026, 10, 4, 4, 30, 0, 123400, tzinfo=timezone.utc)
+ assert host.meta(later)["created_at"] < host.meta(earlier)["created_at"]
- assert host.find_job("ses_test", "call_0", created_since=response_committed) == later
- assert host.find_job("ses_test", "call_0") == later
+ assert host.find_job(instance("call_0", response_seq=2)) == earlier
+ assert host.find_job(instance("call_0", response_seq=5)) == later
+ assert host.find_job(instance("call_0", response_seq=8)) is None
assert _wait_until(lambda: all(host.status(job).state != "running" for job in (earlier, later)))
@@ -558,7 +554,7 @@ async def test_a_command_whose_record_would_be_unreadable_never_starts(tmp_path,
if not starts:
with pytest.raises(JobStartError):
await _start(host, tmp_path, command)
- assert host.find_job("ses_test", "toolu_1") is None
+ assert host.find_job(instance()) is None
return
job_id = await _start(host, tmp_path, command)
assert (await host.wait(job_id, deadline_s=5)).state == "exited"
@@ -584,7 +580,7 @@ async def test_a_start_cancelled_before_its_decision_abandons_the_wrapper_at_onc
with pytest.raises(asyncio.CancelledError):
await task
- job_id = host.find_job("ses_test", "toolu_1")
+ job_id = host.find_job(instance())
assert host.started(job_id) is False
assert _wait_until(lambda: _wrapper_gone(host.job_dir(job_id)), timeout_s=5)
assert not (tmp_path / "ran").exists()
@@ -596,9 +592,9 @@ async def test_a_cwd_with_bytes_that_are_not_utf8_is_recorded_and_read_back(tmp_
host = LocalJobHost(str(tmp_path / "jobs"))
with pytest.raises(JobStartError): # the directory does not exist; the record must not be what fails
- await host.start("true", cwd=cwd, env=_env(), timeout_s=None, session_id="ses_test", tool_call_id="toolu_1")
+ await host.start("true", cwd=cwd, env=_env(), timeout_s=None, call=instance())
- assert host.meta(host.find_job("ses_test", "toolu_1"))["cwd"] == cwd
+ assert host.meta(host.find_job(instance()))["cwd"] == cwd
async def test_meta_json_is_read_in_a_bound(tmp_path):
diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.py
index 047365ee5..4b244f468 100644
--- a/tests/test_backend_failure_retry.py
+++ b/tests/test_backend_failure_retry.py
@@ -153,7 +153,7 @@ def _hand_over_the_open_command(engine, session_id, turn_id):
"""The restart left the Turn's bash command running; startup recovery made it a Watch (T2)."""
from core.agent_core.agent.recovery import settle_open_calls
from core.agent_core.messages import ToolCallBlock, UserMessage, text
- from core.agent_core.tools.base import JobStatus, ToolResult
+ from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult
from storage.agent_transcript import SQLiteTranscriptStore
from tests.agent_core.fakes import FakeJobHost, assistant
@@ -168,10 +168,10 @@ def _hand_over_the_open_command(engine, session_id, turn_id):
async def previous_process_then_t2():
await store.consume_input(session_id, input_id, UserMessage((text("run it"),)))
- await store.append_response(session_id, assistant("", calls=(call,)), final=False)
+ response = await store.append_response(session_id, assistant("", calls=(call,)), final=False)
+ instance = CallInstance(session_id, response.row_id, response.context_seq, "call_bash")
await settle_open_calls(
- session_id=session_id, store=store, jobs=jobs,
- job_ids={(session_id, "call_bash"): "job_1"}, render_result=handed_over,
+ session_id=session_id, store=store, jobs=jobs, job_ids={instance: "job_1"}, render_result=handed_over
)
asyncio.run(previous_process_then_t2())
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 57108a67b..ce2731651 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -34,7 +34,7 @@ from core.agent_core.agent.recovery import UNRECORDED_EFFECT
from core.agent_core.ai.provider import Done
from core.agent_core.harness.projection import project
from core.agent_core.messages import AssistantMessage, TextBlock, ToolCallBlock, ToolResultMessage, UserMessage, text
-from core.agent_core.tools.base import JobStatus, ToolResult
+from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest
from modules.agents.vibey import VibeyAgent
@@ -292,7 +292,7 @@ class _Harness:
jobs=self.jobs,
create_tools=lambda jobs, sink: list(self.tools),
render_recovered=_unused_renderer,
- find_job=lambda session_id, call_id, **_: None,
+ find_job=lambda call: None,
)
self.agent = self.new_agent()
self._turns = 0
@@ -847,7 +847,7 @@ async def test_resume_settles_open_calls_and_admits_unconsumed_inputs_before_the
jobs=jobs,
create_tools=lambda jobs_, sink: [FakeTool("bash"), FakeTool("edit")],
render_recovered=render,
- find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ find_job=lambda call: "job_1" if (call.session_id, call.tool_call_id) == (SESSION, "call_bash") else None,
)
harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("resumed"))]], suite=suite)
# The crashed process: a Turn whose response opened two calls, one with a running job,
@@ -1377,8 +1377,7 @@ async def test_the_footer_reports_the_runs_final_outcome(engine, session, tmp_pa
def tools(tracking, sink):
async def start_and_leave(arguments, ctx):
- await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id)
+ await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, call=ctx.call)
return ToolResult((text("started"),))
return [FakeTool("echo", execute=start_and_leave)]
@@ -1424,8 +1423,7 @@ async def test_a_silent_final_whose_run_failed_after_its_commit_is_typed_by_its_
def tools(tracking, sink):
async def start_and_leave(arguments, ctx):
- await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, session_id=ctx.session_id,
- tool_call_id=ctx.tool_call_id)
+ await tracking.start("sleep 600", cwd=ctx.cwd, env={}, timeout_s=None, call=ctx.call)
return ToolResult((text("started"),))
return [FakeTool("echo", execute=start_and_leave)]
@@ -1581,7 +1579,7 @@ async def test_startup_hands_an_orphaned_foreground_job_to_its_watch(engine, ses
jobs=jobs,
create_tools=lambda jobs_, sink: [FakeTool("bash")],
render_recovered=render,
- find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ find_job=lambda call: "job_1" if (call.session_id, call.tool_call_id) == (SESSION, "call_bash") else None,
)
harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
# The crashed process left a running foreground command, and no Turn will resume this
@@ -1628,7 +1626,7 @@ async def test_startup_recovers_a_session_routed_to_another_agent_since(engine,
jobs=jobs,
create_tools=lambda jobs_, sink: [FakeTool("bash")],
render_recovered=render,
- find_job=lambda session_id, call_id, **_: "job_1" if (session_id, call_id) == (SESSION, "call_bash") else None,
+ find_job=lambda call: "job_1" if (call.session_id, call.tool_call_id) == (SESSION, "call_bash") else None,
)
harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
request = harness.request("run the slow suite")
@@ -1908,14 +1906,14 @@ async def test_a_suppressed_committed_row_becomes_a_receipt_when_its_output_is_s
# --- real wiring: the merged tools, job host and Watch hand-over ---------------------------
-async def _real_job(suite, command: str, *, call_id: str, cwd: Path) -> str:
+def _instance(response, call_id: str) -> CallInstance:
+ """Call ``call_id`` of a committed response (its ``ContextEntry``)."""
+ return CallInstance(response.session_id, response.row_id, response.context_seq, call_id)
+
+
+async def _real_job(suite, command: str, *, call: CallInstance, cwd: Path) -> str:
return await suite.jobs.start(
- command,
- cwd=str(cwd),
- env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
- timeout_s=None,
- session_id=SESSION,
- tool_call_id=call_id,
+ command, cwd=str(cwd), env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")}, timeout_s=None, call=call
)
@@ -2039,8 +2037,16 @@ async def test_a_stop_settles_the_running_command_with_its_recorded_reason(engin
request = harness.request("run it")
running = asyncio.create_task(harness.agent.handle_message(request))
- await _until(lambda: suite.find_job(SESSION, "call_bash") is not None, "the command never started")
- job_id = suite.find_job(SESSION, "call_bash")
+
+ def started() -> Optional[str]:
+ # The job of the call the run's committed response made (its call instance).
+ responses = harness.rows("assistant")
+ if not responses:
+ return None
+ return suite.find_job(CallInstance(SESSION, responses[0]["id"], responses[0]["context_seq"], "call_bash"))
+
+ await _until(lambda: started() is not None, "the command never started")
+ job_id = started()
await _until(lambda: b"started" in suite.jobs.output(job_id)[0], "the command printed nothing")
assert await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"})) is True
await running
@@ -2069,9 +2075,9 @@ async def test_resume_settles_a_real_bash_job_through_the_real_renderer(
)
command = "printf done" if state == "exited" else "sleep 30"
call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ response = await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
# The crashed process had started the command; nothing committed its result.
- job_id = await _real_job(suite, command, call_id="call_bash", cwd=tmp_path)
+ job_id = await _real_job(suite, command, call=_instance(response, "call_bash"), cwd=tmp_path)
try:
if state == "exited":
await _until(lambda: suite.jobs.status(job_id).state == "exited", "the command never exited")
@@ -2093,49 +2099,63 @@ async def test_resume_settles_a_real_bash_job_through_the_real_renderer(
await suite.jobs.kill(job_id)
-async def test_resume_settles_a_reused_call_id_from_the_job_its_own_call_started(
+def _clock_behind(hours: float):
+ """The job host's ``datetime`` after the wall clock stepped back (an NTP or manual correction)."""
+ from datetime import datetime, timedelta
+
+ class Behind(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return datetime.now(tz) - timedelta(hours=hours)
+
+ return Behind
+
+
+async def test_resume_settles_a_reused_call_id_from_its_own_instance_whatever_the_clock_says(
engine, session, tmp_path, published, monkeypatch
) -> None:
- import secrets
-
import core.agent_core.tools.jobs as jobs_module
- from core.watches import ManagedWatchStore
+ from core.watches import watch_allows_runtime
- # The earlier call's job id sorts first, so a lookup by (session, call id) alone finds it.
- job_ids, token_hex = iter(["0" * 16, "f" * 16]), secrets.token_hex
- monkeypatch.setattr(jobs_module.secrets, "token_hex", lambda n=None: next(job_ids) if n == 8 else token_hex(n))
- suite = local_tool_suite(str(tmp_path / "jobs"))
- harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
+ harness = _Harness(engine, tmp_path, "avibe", [])
+ harness.agent._tool_suite = None # the adapter's own job host, whose hand-over takes the job's owning Turn
+ suite = harness.agent._tools()
first = harness.request("print it")
harness.controller._native_start(first.context)
await harness.agent.store.consume_input(
SESSION, first.context.platform_specific["delivery_id"], UserMessage((text("print it"),))
)
reused = ToolCallBlock(id="call_0", name="bash", arguments={"command": "printf old"})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(reused,)), final=False)
- old = await _real_job(suite, "printf old", call_id="call_0", cwd=tmp_path)
+ earlier = await harness.agent.store.append_response(SESSION, assistant("", calls=(reused,)), final=False)
+ old = await _real_job(suite, "printf old", call=_instance(earlier, "call_0"), cwd=tmp_path)
await _until(lambda: suite.jobs.status(old).state == "exited", "the first command never exited")
await harness.agent.store.append_tool_result(
SESSION, ToolResultMessage("call_0", "bash", (text("old"),)), details={"job_id": old}
)
await harness.agent.store.append_response(SESSION, assistant("printed"), final=True)
- # The next Turn's provider reuses call_0; the crash leaves its command running.
+ # The next Turn's provider reuses call_0, and the wall clock steps back an hour between that
+ # response's commit and its command's start; the crash leaves the command running.
second = harness.request("wait for it")
harness.controller._native_start(second.context)
await harness.agent.store.consume_input(
SESSION, second.context.platform_specific["delivery_id"], UserMessage((text("wait for it"),))
)
again = ToolCallBlock(id="call_0", name="bash", arguments={"command": "sleep 30"})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(again,)), final=False)
- current = await _real_job(suite, "sleep 30", call_id="call_0", cwd=tmp_path)
+ later = await harness.agent.store.append_response(SESSION, assistant("", calls=(again,)), final=False)
+ with monkeypatch.context() as clock:
+ clock.setattr(jobs_module, "datetime", _clock_behind(hours=1))
+ current = await _real_job(suite, "sleep 30", call=_instance(later, "call_0"), cwd=tmp_path)
try:
- harness.new_agent()
- await harness.agent.recover_runtime_state()
+ agent = harness.new_agent()
+ agent._tool_suite = None
+ await agent.recover_runtime_state()
result = (await harness.context_rows())[-1]
- watch_id = ManagedWatchStore().find_job_watch(current)
- assert result.kind == "tool_result" and watch_id and f"now Watch {watch_id}" in result.message.content[0].text
- assert ManagedWatchStore().find_job_watch(old) is None
+ watch = _job_watch(current)
+ assert result.kind == "tool_result" and f"now Watch {watch.id}" in result.message.content[0].text
+ assert _job_watch(old) is None
+ # The Watch's authority is the Turn the job's own response answers.
+ assert watch.metadata.get("job_watch_authorization") == "local" and watch_allows_runtime(watch)
finally:
await suite.jobs.kill(current)
@@ -2167,11 +2187,8 @@ async def _two_sessions_with_open_calls(engine, tmp_path, suite) -> tuple[_Harne
session_id, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
)
call = ToolCallBlock(id="call_bash", name="bash", arguments={"command": command})
- await harness.agent.store.append_response(session_id, assistant("", calls=(call,)), final=False)
- jobs[session_id] = await suite.jobs.start(
- command, cwd=str(tmp_path), env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
- timeout_s=None, session_id=session_id, tool_call_id="call_bash",
- )
+ response = await harness.agent.store.append_response(session_id, assistant("", calls=(call,)), final=False)
+ jobs[session_id] = await _real_job(suite, command, call=_instance(response, "call_bash"), cwd=tmp_path)
await _until(lambda: suite.jobs.status(jobs["ses_b"]).state == "exited", "ses_b's job never exited")
return harness, jobs[SESSION], jobs["ses_b"]
@@ -2240,7 +2257,7 @@ async def test_two_recovery_passes_racing_on_one_open_call_settle_it_once(engine
suite = ToolSuite(
jobs=jobs, create_tools=lambda jobs_, sink: [FakeTool("bash")], render_recovered=render,
- find_job=lambda session_id, call_id, **_: "job_1",
+ find_job=lambda call: "job_1",
)
harness = _Harness(engine, tmp_path, "avibe", [], suite=suite)
request = harness.request("run it")
@@ -2363,12 +2380,9 @@ async def _remote_turn_with_open_call(
await harness.agent.store.consume_input(SESSION, delivery_id, UserMessage((text("run the release"),)))
harness.agent.store.bind_agent(SESSION, "vibey")
call = ToolCallBlock(id="call_release", name="bash", arguments={"command": "sleep 30"})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ response = await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
harness.agent.store.bind_agent(SESSION, None)
- return await harness.agent._tools().jobs.start(
- "sleep 30", cwd=str(tmp_path), env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
- timeout_s=None, session_id=SESSION, tool_call_id="call_release",
- )
+ return await _real_job(harness.agent._tools(), "sleep 30", call=_instance(response, "call_release"), cwd=tmp_path)
def _job_watch(job_id: str):
@@ -2457,7 +2471,7 @@ async def test_the_default_job_host_lives_in_the_watch_jobs_dir(engine, session,
controller = _Controller(engine, "avibe")
suite = VibeyAgent(controller, engine=engine)._tools()
- job_id = await _real_job(suite, "true", call_id="call_true", cwd=tmp_path)
+ job_id = await _real_job(suite, "true", call=CallInstance(SESSION, "msg_true", 1, "call_true"), cwd=tmp_path)
try:
# vibe stop's stop_all_jobs and the job-Watch sweep both look in this one directory.
assert Path(suite.jobs.output_path(job_id)).is_relative_to(Path(os.path.realpath(agent_jobs_dir())))
@@ -2465,7 +2479,10 @@ async def test_the_default_job_host_lives_in_the_watch_jobs_dir(engine, session,
await _until(lambda: suite.jobs.status(job_id).state != "running", "the job never ended")
-async def test_startup_prunes_only_jobs_whose_call_and_watch_have_settled(engine, session, tmp_path, published) -> None:
+async def test_startup_prunes_only_jobs_whose_call_and_watch_have_settled(
+ engine, session, tmp_path, published, monkeypatch
+) -> None:
+ import core.agent_core.tools.jobs as jobs_module
from core.watches import ManagedWatchStore
suite = local_tool_suite(str(tmp_path / "jobs"))
@@ -2476,19 +2493,26 @@ async def test_startup_prunes_only_jobs_whose_call_and_watch_have_settled(engine
SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run them"),))
)
calls = tuple(ToolCallBlock(id=f"call_{name}", name="bash", arguments={"command": "printf out"}) for name in "abc")
- await harness.agent.store.append_response(SESSION, assistant("", calls=calls), final=False)
+ response = await harness.agent.store.append_response(SESSION, assistant("", calls=calls), final=False)
# d's call is in no committed response, so nothing can ever settle it.
- jobs = {name: await _real_job(suite, "printf out", call_id=f"call_{name}", cwd=tmp_path) for name in "abcd"}
+ jobs = {
+ name: await _real_job(suite, "printf out", call=_instance(response, f"call_{name}"), cwd=tmp_path)
+ for name in "abcd"
+ }
for job_id in jobs.values():
await _until(lambda job_id=job_id: suite.jobs.status(job_id).state == "exited", "a job never exited")
# a and b have durable results and b's Watch still owns it; c's call is still open.
for name in "ab":
- await harness.agent.store.append_tool_result(
+ settled = await harness.agent.store.append_tool_result(
SESSION, ToolResultMessage(f"call_{name}", "bash", (text("ok"),)), details={"job_id": jobs[name]}
)
- # e reuses a's call id after a's result committed (a model call apart): a's result does not settle it.
- await asyncio.sleep(0.01)
- jobs["e"] = await _real_job(suite, "printf out", call_id="call_a", cwd=tmp_path)
+ # e is the next response's call, which reuses a's id, started after the wall clock stepped back
+ # behind a's result: that earlier result does not settle it.
+ with monkeypatch.context() as clock:
+ clock.setattr(jobs_module, "datetime", _clock_behind(hours=1))
+ jobs["e"] = await _real_job(
+ suite, "printf out", call=CallInstance(SESSION, "msg_next", settled.context_seq + 1, "call_a"), cwd=tmp_path
+ )
await _until(lambda: suite.jobs.status(jobs["e"]).state == "exited", "a job never exited")
await suite.jobs.hand_over(jobs["b"])
assert ManagedWatchStore().job_watch_settled(jobs["b"]) is False
@@ -2518,8 +2542,8 @@ async def test_a_running_service_prunes_settled_jobs_after_its_runs(engine, sess
SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("run it"),))
)
call = ToolCallBlock(id="call_old", name="bash", arguments={"command": "printf out"})
- await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
- job_id = await _real_job(suite, "printf out", call_id="call_old", cwd=tmp_path)
+ response = await harness.agent.store.append_response(SESSION, assistant("", calls=(call,)), final=False)
+ job_id = await _real_job(suite, "printf out", call=_instance(response, "call_old"), cwd=tmp_path)
await _until(lambda: suite.jobs.status(job_id).state == "exited", "the job never exited")
await harness.agent.store.append_tool_result(
SESSION, ToolResultMessage("call_old", "bash", (text("out"),)), details={"job_id": job_id}
diff --git a/tests/test_watch_job_target.py b/tests/test_watch_job_target.py
index f0878cec6..4cef0e463 100644
--- a/tests/test_watch_job_target.py
+++ b/tests/test_watch_job_target.py
@@ -26,6 +26,7 @@ from sqlalchemy import insert
from config import paths
from core import watches as watches_module
+from core.agent_core.tools.base import CallInstance
from core.agent_core.tools.jobs import LocalJobHost
from core.scheduled_tasks import TaskExecutionStore
from core.watches import (
@@ -94,8 +95,7 @@ async def _start_job(host: LocalJobHost, cwd: Path, command: str, *, timeout_s=N
cwd=str(cwd),
env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},
timeout_s=timeout_s,
- session_id=SESSION_ID,
- tool_call_id=tool_call_id,
+ call=CallInstance(SESSION_ID, "msg_1", 1, tool_call_id),
)