Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix
Relax the fallback format and add a ledger-only summary (#45)
Elevatormusicf61448ada904
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e795045..60e467b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,9 +7,12 @@ All notable changes are listed here. The format follows [Keep a Changelog](https### 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).+- Add a ledger-only summary when both model summaries fail and the rows before the tail have tool work (`path=ledger`). Setting `ledger_on_failure` (default true).### Changed+- The fallback summary uses the free handoff sections of the warm request by default (`fallback_format: relaxed`). The source-quote format stays available as `fallback_format: quoted`. A relaxed reply without its end marker passes when all headings are present and the reported output count is below the generation limit. Small local models could not write the quoted format: a local 4B model passed 0 of 16 quoted replies and 10 of 10 relaxed replies in one synthetic test.+- 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.- Ask the fallback model to keep unreported progress unknown and keep rules separate from confirmed actions. Preserve approval conditions and do not add a goal from a prohibition. These prompt rules do not guarantee factual accuracy.- Run CI checks automatically for pushes to `main` through the approval-free `ci-main` environment, which allows only the branch named `main`. Run CI checks automatically for pull requests from branches in this repository. Keep approval through `ci-approval` for pull requests from forks, scheduled runs, and manual dispatch. Local checks still need an explicit request.diff --git a/README.md b/README.mdindex 2f6af8f..e95e202 100644--- a/README.md+++ b/README.md@@ -70,7 +70,7 @@ At each compaction, the plugin sends the last main-model request of the sessionAfter 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.+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 and the rows before the tail have tool work, the plugin compacts with a **ledger-only summary**: the five headings with an unknown line, the work ledger, and the copied user messages (`path=ledger`). This keeps a small local model from growing the context without limit when it cannot write a valid summary. Without tool work, or with `ledger_on_failure: false`, the plugin stops the current compaction pass, preserves its original input history, and reports an error with safe codes only. 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.@@ -172,6 +172,8 @@ The settings are in `plugins.entries.warm_compaction.settings`. An invalid value| `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 |+| `fallback_format` | `relaxed` or `quoted` | `relaxed` | Format of the fallback summary. `relaxed` uses the free handoff sections; `quoted` builds every section from verified source quotes. See [Fallback model and keys](#fallback-model-and-keys) |+| `ledger_on_failure` | bool | true | When both model summaries fail and the rows before the tail have tool work, compact with a ledger-only summary instead of stopping. It applies only when `ledger` is true. Set false to keep the history unchanged in that case |```yamlplugins:@@ -197,7 +199,12 @@ The plugin asks for up to 8,192 generated tokens, so a thinking model has room tThe prompt asks the model to use only stated facts, keep unreported progress unknown, and keep user rules separate from confirmed actions. It also asks the model to preserve approval conditions. These instructions aim to reduce errors; the content checks cannot verify factual accuracy.-The plugin constructs all five fallback sections from source quotes. It keeps complete nonblank lines from the bounded transcript. If a JSON quote is an exact part of one distinct source line, it restores that complete line, including its negation and scope. Repeated source lines do not create ambiguity; repeated decoded quotes within a section are kept once. For a recognized earlier summary, it decodes one JSON layer from the five sections after the transcript bounds. The known core gets the existing 8,000-character / 2,000-token share first; Copied user messages uses only the remainder. A core that fits stays intact. Unstructured legacy summaries keep the existing whole-summary bound. The earlier Next step ends before the engine's separate Copied user messages section. This decoded text can differ from the encoded text in the transcript. It keeps the earlier summary encoded and does not decode arbitrary user or tool text. A collision with ordinary source text is ambiguous.+The fallback has two formats (setting `fallback_format`):++- `relaxed` (default): the five handoff sections of the warm request (free bullets, the `[COMPLETE]`/`[OPEN]`/`[BLOCKED]`/`[CANCELLED]` state tags) with the same grounding rules, and the end marker. Small local models can write it. A reply without its end marker passes only when it has all headings in order, the required sections have text, no part of a marker is in it, and the server reported an output count below the 8,192-token generation limit (so the limit did not cut it). The work ledger keeps the exact command results and file changes. In a synthetic test on a local 4B model (`qwen3.5-4b-mtp`, LM Studio, one coding conversation), 10 of 10 relaxed replies passed on the first call; 0 of 16 quoted replies passed. This is one model and one conversation, not a benchmark.+- `quoted`: the source-quote construction in the rest of this section. Use it when the fallback model is strong and you want every fallback bullet to be an exact source quote.++In the quoted format, the plugin constructs all five fallback sections from source quotes. It keeps complete nonblank lines from the bounded transcript. If a JSON quote is an exact part of one distinct source line, it restores that complete line, including its negation and scope. Repeated source lines do not create ambiguity; repeated decoded quotes within a section are kept once. For a recognized earlier summary, it decodes one JSON layer from the five sections after the transcript bounds. The known core gets the existing 8,000-character / 2,000-token share first; Copied user messages uses only the remainder. A core that fits stays intact. Unstructured legacy summaries keep the existing whole-summary bound. The earlier Next step ends before the engine's separate Copied user messages section. This decoded text can differ from the encoded text in the transcript. It keeps the earlier summary encoded and does not decode arbitrary user or tool text. A collision with ordinary source text is ambiguous.Allowed source also includes the exact bounded focus and memory block sent with the request. This block stays separate from transcript lines; it cannot supply memory text that the request bounds removed or create new line adjacency. If an encoded prior quote also occurs inside an ordinary source line, its decoded meaning is ambiguous and is dropped.@@ -249,7 +256,7 @@ Hermes writes compaction metadata to `logs/agent.log` in the Hermes home folder:warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021 cached_tokens=107968```-- A successful `path` is `warm` or `fallback`. `path=aborted` means that the pass failed without replacing its input history. `reason` records the warm refusal; `fallback_reason` records the safe fallback error code, such as `unavailable`, `gate:<code>`, `summary_too_large`, `quote_capacity`, `capacity`, or `error:<exception class>`. No raw exception text is reported.+- A successful `path` is `warm`, `fallback`, or `ledger` (the ledger-only summary). `path=aborted` means that the pass failed without replacing its input history. `reason` records the warm refusal; `fallback_reason` records the safe fallback error code, such as `unavailable`, `gate:<code>`, `summary_too_large`, `quote_capacity`, `capacity`, or `error:<exception class>`. No raw exception text is reported.- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `provider_not_allowed`, `api_mode_unsupported`, `auth_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.- A refused fallback reply also reports `fallback_output_tokens`, `fallback_requested_max_tokens`, `fallback_body_tokens`, `fallback_attempts`, and `fallback_end_marker`. The output count is `None` when it is unavailable or invalid. The body count is an estimate. The marker code is `present`, `missing`, `not_last`, `duplicate`, or `empty`; it contains no reply text or random marker. The requested limit does not prove that Hermes sent it or that the server applied it.diff --git a/tests/test_wc_engine.py b/tests/test_wc_engine.pyindex 868ad37..2072c9d 100644--- a/tests/test_wc_engine.py+++ b/tests/test_wc_engine.py@@ -1740,7 +1740,7 @@ class EngineTest(unittest.TestCase):self.llm = FakeLlm(text=HEADINGS_TEXT.replace("- [OPEN] Write the report.", "- " + state).replace('- "Use short names."', '- "Check PKG-17 progress."')+ "\n" + END_LINE)- engine = self.make(warm=False)+ engine = self.make(warm=False, fallback_format="quoted")history = [user("Check PKG-17 progress."), *old_turns(), assistant("synthetic final reply")]original = copy.deepcopy(history)new = engine.compress(history)@@ -1772,7 +1772,7 @@ class EngineTest(unittest.TestCase):return SimpleNamespace(text=text.replace(END_LINE, end_line),usage=SimpleNamespace(input_tokens=50, output_tokens=output))self.llm = SimpleNamespace(complete=complete)- engine = self.make(warm=False)+ engine = self.make(warm=False, fallback_format="quoted")with self.assertLogs("warm_compaction", level="INFO") as logs:self.assert_aborted(engine, [*old_turns(), assistant("synthetic final reply")], "gate:" + reason)status = engine.get_status()["warm_last"]@@ -1900,6 +1900,61 @@ class EngineTest(unittest.TestCase):self.assertEqual(engine.warm_last["path"], "fallback")self.assertNotIn(ledger.HEADING, self.summary_text(new))+ def test_failed_summaries_compact_with_the_ledger_only(self):+ from warm_compaction import ledger+ from warm_compaction.engine import LEDGER_ONLY_LINE+ self.llm.error = RuntimeError("synthetic failure")+ engine = self.make(warm=False)+ rows = self.ledger_rows()+ new = engine.compress([*rows, assistant("final")])+ self.assertEqual((engine.warm_last["path"], engine.warm_last["fallback_reason"]),+ ("ledger", "error:RuntimeError"))+ self.assertEqual(engine.compression_count, 1)+ text = self.summary_text(new)+ for heading in ("## Goal", "## User instructions", "## Current state", "## Key facts", "## Next step"):+ self.assertIn(f"{heading}\n{LEDGER_ONLY_LINE}", text)+ self.assertEqual(text.count(ledger.HEADING), 1)+ self.assertIn("- `pytest -q`: exit 1; FAILED tests/test_api.py::test_timeout", text)+ self.assertIn("## Copied user messages", text)+ self.assertLess(len(new), len(rows) + 1)++ def test_a_ledger_only_summary_fits_a_large_prepended_request(self):+ # No model saw the request: the middle that the cut removes goes after the ledger as a quote, and the+ # prepended row fits in the room.+ from warm_compaction.rows import estimate_tokens+ self.llm.error = RuntimeError("synthetic failure")+ rows = [*self.ledger_rows(), user("BIG start " + "q" * 3_000 + " MID-REQ " + "q" * 37_000 + " big end"),+ assistant("", [("c3", "read", "{}")]), tool("c3", "r1"), assistant("done")]+ engine = self.make(threshold=0.95, tail_tokens=2_000, warm=False)+ engine.update_model(model=ROUTE[0], context_length=64_000, base_url=ROUTE[1], api_key="k",+ provider="custom", api_mode=ROUTE[2])+ new = engine.compress(rows)+ self.assertEqual(engine.warm_last["path"], "ledger")+ prepended = next(row for row in new if str(row.get("content")).startswith("BIG start"))+ self.assertNotIn("MID-REQ", prepended["content"])+ self.assertIn("MID-REQ", self.summary_text(new))+ self.assertLess(sum(estimate_tokens(str(row.get("content"))) for row in new), 64_000 * 0.95)++ def test_without_a_ledger_or_with_the_setting_off_failed_summaries_keep_history(self):+ self.llm.error = RuntimeError("synthetic failure")+ for settings, history in (({}, [*old_turns(), assistant("final")]),+ ({"ledger_on_failure": False}, [*self.ledger_rows(), assistant("final")]),+ ({"ledger": False}, [*self.ledger_rows(), assistant("final")])):+ with self.subTest(settings=settings):+ engine = self.make(warm=False, **settings)+ self.assert_aborted(engine, history, "error:RuntimeError")++ def test_the_default_relaxed_fallback_accepts_a_paraphrased_summary(self):+ plain = ("## Goal\nFix the synthetic timeout test.\n\n## User instructions\n- none\n\n"+ "## Current state\n- [OPEN] test_timeout fails.\n\n## Key facts\n- src/api.py changed.\n\n"+ "## Next step\nRun pytest -q.")+ self.llm = FakeLlm(text=plain + "\n" + END_LINE)+ engine = self.make(warm=False)+ new = engine.compress([*self.ledger_rows(), assistant("final")])+ self.assertEqual(engine.warm_last["path"], "fallback")+ self.assertIn("- [OPEN] test_timeout fails.", self.summary_text(new))+ self.assertEqual(len(self.llm.calls), 1)+def test_the_ledger_uses_only_the_summary_budget_that_is_left(self):from warm_compaction import ledgerengine = self.make(warm=False)@@ -2243,7 +2298,7 @@ class EngineTest(unittest.TestCase):def test_all_unknown_replies_preserve_history(self):self.llm = FakeLlm(FALLBACK_TEXT + "\n" + END_LINE)- engine = self.engine = self.make(warm=False, tail_tokens=10)+ engine = self.engine = self.make(warm=False, tail_tokens=10, fallback_format="quoted")rows = [*old_turns(4), user("Check JOB-X3."), assistant("done")]self.assert_aborted(engine, rows, "gate:no_useful_evidence")self.assertEqual(len(self.llm.calls), 2)@@ -2252,7 +2307,7 @@ class EngineTest(unittest.TestCase):self.llm.error = RuntimeError("synthetic failure")rows = [*old_turns(4), user("go"), assistant("", [("c1", "read", "{}")]),tool("c1", "head " + "u" * 20_000 + " MIDDLE-FACT " + "u" * 20_000 + " end")]- engine = self.make(tail_tokens=2_000, warm=False)+ engine = self.make(tail_tokens=2_000, warm=False, fallback_format="quoted")self.assert_aborted(engine, rows, "error:RuntimeError")def test_a_capture_with_a_changed_source_is_not_used_for_the_budget(self):@@ -2284,16 +2339,18 @@ 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", "ledger": False}+ "summary_words": 1200, "warm_providers": "opencode-go,commandcode", "ledger": False,+ "fallback_format": "quoted", "ledger_on_failure": 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, "ledger": "yes"}+ "summary_words": 0, "warm_providers": 7, "ledger": "yes", "fallback_format": "strict",+ "ledger_on_failure": 1}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), 7)+ self.assertEqual(len(logs.output), 9)def test_a_word_count_below_one_uses_the_default(self):def reader(values):diff --git a/tests/test_wc_fallback.py b/tests/test_wc_fallback.pyindex ec98f6e..32193f4 100644--- a/tests/test_wc_fallback.py+++ b/tests/test_wc_fallback.py@@ -949,6 +949,72 @@ class SourceContextTest(unittest.TestCase):logger.warning.assert_called_once()+PLAIN = ("## Goal\nFix the synthetic parser test.\n\n## User instructions\n- \"Keep the public API.\"\n\n"+ "## Current state\n- [OPEN] Fix tests/test_p.py; it fails with ValueError.\n\n"+ "## Key facts\n- The failing file is src/p.py.\n\n## Next step\nPatch src/p.py and run pytest.")+++class RelaxedFallbackTest(unittest.TestCase):+ """quoted=False: free handoff sections, as a small model writes them. All replies are synthetic."""++ def marker(self, messages):+ return messages[0]["content"].rstrip().splitlines()[-1]++ def test_the_relaxed_instruction_uses_the_handoff_sections_without_source_quotes(self):+ llm = FakeLlm(text=lambda messages, kwargs, count: PLAIN + "\n" + self.marker(messages))+ llm_summary(llm, [user("hi")], PREFIXES, quoted=False)+ instruction = llm.calls[0][0][0]["content"]+ self.assertNotIn("one JSON string", instruction)+ self.assertIn("[COMPLETE]", instruction)+ self.assertIn("Use only facts from the transcript.", instruction)+ self.assertEqual(instruction.count("End the summary with this line:"), 1)+ self.assertTrue(self.marker(llm.calls[0][0]).startswith("[END OF SUMMARY "))++ def test_paraphrased_bullets_pass_in_relaxed_mode_and_fail_in_quoted_mode(self):+ reply = lambda messages, kwargs, count: PLAIN + "\n" + self.marker(messages) # noqa: E731+ self.assertEqual(llm_summary(FakeLlm(text=reply), [user("hi")], PREFIXES, quoted=False), (PLAIN, 321))+ with self.assertLogs("warm_compaction.fallback", level="WARNING"):+ self.assertEqual(llm_summary(FakeLlm(text=reply), [user("hi")], PREFIXES), (None, None))++ def test_a_complete_reply_without_the_marker_passes_below_the_generation_limit(self):+ llm, failure = FakeLlm(text=PLAIN + "\n", output_tokens=400), {}+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, quoted=False, failure=failure), (PLAIN, 321))+ self.assertEqual((len(llm.calls), failure), (1, {}))++ def test_a_reply_without_the_marker_retries_when_it_can_be_cut(self):+ # Unknown output count, an output at the limit, a missing heading, or a marker part: not proof of an end.+ cases = ((PLAIN, None), (PLAIN, REQUEST_MAX_TOKENS), (PLAIN.replace("## Next step\n", ""), 400),+ (PLAIN + "\n[END OF SUMMARY", 400))+ for text, output in cases:+ with self.subTest(output=output, text=text[-20:]):+ llm, failure = FakeLlm(text=text, output_tokens=output), {}+ with self.assertLogs("warm_compaction.fallback", level="WARNING"):+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, quoted=False, failure=failure),+ (None, None))+ self.assertEqual(failure["reason"], "gate:missing_end_marker")+ self.assertEqual(len(llm.calls), 3)++ def test_text_after_the_marker_still_fails_in_relaxed_mode(self):+ reply = lambda messages, kwargs, count: PLAIN + "\n" + self.marker(messages) + "\nNow I run pytest." # noqa: E731+ llm, failure = FakeLlm(text=reply, output_tokens=400), {}+ with self.assertLogs("warm_compaction.fallback", level="WARNING"):+ self.assertEqual(llm_summary(llm, [user("hi")], PREFIXES, quoted=False, failure=failure), (None, None))+ self.assertEqual(failure["reason"], "gate:missing_end_marker")++ def test_relaxed_mode_keeps_the_heading_and_size_gates(self):+ cases = (("Sure! Here it is.\n" + PLAIN, "heading_preamble"),+ (PLAIN.replace("## Goal\nFix the synthetic parser test.", "## Goal"), "section_empty"),+ (PLAIN + "\n" + "word " * 3_000, "body_token_limit"))+ for text, reason in cases:+ with self.subTest(reason=reason):+ reply = lambda messages, kwargs, count, text=text: text + "\n" + self.marker(messages) # noqa: E731+ failure = {}+ with self.assertLogs("warm_compaction.fallback", level="WARNING"):+ self.assertEqual(llm_summary(FakeLlm(text=reply), [user("hi")], PREFIXES, quoted=False,+ failure=failure), (None, None))+ self.assertEqual(failure["reason"], "gate:" + reason)++class UsefulEvidenceTest(unittest.TestCase):def test_all_unknown_retries_then_refuses_without_provider_text(self):llm, failure = FakeLlm(SUMMARY + "\n" + END_LINE), {}diff --git a/tests/test_wc_register.py b/tests/test_wc_register.pyindex 646e0a4..4a2eb14 100644--- a/tests/test_wc_register.py+++ b/tests/test_wc_register.py@@ -136,7 +136,8 @@ 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:", " ledger:"):+ " tail_tokens:", " user_copy_chars:", " warm:", " ledger:", " fallback_format:",+ " ledger_on_failure:"):self.assertIn(line + "\n", text)def test_the_alpha_files_are_gone(self):diff --git a/warm_compaction/engine.py b/warm_compaction/engine.pyindex 3fe3cfc..0470356 100644--- a/warm_compaction/engine.py+++ b/warm_compaction/engine.py@@ -20,7 +20,11 @@ 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": "", "ledger": True}+ "warm_providers": "", "ledger": True, "fallback_format": "relaxed",+ "ledger_on_failure": True}+FALLBACK_FORMATS = ("relaxed", "quoted")+# The text of each section of a ledger-only summary: no model wrote a summary.+LEDGER_ONLY_LINE = "- unknown: no model summary; see the work ledger and the copied user messages"THRESHOLD_RANGE = (0.10, 0.95)TAIL_SHARE = 0.025TAIL_MIN = 10_000@@ -73,8 +77,10 @@ class CompactionAborted(RuntimeError):def _valid(key: str, value: Any) -> bool:- if key in ("warm", "ledger"):+ if key in ("warm", "ledger", "ledger_on_failure"):return isinstance(value, bool)+ if key == "fallback_format":+ return value in FALLBACK_FORMATSif key == "warm_providers":return isinstance(value, str)if isinstance(value, bool):@@ -374,7 +380,8 @@ class WarmCompactionEngine(ContextEngine):summary, _tokens = fallback.llm_summary(self._llm, [*messages[:start], *removed], prefixes, focus_topic=focus_topic, memory_context=memory,task=self._task, summary_words=self._settings["summary_words"],- ready=lambda: not self._cancelled() and self._attempt() == attempt, failure=failure)+ ready=lambda: not self._cancelled() and self._attempt() == attempt, failure=failure,+ quoted=self._settings["fallback_format"] == "quoted")if summary is None:record["fallback_reason"] = failure.get("reason", "unavailable")for key in ("output_tokens", "requested_max_tokens", "end_marker", "attempts", "body_tokens"):@@ -399,9 +406,21 @@ class WarmCompactionEngine(ContextEngine):record.update(path="cancelled", reason="route_changed")self._finish(record, started, attempt[-1])return messages+ if summary is None and self._settings["ledger"] and self._settings["ledger_on_failure"]:+ # Both model summaries failed (a small model can miss the format): compact with the work ledger and the+ # copied user messages, under the five headings with an unknown line. Without a ledger, keep history.+ stub = "\n\n".join(f"{heading}\n{LEDGER_ONLY_LINE}" for heading in handoff.HEADINGS)+ # Leave room for the cut quote of a long prepended request, as on the fallback path.+ quote_room = fallback.CUT_QUOTE_CHARS // 4 if prepend else 0+ room = min(ledger.MAX_TOKENS,+ self._summary_budget(overhead, reserve) - estimate_tokens(stub) - quote_room - 4)+ block = ledger.build(messages[:start], prefixes, room) if room > 0 else ""+ if block and self._summary_fits(stub + "\n\n" + block, overhead, reserve):+ summary = stub + "\n\n" + block+ record["path"] = "ledger"if summary is None:return self._abort(messages, record, started, attempt)- if self._settings["ledger"]:+ if self._settings["ledger"] and record["path"] != "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@@ -423,11 +442,11 @@ class WarmCompactionEngine(ContextEngine):if record["path"] == "warm":# The warm request had the whole row.prepend = layout.fit_user_row(prepend, allowed)- elif record["path"] == "fallback":- # The fallback transcript had only the start and end of a long row: the middle that this cut- # removes goes after the summary as a quote. The quote takes only what the summary budget has- # left (the tail cap stays at least the cap of the fallback transcript); the room keeps space- # for it.+ elif record["path"] in ("fallback", "ledger"):+ # The fallback transcript had only the start and end of a long row, and no model saw the row on+ # the ledger path: the middle that this cut removes goes after the summary as a quote. The quote+ # takes only what the summary budget has left (the tail cap stays at least the cap of the+ # fallback transcript); the room keeps space for it.left = max(0, min(fallback.CUT_QUOTE_CHARS // 4,self._summary_budget(overhead, reserve) - estimate_tokens(summary) - 4))fitted = layout.fit_user_row(prepend, allowed - left, cut)@@ -796,7 +815,7 @@ class WarmCompactionEngine(ContextEngine):logger.info("Warm compaction works again after %d compactions without it", self._warm_failures)self._clear_warm_failures()return- if path != "fallback" or reason in ("disabled", "provider_not_allowed"):+ if path not in ("fallback", "ledger") or reason in ("disabled", "provider_not_allowed"):returnlogger.warning("Warm compaction skipped (%s); used the %s summary", reason, path)self._warm_failures += 1diff --git a/warm_compaction/fallback.py b/warm_compaction/fallback.pyindex ff03aba..0fa2faa 100644--- a/warm_compaction/fallback.py+++ b/warm_compaction/fallback.py@@ -11,7 +11,8 @@ from typing import Anyfrom collections.abc import Callable, Iterablefrom .handoff import (- DEFAULT_SUMMARY_WORDS, END_MARKER, HEADINGS, LEGACY_PREFIX, MAX_REPLY_BYTES, SUMMARY_WORDS_TOKEN,+ DEFAULT_SUMMARY_WORDS, END_MARKER, HEADINGS, INSTRUCTION_TEMPLATE, LEGACY_PREFIX, MAX_REPLY_BYTES,+ SUMMARY_WORDS_TOKEN,extras, gate_content,)from .layout import COPY_HEADING, CUT_NOTE, is_real_user, is_summary, quote@@ -115,6 +116,14 @@ End the summary with this line:# count as a token, so a caller can set it.FALLBACK_INSTRUCTION = FALLBACK_INSTRUCTION_TEMPLATE.replace(SUMMARY_WORDS_TOKEN, str(DEFAULT_SUMMARY_WORDS))+# The relaxed format: the rules of the quoted format with the handoff sections of the warm request, without source+# quotes. A small model can write it. The work ledger keeps the exact command results and file changes.+_SECTIONS = "Use these five headings"+RELAXED_INSTRUCTION_TEMPLATE = (+ FALLBACK_INSTRUCTION_TEMPLATE[:FALLBACK_INSTRUCTION_TEMPLATE.index(_SECTIONS)]+ + INSTRUCTION_TEMPLATE[INSTRUCTION_TEMPLATE.index(_SECTIONS):]+ + "\nEnd the summary with this line:\n" + END_LINE + "\n")+def _cut(text: str, limit: int) -> str:return text if len(text) <= limit else text[:limit] + CUT_MARK@@ -334,6 +343,17 @@ def _complete_reply(raw: str, end_line: str) -> tuple[str | None, str]:return None, "\n".join(lines[:-1])+def _complete_without_marker(result: Any, raw: str, body: str, end_line: str, prefixes: Iterable[str]) -> bool:+ """True when a relaxed reply without its end marker is still complete: no part of the marker, all headings in+ order with the required sections, and a known output count below the generation limit (not cut by it)."""+ output = getattr(getattr(result, "usage", None), "output_tokens", None)+ if not isinstance(output, int) or isinstance(output, bool) or not 0 < output < REQUEST_MAX_TOKENS:+ return False+ if end_line in raw or "[END OF SUMMARY" in raw:+ return False+ return gate_content(body, prefixes)[0] is not None++def _refuse(failure: dict[str, Any] | None, reason: str | None, result: Any, raw: str, end_line: str, body: str,attempts: int) -> tuple[None, None]:"""Record a gate refusal with safe reply metadata only, and return (None, None)."""@@ -588,11 +608,14 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topimemory_context: str = "", task: str | None = TASK, timeout_s: float = TIMEOUT_S,summary_words: int = DEFAULT_SUMMARY_WORDS,ready: Callable[[], bool] | None = None,- failure: dict[str, Any] | None = None) -> tuple[str | None, int | None]:+ failure: dict[str, Any] | None = None, quoted: bool = True) -> tuple[str | None, int | None]:"""Return (summary text, prompt tokens) from ctx.llm, or (None, None) when the request or the reply fails.ready checks the route and cancellation before each call and after each reply.An invalid reply gets one retry; after an end-marker failure it gets two. All calls share one time limit, anda retry starts only when RETRY_MIN_SHARE of it remains.+ quoted builds every section from verified source quotes. Otherwise the reply uses the free handoff sections+ of the warm request, and a reply without its end marker passes when it has all headings and stopped below the+ generation limit.failure gets safe codes and bounded reply metadata only. It never gets provider text."""if failure is not None:failure.clear()@@ -613,7 +636,8 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topifor attempt in range(1, MAX_ATTEMPTS + 1):end_line = END_LINE.replace("{nonce}", secrets.token_hex(16))words = int(summary_words) if attempt == 1 else min(int(summary_words), 300)- instruction = FALLBACK_INSTRUCTION_TEMPLATE.replace(SUMMARY_WORDS_TOKEN, str(words))+ template = FALLBACK_INSTRUCTION_TEMPLATE if quoted else RELAXED_INSTRUCTION_TEMPLATE+ instruction = template.replace(SUMMARY_WORDS_TOKEN, str(words))instruction = instruction.replace(END_LINE, end_line)if attempt > 1:# The most frequent failure of a local model is the marker line; state that requirement instead of the@@ -668,18 +692,23 @@ def llm_summary(llm: Any, messages: list, prefixes: Iterable[str], *, focus_topireturn None, Noneraw = str(getattr(result, "text", "") or "")reason, body = _complete_reply(raw, end_line)+ if reason == "missing_end_marker" and not quoted and _complete_without_marker(result, raw, body, end_line,+ prefixes):+ reason = Nonetext = Noneif reason is None:if len(body.encode("utf-8", "surrogatepass")) > MAX_REPLY_BYTES:reason = "byte_bound"elif estimate_tokens(body) > MAX_TOKENS:reason = "body_token_limit"+ elif not quoted:+ text, reason = gate_content(body, prefixes)else:body = _canonical_source_json(body)text, reason = gate_content(body, prefixes)if text is not None and estimate_tokens(body) > MAX_TOKENS:text, reason = None, "body_token_limit"- if text is not None:+ if text is not None and quoted:text = _construct_current_state(text, source, prefixes)text, reason = gate_content(text, prefixes)if text is not None and estimate_tokens(text) > MAX_TOKENS:diff --git a/warm_compaction/plugin.yaml b/warm_compaction/plugin.yamlindex 3c4c2ec..9e91aac 100644--- a/warm_compaction/plugin.yaml+++ b/warm_compaction/plugin.yaml@@ -32,6 +32,14 @@ config_schema:type: booldefault: truedescription: Add the work ledger (commands with exit codes and first error lines, changed files) after the summary. Set false for comparison runs.+ fallback_format:+ type: str+ default: relaxed+ description: Format of the fallback summary. relaxed uses the free handoff sections; quoted builds every section from verified source quotes.+ ledger_on_failure:+ type: bool+ default: true+ description: When both model summaries fail and the rows before the tail have tool work, compact with a ledger-only summary instead of stopping. Applies only when ledger is true.summary_words:type: intdefault: 600