From def51f81dc65cd7d4c16a9a2065972537954841a Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Sat, 10 Oct 2026 08:33:59 +0000 Subject: [PATCH] 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. --- AGENTS.md | 14 ++- config.example.json | 2 + semif_agent/decisions.py | 18 ++++ semif_agent/scheduler.py | 90 ++++++++++++++++++ semif_agent/skill.py | 4 + semif_agent/skills.py | 31 ++++++- tests/test_skills.py | 196 ++++++++++++++++++++++++++++++++++++++- 7 files changed, 351 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fab0b01..eb59fd9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,6 +91,13 @@ scheduler.py no up-front gate: every input is dispatched (retry/repair_skill/ask_user/no_repair) surfaced to the user, while a `continue` step is re-dispatched into next-step routing with a bounded run ledger (the chained multi-step path); + a completed real-skill run's ledger is also held in memory per + origin source for `query_recall_window` seconds (0 disables), so a + follow-up request in the same chat arrives with it as + `prior_ledger` (a `previous request` context block) and can refer + to the prior result — kept separate from `run_ledger` so a + recall never skips the actionability guard or feeds the + monotonic-progress guard; housekeeping meta skills (delete/clear-config/regen/cancel-build) operate on the tree via `ctx.admin`; new-skill creation is gated by a tri-state mode (`new_skill_creation`: allow/deny/ask) with a @@ -130,7 +137,12 @@ skills.py tree + registry (hardcoded built-ins: the closed `response` canned parses a free-form request for a category.skill or bare name; parse_meta_command recognizes explicit housekeeping commands and the meta skills resolve or ask for their target as an input - variable + variable; compose_state / render_ledger / render_recall render + the steps already taken (and, for a follow-up within + `query_recall_window`, the recalled `prior_ledger` as a `previous + request` block) into the routing/assessment state, and + last_result returns the last run-ledger (or recalled) outcome a + chained body can reuse instead of recomputing skill.py loop: observe -> act -> observe -> assess; the body is a single act(ctx, request) phase that returns ActionResult (its own SemIf sub-decisions ride on ActionResult.decisions and are diff --git a/config.example.json b/config.example.json index bb69284..b961189 100644 --- a/config.example.json +++ b/config.example.json @@ -2,6 +2,8 @@ "_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.", "tau": 0.6, "max_reentries": 3, + "query_recall_window": 30, + "_query_recall_window_comment": "Seconds a completed run stays recallable to a follow-up request in the same chat/source. A follow-up within the window is given the previous run's ledger as 'previous request' context (and bodies can reuse its result via last_result), so a reference like \"send it to Sam\" resolves against what the agent just did. 0 disables recall entirely. Measured from the previous run's completion; only the last completed real skill run per source is remembered (canned responses and housekeeping meta skills are never recalled).", "new_skill_creation": "allow", "_new_skill_creation_comment": "Global new-skill creation mode: \"allow\" (create without asking), \"deny\" (never author new skills/categories), or \"ask\" (author only after the human approves the proposal). A category can override this in data/skills//config.json with its own \"new_skill_creation\" value; the built-in housekeeping and response categories are always denied in code.", "verbosity": "result", diff --git a/semif_agent/decisions.py b/semif_agent/decisions.py index adae0dc..1e10bf6 100644 --- a/semif_agent/decisions.py +++ b/semif_agent/decisions.py @@ -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, ) diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 7be44b4..9134155 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -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 diff --git a/semif_agent/skill.py b/semif_agent/skill.py index 928eb95..b459954 100644 --- a/semif_agent/skill.py +++ b/semif_agent/skill.py @@ -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}" diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 9686162..3dd7e98 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -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}" diff --git a/tests/test_skills.py b/tests/test_skills.py index 5458914..f68d060 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -49,8 +49,10 @@ from semif_agent.skills import ( confirm_skill_fit, category_descriptions, CATEGORY_DESCRIPTIONS, + compose_state, generate_category, generate_skill, + last_result, merge_registry, merge_seed_store, merge_skill_store, @@ -130,7 +132,8 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]: return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" -def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosity=None): +def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosity=None, + recall_window=None): """A scheduler driven by the deterministic scripted engine (conftest) so scheduling/authoring mechanics are testable without a GGUF. Assessment is a SemIf decision now, so a run needs the engine to answer `assess:*`.""" @@ -142,6 +145,8 @@ def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosit } if verbosity is not None: config["verbosity"] = verbosity + if recall_window is not None: + config["query_recall_window"] = recall_window return Scheduler( engine=ScriptedEngine(choices=choices, default=default), llm=LLMClient(base_url="http://localhost:1/v1", model="test"), @@ -2199,6 +2204,195 @@ def test_continue_routes_next_step_carries_ledger(tmp_path): assert any(e["kind"] == "continued" for e in scheduler.trace.read()) +def _completed(skill_name="calculator.calculate", log="255 * 12 = 3060"): + category, name = skill_name.split(".", 1) + skill = Skill( + name=name, + category=category, + description="Do arithmetic.", + act=lambda ctx, request: ActionResult(action_log=log, new_state=log), + ) + outcome = RunResult( + skill=skill_name, + success=True, + summary=f"{skill_name}: ok — {log}", + action_log=log, + new_state=log, + outcome="done", + ) + return skill, outcome + + +def test_recall_records_and_attaches_recent_run(tmp_path): + """A completed real run is remembered per source; a follow-up within the + window gets its ledger as `prior_ledger`, rendered as a 'previous request' + block and exposed to bodies via last_result.""" + scheduler = _scheduler(tmp_path) + assert scheduler.query_recall_window == 30 + skill, outcome = _completed() + first = Request("what is 255*12?", source="typed") + first.origin_source = "typed" + scheduler._record_recall(skill, first, outcome) + + follow = Request("send that to Sam", source="typed") + follow.origin_source = "typed" + scheduler._attach_recall(follow) + + assert follow.prior_ledger == [ + { + "query": "what is 255*12?", + "skill": "calculator.calculate", + "outcome": "255 * 12 = 3060", + } + ] + assert follow.prior_at > 0 + assert last_result(follow) == "255 * 12 = 3060" + state = compose_state(follow) + assert "previous request" in state + assert "calculator.calculate -> 255 * 12 = 3060" in state + assert any(e["kind"] == "recall_used" for e in scheduler.trace.read()) + + +def test_recall_window_zero_disables(tmp_path): + """`query_recall_window: 0` remembers nothing and recalls nothing.""" + scheduler = _scheduler(tmp_path, recall_window=0) + skill, outcome = _completed() + first = Request("what is 255*12?", source="typed") + first.origin_source = "typed" + scheduler._record_recall(skill, first, outcome) + assert scheduler._recall == {} + + follow = Request("send that to Sam", source="typed") + follow.origin_source = "typed" + scheduler._attach_recall(follow) + assert follow.prior_ledger == [] + assert not any(e["kind"] == "recall_used" for e in scheduler.trace.read()) + + +def test_recall_expired_is_not_attached_and_pruned(tmp_path): + """A run older than the window is not recalled, and its stale memory is + dropped.""" + scheduler = _scheduler(tmp_path, recall_window=30) + skill, outcome = _completed() + first = Request("what is 255*12?", source="typed") + first.origin_source = "typed" + scheduler._record_recall(skill, first, outcome) + scheduler._recall["typed"]["completed_at"] = time.time() - 100 + + follow = Request("send that to Sam", source="typed") + follow.origin_source = "typed" + scheduler._attach_recall(follow) + assert follow.prior_ledger == [] + assert "typed" not in scheduler._recall + + +def test_recall_is_per_source(tmp_path): + """Two chats do not recall each other's runs.""" + scheduler = _scheduler(tmp_path) + skill, outcome = _completed() + first = Request("what is 255*12?", source="gateway:a") + first.origin_source = "gateway:a" + scheduler._record_recall(skill, first, outcome) + + other = Request("send that to Sam", source="gateway:b") + other.origin_source = "gateway:b" + scheduler._attach_recall(other) + assert other.prior_ledger == [] + + same = Request("send that to Sam", source="gateway:a") + same.origin_source = "gateway:a" + scheduler._attach_recall(same) + assert same.prior_ledger and same.prior_ledger[-1]["outcome"] == "255 * 12 = 3060" + + +def test_recall_excludes_canned_and_housekeeping(tmp_path): + """The canned `response` tree and the housekeeping meta skills are never + remembered (a greeting must not occupy the recall slot).""" + scheduler = _scheduler(tmp_path) + for category in ("response", "housekeeping"): + skill = Skill( + name="x", + category=category, + description="d", + act=lambda ctx, request: ActionResult("line", "line"), + ) + outcome = RunResult( + skill=f"{category}.x", success=True, summary="ok", + action_log="line", new_state="line", outcome="done", + ) + req = Request("hi", source="typed") + req.origin_source = "typed" + scheduler._record_recall(skill, req, outcome) + assert scheduler._recall == {} + + +def test_finish_run_records_terminal_but_not_intermediate(tmp_path): + """`_finish_run` records a terminal run, records a failure, but does not + record an intermediate `continue` (the child records the full ledger).""" + scheduler = _scheduler(tmp_path) + skill, outcome = _completed(skill_name="tracking.check", log="opened") + done = Request("track my package", source="typed") + done.origin_source = "typed" + scheduler._finish_run(skill, done, outcome) + assert scheduler._recall["typed"]["ledger"][-1]["skill"] == "tracking.check" + + # An intermediate continue is re-dispatched, not recorded as terminal. + scheduler._recall.clear() + cont = Request("track my package", source="typed") + cont.origin_source = "typed" + cont_outcome = RunResult( + skill="tracking.check", success=True, summary="ok", + action_log="opened", new_state="opened", outcome="continue", + ) + result = scheduler._finish_run(skill, cont, cont_outcome) + assert result.intermediate is True + assert scheduler._recall == {} + + # A failure is remembered too (a follow-up can refer to what failed). + scheduler._recall.clear() + failed = Request( + "check my inbox", source="typed" + ) + failed.origin_source = "typed" + err = RunResult( + skill="mail.check", success=False, summary="", + action_log="", new_state="", error="bridge refused", outcome="failed", + ) + scheduler._finish_run( + Skill(name="check", category="mail", description="d", + act=lambda ctx, r: ActionResult("", "")), + failed, + err, + ) + assert scheduler._recall["typed"]["ledger"][-1]["outcome"] == "bridge refused" + + +def test_continue_carries_recall_context(tmp_path): + """A chained continuation keeps the recalled previous-request context and + the origin source.""" + scheduler = _scheduler(tmp_path) + request = Request("send that to Sam", source="typed") + request.origin_source = "gateway:a" + request.prior_ledger = [ + {"query": "what is 255*12?", "skill": "calculator.calculate", "outcome": "3060"} + ] + request.prior_at = 123.0 + scheduler._finish_run( + Skill(name="send_message", category="simplex", description="d", + act=lambda ctx, r: ActionResult("sent", "sent")), + request, + RunResult( + skill="simplex.send_message", success=True, summary="ok", + action_log="sent", new_state="sent", outcome="continue", + ), + ) + child = scheduler.queue.pop() + assert child is not None + assert child.origin_source == "gateway:a" + assert child.prior_ledger == request.prior_ledger + assert child.prior_at == 123.0 + + def test_capped_continue_halts_chain_not_repair(tmp_path): """A `continue` with the step budget spent stops the chain (it worked, so no repair offer) rather than looping."""