Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Add a model-free work ledger after the summary (#44)

Elevatormusica6df7a3c957b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 391969a..e795045 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
## [Unreleased]
+### Added
+
+- Add a work ledger after the summary: the commands that ran, with their exit codes and first error lines, and the files that tools changed. Code writes it from the tool calls and results; no model writes it. A later compaction keeps the earlier ledger lines. Setting `ledger` (default true).
+
### Changed
- Give fallback generation an 8,192-token allowance while keeping the visible summary within 2,048 estimated tokens. Check a fresh end marker and the summary content instead of refusing a short reply because its reported output count can include thinking. Retry an invalid reply once from the original transcript, within a shared deadline and cancellation checks. The public API still cannot report the server stop reason or stop an in-flight call.
diff --git a/README.md b/README.md
index 1879064..2f6af8f 100644
--- a/README.md
+++ b/README.md
@@ -68,6 +68,8 @@ Run these commands in a terminal (PowerShell, Terminal, or any shell) where the
At each compaction, the plugin sends the last main-model request of the session again. It adds the rows that came after that request and one handoff instruction at the end. This is the *warm request*. The server can reuse the cached prefix of the earlier request, so it reads only the new rows. The reply is a Markdown handoff with five headings: Goal, User instructions, Current state, Key facts, and Next step. The plugin replaces the older rows with the handoff and keeps a verbatim tail of recent rows.
+After the handoff, the plugin adds a **work ledger**. Code writes the ledger from the tool calls and tool results before the tail; no model writes it. It has two lists: the commands that ran, each with its exit code (or `exit unknown`) and the first error line of its output, and the files that tools wrote, changed, moved, or deleted. A failed edit, or an edit without a result, is listed as a tool call, not as a changed file. Reads are not listed. A later compaction keeps the ledger lines of the earlier summary and adds the new ones. The ledger uses the summary budget that the handoff leaves, at most 1,000 estimated tokens; when it is too large, the oldest commands go first, then the oldest files. It is reference data for the next request, not a list of tasks. Set `ledger: false` to turn it off.
+
If the warm request cannot run, or if its reply fails the gate, the same compaction attempt uses a model-based fallback summary through the Hermes auxiliary route. If neither path produces a usable summary, the plugin stops the current compaction pass, preserves its original input history, and reports an error with safe codes only. It never creates a summary without a model. Hermes can retry an automatic failure; the plugin cannot stop the entire host turn through its documented API. When Hermes cancels an attempt, the history stays unchanged.
The plugin does this for manual `/compress` and for automatic compaction.
@@ -169,6 +171,7 @@ The settings are in `plugins.entries.warm_compaction.settings`. An invalid value
| `warm` | bool | true | Set false to use only the fallback summary, for comparison runs |
| `summary_words` | int, 1 or more | 600 | Word count the handoff instruction asks for. It applies to the warm request and the fallback summary. A larger value records more of a long session. The task, not this value, controls the final reply size |
| `warm_providers` | text | empty: every provider | Comma-separated provider names that may use the warm path. A provider outside the list sends no warm request, so a route that can miss its prefix cache does not pay for the whole prompt. Names are matched without case. An empty value keeps every provider |
+| `ledger` | bool | true | Add the work ledger (commands with exit codes and first error lines, changed files) after the summary. Set false for comparison runs |
```yaml
plugins:
diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.py
index afadab0..868ad37 100644
--- a/tests/test_wc_engine.py
+++ b/tests/test_wc_engine.py
@@ -1862,6 +1862,51 @@ class EngineTest(unittest.TestCase):
self.assertIn("Use at most 1200 words.", sent)
self.assertNotIn("600 words", sent)
+ def ledger_rows(self):
+ # Synthetic work before the tail: one failed command and one file change.
+ return [user("Synthetic task: fix the timeout test."),
+ assistant("", [("c1", "terminal", json.dumps({"command": "pytest -q"}))]),
+ tool("c1", json.dumps({"output": "FAILED tests/test_api.py::test_timeout - AssertionError: 30 != 60",
+ "exit_code": 1, "error": None})),
+ assistant("", [("c2", "patch", json.dumps({"path": "src/api.py", "old_string": "30",
+ "new_string": "60"}))]),
+ tool("c2", json.dumps({"success": True})),
+ *old_turns()]
+
+ def summary_text(self, new):
+ return "\n".join(str(row.get("content")) for row in new if row.get("_compressed_summary"))
+
+ def test_the_work_ledger_is_in_the_summary_on_both_paths(self):
+ from warm_compaction import ledger
+ for warm in (True, False):
+ with self.subTest(warm=warm):
+ engine = self.make(warm=warm)
+ rows, reply = self.ledger_rows(), assistant("final")
+ if warm:
+ self.seed(rows, reply)
+ new = engine.compress([*rows, reply])
+ self.assertEqual(engine.warm_last["path"], "warm" if warm else "fallback")
+ text = self.summary_text(new)
+ self.assertIn(ledger.HEADING, text)
+ self.assertIn("- `pytest -q`: exit 1; FAILED tests/test_api.py::test_timeout", text)
+ self.assertIn("- src/api.py: changed", text)
+ self.assertLess(text.index(ledger.HEADING), text.index("## Copied user messages"))
+
+ def test_the_ledger_setting_false_keeps_the_summary_without_a_ledger(self):
+ from warm_compaction import ledger
+ engine = self.make(warm=False, ledger=False)
+ rows = self.ledger_rows()
+ new = engine.compress([*rows, assistant("final")])
+ self.assertEqual(engine.warm_last["path"], "fallback")
+ self.assertNotIn(ledger.HEADING, self.summary_text(new))
+
+ def test_the_ledger_uses_only_the_summary_budget_that_is_left(self):
+ from warm_compaction import ledger
+ engine = self.make(warm=False)
+ engine._summary_budget = lambda *args, **kwargs: 0
+ new = engine.compress([*self.ledger_rows(), assistant("final")])
+ self.assertNotIn(ledger.HEADING, self.summary_text(new))
+
def test_a_provider_outside_the_list_skips_the_warm_request(self):
# The route is kept out of the warm path: no warm request is sent, and the fallback summary runs.
engine = self.make(warm_providers="opencode-go,commandcode")
@@ -2239,16 +2284,16 @@ class SettingsTest(unittest.TestCase):
def test_valid_values(self):
values = {"threshold": 0.6, "tail_tokens": 12_000, "user_copy_chars": 0, "warm": False,
- "summary_words": 1200, "warm_providers": "opencode-go,commandcode"}
+ "summary_words": 1200, "warm_providers": "opencode-go,commandcode", "ledger": False}
self.assertEqual(self.module.read_settings(lambda key, default: values.get(key, default)), values)
def test_invalid_values_use_the_defaults_with_a_warning(self):
values = {"threshold": 2.0, "tail_tokens": -1, "user_copy_chars": "big", "warm": "no",
- "summary_words": 0, "warm_providers": 7}
+ "summary_words": 0, "warm_providers": 7, "ledger": "yes"}
with self.assertLogs("warm_compaction.engine", level="WARNING") as logs:
settings = self.module.read_settings(lambda key, default: values.get(key, default))
self.assertEqual(settings, self.module.DEFAULTS)
- self.assertEqual(len(logs.output), 6)
+ self.assertEqual(len(logs.output), 7)
def test_a_word_count_below_one_uses_the_default(self):
def reader(values):
diff --git a/tests/test_wc_ledger.py b/tests/test_wc_ledger.py
new file mode 100644
index 0000000..e7b99f1
--- /dev/null
+++ b/tests/test_wc_ledger.py
@@ -0,0 +1,151 @@
+"""Unit tests for the work ledger. All rows, commands, paths, and outputs are SYNTHETIC."""
+
+import json
+import unittest
+
+from warm_compaction import ledger
+from warm_compaction.layout import COPY_HEADING
+from warm_compaction.rows import estimate_tokens
+from wc_fixtures import assistant, tool, user
+
+PREFIXES = ("[HERMES PREFIX]", "[CONTEXT SUMMARY]:")
+
+
+def terminal(call_id, command):
+ return assistant("", [(call_id, "terminal", json.dumps({"command": command}))])
+
+
+def result(call_id, output="", exit_code=0, error=None):
+ return tool(call_id, json.dumps({"output": output, "exit_code": exit_code, "error": error}))
+
+
+SESSION = [
+ user("Synthetic task: fix tests/test_dates.py."),
+ terminal("c1", "pytest tests/test_dates.py -q"),
+ result("c1", "F.\nFAILED tests/test_dates.py::test_parse_dates - ValueError: unconverted data remains: Z\n"
+ "1 failed, 1 passed", exit_code=1),
+ assistant("", [("c2", "read_file", json.dumps({"path": "src/dates.py"}))]),
+ tool("c2", "def parse_date(text): ..."),
+ assistant("", [("c3", "patch", json.dumps({"path": "src/dates.py", "old_string": "a", "new_string": "b"}))]),
+ tool("c3", json.dumps({"success": True})),
+ terminal("c4", "pytest tests/test_dates.py -q"),
+ result("c4", "..\n2 passed in 0.04s", exit_code=0),
+ assistant("", [("c5", "write_file", json.dumps({"path": "CHANGELOG.md", "content": "- Accept Z."}))]),
+ tool("c5", json.dumps({"success": True})),
+]
+
+
+class LedgerTest(unittest.TestCase):
+ def test_commands_keep_the_exit_code_and_the_first_error_line(self):
+ text = ledger.build(SESSION, PREFIXES)
+ self.assertIn("- `pytest tests/test_dates.py -q`: exit 1; FAILED tests/test_dates.py::test_parse_dates - "
+ "ValueError: unconverted data remains: Z", text)
+ self.assertIn("- `pytest tests/test_dates.py -q`: exit 0", text)
+ self.assertLess(text.index("exit 1"), text.index("exit 0"))
+
+ def test_changed_files_are_listed_and_reads_are_not(self):
+ text = ledger.build(SESSION, PREFIXES)
+ files = text.split(ledger.FILES_HEADING, 1)[1]
+ self.assertIn("- src/dates.py: changed", files)
+ self.assertIn("- CHANGELOG.md: written", files)
+ self.assertEqual(files.count("src/dates.py"), 1)
+
+ def test_the_block_has_the_heading_and_the_reference_note(self):
+ lines = ledger.build(SESSION, PREFIXES).splitlines()
+ self.assertEqual(lines[:2], [ledger.HEADING, ledger.NOTE])
+
+ def test_no_tool_calls_give_no_block(self):
+ self.assertEqual(ledger.build([user("hi"), assistant("hello")], PREFIXES), "")
+
+ def test_a_failed_edit_is_a_tool_line_not_a_changed_file(self):
+ edit = json.dumps({"path": "src/x.py", "old_string": "a", "new_string": "b"})
+ rows = [assistant("", [("e1", "patch", edit)]),
+ tool("e1", json.dumps({"success": False, "error": "old_string not found in src/x.py"}))]
+ text = ledger.build(rows, PREFIXES)
+ self.assertIn("- tool patch src/x.py: error; old_string not found in src/x.py", text)
+ self.assertNotIn(ledger.FILES_HEADING, text)
+
+ def test_an_edit_without_a_result_is_a_tool_line_not_a_changed_file(self):
+ edit = json.dumps({"path": "src/x.py", "old_string": "a", "new_string": "b"})
+ patch = json.dumps({"mode": "patch", "patch": "*** Begin Patch\n*** Update File: y.py\n@@\n-x\n+y\n"})
+ text = ledger.build([assistant("", [("u1", "patch", edit), ("u2", "patch", patch)])], PREFIXES)
+ self.assertIn("- tool patch src/x.py: no result recorded", text)
+ self.assertIn("- tool patch y.py: no result recorded", text)
+ self.assertNotIn(ledger.FILES_HEADING, text)
+
+ def test_v4a_patch_headers_give_each_file_and_action(self):
+ patch = "*** Begin Patch\n*** Update File: a.py\n@@\n-x\n+y\n*** Add File: b.py\n+z\n*** Delete File: c.py\n"
+ rows = [assistant("", [("p1", "patch", json.dumps({"mode": "patch", "patch": patch}))]),
+ tool("p1", json.dumps({"success": True}))]
+ files = ledger.build(rows, PREFIXES).split(ledger.FILES_HEADING, 1)[1]
+ self.assertIn("- a.py: changed", files)
+ self.assertIn("- b.py: written", files)
+ self.assertIn("- c.py: deleted", files)
+
+ def test_plain_text_results_and_terminal_errors(self):
+ cases = (("make build\nexit code 2\nerror: missing header", "exit 2; error: missing header"),
+ ("Error: command not allowed", "error; Error: command not allowed"),
+ ("all good", "exit unknown"))
+ for output, expected in cases:
+ with self.subTest(output=output):
+ rows = [terminal("t1", "make build"), tool("t1", output)]
+ self.assertIn(f"- `make build`: {expected}", ledger.build(rows, PREFIXES))
+ timeout = [terminal("t2", "sleep 999"),
+ result("t2", exit_code=124, error="Command timed out after 180 seconds")]
+ self.assertIn("- `sleep 999`: exit 124; Command timed out after 180 seconds", ledger.build(timeout, PREFIXES))
+
+ def test_a_reused_call_id_keeps_the_result_of_each_turn(self):
+ # A provider can use the same call id again in a later turn (synthetic ids).
+ rows = [terminal("call_0", "pytest -q"), result("call_0", "FAILED tests/test_a.py::test_x", exit_code=1),
+ terminal("call_0", "pytest -q"), result("call_0", "3 passed", exit_code=0)]
+ lines = [line for line in ledger.build(rows, PREFIXES).splitlines() if line.startswith("- `")]
+ self.assertEqual(lines, ["- `pytest -q`: exit 1; FAILED tests/test_a.py::test_x", "- `pytest -q`: exit 0"])
+
+ def test_a_result_before_its_call_is_not_used(self):
+ rows = [result("r1", exit_code=1), terminal("r1", "make")]
+ self.assertIn("- `make`: no result recorded", ledger.build(rows, PREFIXES))
+
+ def test_a_call_without_a_result_says_so(self):
+ self.assertIn("- `ls`: no result recorded", ledger.build([terminal("n1", "ls")], PREFIXES))
+
+ def test_commands_are_one_bounded_line_without_backticks(self):
+ rows = [terminal("b1", "echo `date`\n" + "x" * 500), result("b1")]
+ line = next(line for line in ledger.build(rows, PREFIXES).splitlines() if line.startswith("- `"))
+ self.assertNotIn("\n", line)
+ self.assertLessEqual(len(line), ledger.COMMAND_CHARS + 40)
+ self.assertEqual(line.count("`"), 2)
+
+ def test_the_oldest_commands_go_first_when_the_block_is_too_large(self):
+ rows = []
+ for index in range(60):
+ rows += [terminal(f"k{index}", f"run step {index}"), result(f"k{index}", exit_code=0)]
+ rows += [assistant("", [("w1", "write_file", json.dumps({"path": "out.txt", "content": "x"}))]),
+ tool("w1", json.dumps({"success": True}))]
+ text = ledger.build(rows, PREFIXES, max_tokens=200)
+ self.assertLessEqual(estimate_tokens(text), 200)
+ self.assertIn("run step 59", text)
+ self.assertNotIn("run step 0`", text)
+ self.assertIn("- out.txt: written", text)
+
+ def test_a_budget_below_the_heading_gives_no_block(self):
+ self.assertEqual(ledger.build(SESSION, PREFIXES, max_tokens=5), "")
+
+ def test_a_later_compaction_keeps_the_ledger_of_the_earlier_summary(self):
+ first = ledger.build(SESSION, PREFIXES)
+ content = f"[CONTEXT SUMMARY]:\n## Goal\n- x\n\n{first}\n\n{COPY_HEADING}\n\n(none)"
+ summary_row = {"role": "user", "content": content, "_compressed_summary": True}
+ later = [summary_row, terminal("z1", "pytest -q"),
+ result("z1", "FAILED tests/test_api.py::test_timeout - AssertionError: 30 != 60", exit_code=1),
+ assistant("", [("z2", "patch", json.dumps({"path": "src/dates.py", "old_string": "b",
+ "new_string": "c"}))]),
+ tool("z2", json.dumps({"success": True}))]
+ text = ledger.build(later, PREFIXES)
+ self.assertIn("exit 1; FAILED tests/test_dates.py::test_parse_dates", text)
+ self.assertIn("- `pytest -q`: exit 1; FAILED tests/test_api.py::test_timeout", text)
+ files = text.split(ledger.FILES_HEADING, 1)[1].splitlines()
+ self.assertEqual([line for line in files if line], ["- CHANGELOG.md: written", "- src/dates.py: changed"])
+ self.assertEqual(text.count(ledger.HEADING), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_wc_register.py b/tests/test_wc_register.py
index bb5eda5..646e0a4 100644
--- a/tests/test_wc_register.py
+++ b/tests/test_wc_register.py
@@ -136,7 +136,7 @@ class RegisterTest(unittest.TestCase):
def test_manifest_declares_the_settings(self):
text = (ROOT / "warm_compaction" / "plugin.yaml").read_text(encoding="utf-8")
for line in ("manifest_version: 2", "name: warm_compaction", "config_schema:", " threshold:",
- " tail_tokens:", " user_copy_chars:", " warm:"):
+ " tail_tokens:", " user_copy_chars:", " warm:", " ledger:"):
self.assertIn(line + "\n", text)
def test_the_alpha_files_are_gone(self):
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index a578b90..3fe3cfc 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -11,7 +11,7 @@ from collections.abc import Callable
from agent.context_engine import ContextEngine
-from . import fallback, handoff, layout, native, protocol, warm
+from . import fallback, handoff, layout, ledger, native, protocol, warm
from .capture import CaptureStore, key_stamp
from .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value, sent_rows, sent_tokens
@@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)
NAME = "warm_compaction"
DEFAULTS: dict[str, Any] = {"threshold": 0.50, "tail_tokens": 0, "user_copy_chars": 24_000, "warm": True,
"summary_words": handoff.DEFAULT_SUMMARY_WORDS,
- "warm_providers": ""}
+ "warm_providers": "", "ledger": True}
THRESHOLD_RANGE = (0.10, 0.95)
TAIL_SHARE = 0.025
TAIL_MIN = 10_000
@@ -73,7 +73,7 @@ class CompactionAborted(RuntimeError):
def _valid(key: str, value: Any) -> bool:
- if key == "warm":
+ if key in ("warm", "ledger"):
return isinstance(value, bool)
if key == "warm_providers":
return isinstance(value, str)
@@ -401,6 +401,15 @@ class WarmCompactionEngine(ContextEngine):
return messages
if summary is None:
return self._abort(messages, record, started, attempt)
+ if self._settings["ledger"]:
+ # The work ledger: commands, results, and file changes of the rows before the tail, written by code.
+ # It takes the summary budget that the summary left, with room for a fallback cut quote.
+ quote_room = fallback.CUT_QUOTE_CHARS // 4 if record["path"] == "fallback" and prepend else 0
+ ledger_tokens = min(ledger.MAX_TOKENS, self._summary_budget(overhead, reserve)
+ - estimate_tokens(summary) - quote_room - 4)
+ block = ledger.build(messages[:start], prefixes, ledger_tokens) if ledger_tokens > 0 else ""
+ if block:
+ summary = summary.rstrip() + "\n\n" + block
# The prepended user row must be in the tail: when it does not fit in the room, keep its start and end.
# With an unknown overhead, the room is unknown too: the row keeps only its minimum. The room is after the
# tail as the cap cuts it: an uncut large tool result would leave no room.
diff --git a/warm_compaction/ledger.py b/warm_compaction/ledger.py
new file mode 100644
index 0000000..5a3c403
--- /dev/null
+++ b/warm_compaction/ledger.py
@@ -0,0 +1,203 @@
+"""Work ledger: commands, their results, and file changes, extracted by code from the rows before the tail.
+
+No model writes the ledger. A model summary keeps the goal and the state; the ledger keeps the hard facts that a
+summary often drops: which command failed, with which error, and which files changed. The ledger is reference
+data for the next model, not a list of tasks.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+from collections.abc import Iterable
+
+from .layout import COPY_HEADING, is_summary
+from .rows import attr, estimate_tokens, plain_text, tool_calls_of
+
+HEADING = "## Work ledger"
+NOTE = "Recorded by the plugin from tool calls and results before this point. Reference only; not new tasks."
+COMMANDS_HEADING = "### Commands"
+FILES_HEADING = "### Files changed"
+MAX_TOKENS = 1_000
+COMMAND_CHARS = 160
+DETAIL_CHARS = 200
+PATH_CHARS = 200
+# Argument keys that hold a shell command, and keys that hold a file path.
+COMMAND_KEYS = ("command", "cmd")
+PATH_KEYS = ("path", "file_path", "filepath", "filename", "target_file")
+# The file action of a tool, from words in its name. The first match wins.
+FILE_ACTIONS = (("delete", "deleted"), ("remove", "deleted"), ("move", "moved"), ("rename", "moved"),
+ ("write", "written"), ("create", "written"), ("patch", "changed"), ("edit", "changed"),
+ ("replace", "changed"), ("apply", "changed"))
+# File headers of a V4A patch (the Hermes patch tool in patch mode).
+PATCH_HEADER = re.compile(r"^\*\*\* (Update|Add|Delete|Move) File: (.+?)\s*$", re.MULTILINE)
+PATCH_ACTIONS = {"Update": "changed", "Add": "written", "Delete": "deleted", "Move": "moved"}
+# A line that reports a failure in tool output.
+ERROR_LINE = re.compile(r"\b(error|errors|failed|failure|exception|traceback|fatal|denied|not found)\b", re.I)
+# The exit code in plain text output ("exit code 2", "Exit status: 1").
+EXIT_TEXT = re.compile(r"\bexit(?:ed)?(?: with)?(?: code| status)?[:= ]+(-?\d+)\b", re.I)
+
+
+def _one_line(text: str, limit: int) -> str:
+ """Collapse whitespace and keep at most limit characters (with an ellipsis when cut)."""
+ text = " ".join(str(text).split())
+ return text if len(text) <= limit else text[:limit - 3].rstrip() + "..."
+
+
+def _arguments(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return value
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+ return {}
+
+
+def _first_error(text: str) -> str:
+ for line in text.splitlines():
+ if line.strip() and ERROR_LINE.search(line):
+ return _one_line(line, DETAIL_CHARS)
+ return ""
+
+
+def _outcome(result: str | None) -> tuple[str, bool]:
+ """Return (outcome text, failed) for one tool result. The outcome is only what the result reports."""
+ if result is None:
+ return "no result recorded", False
+ data: Any = None
+ try:
+ data = json.loads(result)
+ except (TypeError, ValueError):
+ pass
+ if isinstance(data, dict):
+ error = data.get("error")
+ code = data.get("exit_code")
+ output = data.get("output")
+ output = output if isinstance(output, str) else ""
+ if isinstance(code, int) and not isinstance(code, bool):
+ detail = _one_line(str(error), DETAIL_CHARS) if error else (_first_error(output) if code else "")
+ return f"exit {code}" + (f"; {detail}" if detail else ""), code != 0
+ if error:
+ return "error; " + _one_line(str(error), DETAIL_CHARS), True
+ if data.get("success") is False:
+ return "failed", True
+ detail = _first_error(output)
+ return ("exit unknown; " + detail if detail else "exit unknown"), False
+ match = EXIT_TEXT.search(result)
+ detail = _first_error(result)
+ if match:
+ code = int(match.group(1))
+ return f"exit {code}" + (f"; {detail}" if code and detail else ""), code != 0
+ if result.lstrip().lower().startswith("error"):
+ return "error; " + _one_line(result.lstrip(), DETAIL_CHARS), True
+ return ("exit unknown; " + detail if detail else "exit unknown"), False
+
+
+def _file_action(name: str) -> str | None:
+ lowered = name.lower()
+ for word, action in FILE_ACTIONS:
+ if word in lowered:
+ return action
+ return None
+
+
+def _prior(messages: list, prefixes: tuple[str, ...]) -> tuple[list[str], dict[str, str]]:
+ """The ledger lines of earlier summary rows, so that a later compaction keeps them."""
+ commands: list[str] = []
+ files: dict[str, str] = {}
+ for row in messages:
+ if not is_summary(row, prefixes):
+ continue
+ lines = plain_text(attr(row, "content")).splitlines()
+ if HEADING not in lines:
+ continue
+ section = None
+ for line in lines[lines.index(HEADING) + 1:]:
+ if line in (COMMANDS_HEADING, FILES_HEADING):
+ section = line
+ elif line.startswith("## ") or line == COPY_HEADING:
+ break
+ elif line.startswith("- ") and section == COMMANDS_HEADING:
+ commands.append(line)
+ elif line.startswith("- ") and section == FILES_HEADING and ": " in line:
+ path, _, action = line[2:].rpartition(": ")
+ files.pop(path, None)
+ files[path] = action
+ return commands, files
+
+
+def entries(messages: Iterable[Any], prefixes: Iterable[str] = ()) -> tuple[list[str], dict[str, str]]:
+ """Return (command lines, {path: action}) in the order of the rows, oldest first."""
+ messages = list(messages)
+ commands, files = _prior(messages, tuple(prefixes))
+ # Each result goes to the oldest earlier call with its id that has no result yet: a provider can use the same
+ # call id again in a later turn, and each turn keeps its own result.
+ calls: list[tuple[str, Any, list[str | None]]] = []
+ waiting: dict[str, list[list[str | None]]] = {}
+ for row in messages:
+ if attr(row, "role") == "assistant":
+ for call_id, name, raw_arguments in tool_calls_of(row):
+ slot: list[str | None] = [None]
+ calls.append((name, raw_arguments, slot))
+ if call_id:
+ waiting.setdefault(call_id, []).append(slot)
+ elif attr(row, "role") == "tool":
+ pending = waiting.get(str(attr(row, "tool_call_id") or ""))
+ if pending:
+ pending.pop(0)[0] = plain_text(attr(row, "content"))
+ for name, raw_arguments, slot in calls:
+ arguments = _arguments(raw_arguments)
+ outcome, failed = _outcome(slot[0])
+ command = next((arguments[key] for key in COMMAND_KEYS if isinstance(arguments.get(key), str)), None)
+ if command is not None and command.strip():
+ commands.append(f"- `{_one_line(command, COMMAND_CHARS).replace('`', chr(39))}`: {outcome}")
+ continue
+ action = _file_action(name)
+ paths = [arguments[key] for key in PATH_KEYS if isinstance(arguments.get(key), str)]
+ touched = [(path, action) for path in paths if action] if paths else []
+ for value in arguments.values():
+ if isinstance(value, str):
+ touched.extend((path, PATCH_ACTIONS[kind]) for kind, path in PATCH_HEADER.findall(value))
+ if failed or (touched and slot[0] is None):
+ # A failed edit did not change the file, and an edit without a result is not confirmed: report a tool
+ # line instead of a changed file.
+ first = paths[0] if paths else touched[0][0] if touched else ""
+ target = f" {_one_line(first, PATH_CHARS)}" if first else ""
+ commands.append(f"- tool {_one_line(name, 60)}{target}: {outcome}")
+ continue
+ for path, kind in touched:
+ path = _one_line(path, PATH_CHARS)
+ if path:
+ files.pop(path, None)
+ files[path] = kind
+ return commands, files
+
+
+def build(messages: Iterable[Any], prefixes: Iterable[str] = (), max_tokens: int = MAX_TOKENS) -> str:
+ """Return the ledger block, or "" when it is empty or does not fit in max_tokens.
+ The oldest command lines go first when the block is too large, then the oldest files."""
+ commands, files = entries(messages, prefixes)
+ paths = list(files.items())
+
+ def render() -> str:
+ lines = [HEADING, NOTE]
+ if commands:
+ lines += [COMMANDS_HEADING, *commands]
+ if paths:
+ lines += [FILES_HEADING, *(f"- {path}: {action}" for path, action in paths)]
+ return "\n".join(lines)
+
+ if not commands and not paths:
+ return ""
+ text = render()
+ while estimate_tokens(text) > max_tokens and (commands or paths):
+ if commands:
+ commands.pop(0)
+ else:
+ paths.pop(0)
+ text = render() if commands or paths else ""
+ return text
diff --git a/warm_compaction/plugin.yaml b/warm_compaction/plugin.yaml
index f2002f6..3c4c2ec 100644
--- a/warm_compaction/plugin.yaml
+++ b/warm_compaction/plugin.yaml
@@ -28,6 +28,10 @@ config_schema:
type: bool
default: true
description: Use the warm request. Set false for comparison runs.
+ ledger:
+ type: bool
+ default: true
+ description: Add the work ledger (commands with exit codes and first error lines, changed files) after the summary. Set false for comparison runs.
summary_words:
type: int
default: 600