recall the previous run's ledger for a follow-up within query_recall_window

A completed real-skill run's ledger is held in memory per origin source
for query_recall_window seconds (default 30, 0 disables). A follow-up
request in the same chat arrives with it as prior_ledger -- rendered as a
'previous request' context block in navigation/assessment state and
exposed to bodies via last_result -- so a reference like 'send it to Sam'
resolves against what the agent just did.

Kept separate from run_ledger: recall is not an in-flight continuation,
so it never skips the actionability guard nor feeds the monotonic-progress
guard. Only terminal real-skill runs are remembered (canned responses and
housekeeping meta skills excluded); the final step is synthesized as a
ledger entry since a single-step run's own run_ledger is empty.
This commit is contained in:
gabby committed 2026-10-10 08:33:59 +00:00
1 parent ab0defca1e
commit def51f81dc
7 files changed
+351 -4

No files matched your search

+18
View File
@@ -66,6 +66,10 @@ class Request:
text: str
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
source: str = "typed"
#: The originating source/chat, threaded through a continued chain (whose
#: own `source` becomes "continue"). Recall memory is keyed by this so a
#: follow-up in one chat never recalls another chat's run.
origin_source: str = ""
meta: dict[str, Any] = field(default_factory=dict)
received_at: float = field(default_factory=time.time)
priority: float = 0.5
@@ -79,16 +83,30 @@ class Request:
#: request. Bounded by construction (each outcome is bounded to the
#: speakable budget, and the chain is capped).
run_ledger: list[dict[str, Any]] = field(default_factory=list)
#: The previous *completed* run's ledger, recalled when this request arrived
#: within `query_recall_window` seconds of it (per origin source). Rendered
#: as a "previous request" context block and exposed to bodies via
#: `last_result`, so a follow-up can refer to the prior result ("send it to
#: Sam"). Deliberately separate from `run_ledger`: recall is not an in-flight
#: continuation, so it must not skip the actionability guard nor feed the
#: monotonic-progress guard. Empty when there is nothing to recall.
prior_ledger: list[dict[str, Any]] = field(default_factory=list)
#: Completion time of the recalled run (for the "Ns ago" label); 0.0 when
#: there is no recall.
prior_at: float = 0.0
def copy_for_requeue(self) -> "Request":
return Request(
text=self.text,
id=self.id,
source=self.source,
origin_source=self.origin_source,
meta=dict(self.meta),
received_at=self.received_at,
priority=self.priority,
reentries=self.reentries + 1,
resume=dict(self.resume),
run_ledger=[dict(entry) for entry in self.run_ledger],
prior_ledger=[dict(entry) for entry in self.prior_ledger],
prior_at=self.prior_at,
)
+90
View File
@@ -54,6 +54,7 @@ from .skills import (
SkillDraft,
SkillStore,
apply_tombstones,
bound_output,
build_housekeeping_skills,
build_skills,
build_tree,
@@ -312,6 +313,13 @@ class Scheduler:
#: is truncated to this many characters at a word boundary.
chain_cfg = config.get("chain", {}) or {}
self.result_chars = int(chain_cfg.get("result_chars", 300))
#: Seconds a completed run stays recallable for a follow-up request in
#: the same chat/source. A follow-up within the window gets the prior
#: run's ledger as context so it can refer to it ("send it to Sam"); 0
#: disables recall entirely. Measured from the prior run's completion.
self.query_recall_window = max(
0.0, float(config.get("query_recall_window", 30) or 0)
)
#: The `assess:outcome` thresholds (precedence failed > done > continue).
assess_cfg = config.get("assess", {}) or {}
self.done_tau = float(assess_cfg.get("done_tau", 0.5))
@@ -397,6 +405,11 @@ class Scheduler:
self._repair_counts: dict[str, int] = {}
self._approval_notify = threading.Condition(self._lock)
self.approvals: list[PendingApproval] = []
#: Per-origin-source memory of the last completed run's ledger, keyed by
#: `Request.origin_source`: {"ledger": [...], "completed_at": float}. A
#: follow-up within `query_recall_window` recalls it. Only real skills
#: are recorded (not the canned `response` tree or housekeeping).
self._recall: dict[str, dict] = {}
# ---- fatal handling ----
@@ -438,7 +451,9 @@ class Scheduler:
def _submit_locked(self, text: str, source: str = "typed") -> SchedulerReply:
request = Request(text, source=source)
request.origin_source = source
self.trace.append("submit", request.id, text=text, source=source)
self._attach_recall(request)
if self.current is None:
self.current = Process(request=request, skill="(scheduling)")
@@ -468,6 +483,73 @@ class Scheduler:
self.trace.append("queued", request.id)
return SchedulerReply("queued", "queued", request.id)
# ---- previous-run recall ----
def _attach_recall(self, request: Request) -> None:
"""Give a fresh request the last completed run's ledger if it is recent.
Recall is per origin source and bounded by `query_recall_window`; a
request that arrives in time gets the prior ledger as context so it can
refer to it. It is attached as `prior_ledger` (never `run_ledger`): the
follow-up is not an in-flight continuation, so the actionability guard
must still run and the monotonic-progress guard must not see it.
"""
if self.query_recall_window <= 0:
return
source = request.origin_source or request.source
memory = self._recall.get(source)
if not memory:
return
age = time.time() - float(memory.get("completed_at", 0.0))
if age > self.query_recall_window:
self._recall.pop(source, None)
return
request.prior_ledger = [dict(e) for e in memory.get("ledger", [])]
request.prior_at = float(memory.get("completed_at", 0.0))
self.trace.append(
"recall_used",
request.id,
source=source,
age=round(age, 1),
steps=len(request.prior_ledger),
)
def _record_recall(self, skill: Skill, request: Request, outcome) -> None:
"""Remember a completed run's ledger for a later follow-up.
Keys on the origin source and stamps completion time. Real skills only:
the canned `response` tree and the deterministic `housekeeping` meta
skills are not recorded (a greeting should not occupy the recall slot).
The final step is synthesized as a ledger entry because a single-step
run's own `run_ledger` is empty — without it there would be nothing to
recall.
"""
if self.query_recall_window <= 0:
return
if (
skill.category in CANNED_CATEGORIES
or skill.category in DETERMINISTIC_CATEGORIES
):
return
outcome_text = (
outcome.action_log
or outcome.new_state
or outcome.summary
or outcome.error
or ""
)
entry = {
"query": request.text,
"skill": f"{skill.category}.{skill.name}",
"outcome": bound_output(outcome_text, self.result_chars),
}
ledger = [dict(e) for e in request.run_ledger] + [entry]
source = request.origin_source or request.source
self._recall[source] = {
"ledger": ledger,
"completed_at": time.time(),
}
def busy(self, text: str, skill: str = "(driving)") -> None:
"""Set a fake in-progress process so the queue path is exercised."""
with self._lock:
@@ -806,6 +888,7 @@ class Scheduler:
"error", request.id, skill=skill.name, message=outcome.error
)
self._propose_repair(skill, request, outcome)
self._record_recall(skill, request, outcome)
return DispatchResult(kind="error", summary=f"skill error: {outcome.error}")
if outcome.needs_input:
self.pending = PendingRun(
@@ -878,6 +961,7 @@ class Scheduler:
skill=entry["skill"],
reason="repeat" if repeat else "budget",
)
self._record_recall(skill, request, outcome)
return DispatchResult(
kind="ran",
summary=outcome.summary,
@@ -888,6 +972,7 @@ class Scheduler:
)
if verdict == "failed":
self._propose_repair(skill, request, outcome)
self._record_recall(skill, request, outcome)
return DispatchResult(
kind="ran",
summary=outcome.summary,
@@ -2454,9 +2539,14 @@ def _continue(request: Request, entry: dict) -> Request:
config answers must not leak forward).
"""
updated = Request(request.text, source="continue")
updated.origin_source = request.origin_source or request.source
updated.reentries = request.reentries + 1
updated.meta["parent_run"] = request.id
updated.run_ledger = [dict(e) for e in request.run_ledger] + [dict(entry)]
# Carry any recalled previous-request context forward so the whole new chain
# keeps the reference the follow-up was resolved against.
updated.prior_ledger = [dict(e) for e in request.prior_ledger]
updated.prior_at = request.prior_at
return updated
+4
View File
@@ -39,6 +39,7 @@ from .skills import (
SkillStore,
bound_output,
render_ledger,
render_recall,
resolve_skill_config,
unresolved_variables,
)
@@ -345,6 +346,9 @@ class SkillRunner:
f"resolved inputs:\n{resolved}\n"
f"action log:\n{observed}"
)
recall = render_recall(request)
if recall:
state += f"\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"
+29 -2
View File
@@ -17,6 +17,7 @@ import json
import os
import re
import shutil
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
@@ -607,25 +608,48 @@ def render_ledger(entries: list[dict]) -> str:
def last_result(request: Request) -> str:
"""The most recent chained step's result, or "" on a first-step request.
"""The most recent result this run can build on.
A body that runs as a later step of a chain reads this to use what the
previous step produced (e.g. a computed value to send) instead of
recomputing or fabricating it. The value is the prior step's bounded outcome
(its ``action_log`` or ``new_state``) — the same text the run ledger carries
and renders into the routing/assessment state.
When the current chain has no steps yet, it falls back to the recalled
previous request's last outcome (a follow-up within ``query_recall_window``),
so "send it to Sam" can reuse the answer the agent just gave.
"""
ledger = getattr(request, "run_ledger", None) or []
if not ledger:
return ""
ledger = getattr(request, "prior_ledger", None) or []
return str(ledger[-1].get("outcome") or "") if ledger else ""
return str(ledger[-1].get("outcome") or "")
def render_recall(request: Request) -> str:
"""Render the recalled previous request's ledger as a compact context block.
Distinct from `render_ledger`/`run_ledger`: recall is background context for
resolving a reference in the current request, not a step of the current
chain. Returns "" when there is nothing to recall.
"""
entries = getattr(request, "prior_ledger", None) or []
if not entries:
return ""
prior_at = getattr(request, "prior_at", 0.0) or 0.0
age = f" ({int(max(0.0, time.time() - prior_at))}s ago)" if prior_at else ""
return f"previous request{age}:\n{render_ledger(entries)}"
def compose_state(request: Request, additional_context: str | None = None) -> str:
parts = [request.text]
if additional_context:
parts.append(f"({additional_context})")
state = " ".join(parts)
recall = render_recall(request)
if recall:
state = f"{state}\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state = f"{state}\nsteps already taken:\n{ledger}"
@@ -1572,6 +1596,9 @@ def confirm_skill_fit(
f"Requested action: {request.text}\n"
f"Action of the existing skill: {skill.description}"
)
recall = render_recall(request)
if recall:
state += f"\n{recall}"
ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"