From bd24c5d02a2418c5664262c19ba68d9451dcabbe Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Tue, 3 Nov 2026 09:24:09 -0500 Subject: [PATCH] compaction: lcm is coding-lcm; its budgets are in provider tokens, notes follow its summaries, and a summary that stopped early is never kept A long-lived session on a 1M window ran 20 days without one merge: relief measured the request with the bytes/4 estimate, which read it as about 395k against a 400k landing while the provider counted 554k (dense tool schemas, replayed reasoning and images). Every budget a compaction measures now scales the estimate by the provider's count for the previous request (`compaction.scale`, never below one). The notes layer goes right after a strategy's stored folds (`View.folds`), so a compaction that appends a leaf no longer rewrites the provider's cache of every older node; rolling and snapcompact report none and keep their notes first. A strategy may turn the notes layer off (`Strategy.notes`), and fold providers name every strategy that writes them (`Folds.owners`). One day of that session became a 185-character stub: the summarizer's reply stopped mid-sentence and was saved. `compaction.reply_text` keeps a reply only when it finished, or when a long one reached its output limit (marked as cut there); a refusal, a filter or a short cut-off reply is retried like an empty one. The strategy is renamed `coding-lcm` ahead of a second strategy on the same graph; a startup data migration renames sessions' choices, the global default and the settings section that still say `lcm`. --- robot-docs/compaction.md | 22 +- .../harness/albedo_extension_settings.erl | 35 ++- src/albedo/harness/compaction.gleam | 91 +++++- .../extensions/commands/extension.gleam | 2 +- .../harness/extensions/lcm/extension.gleam | 287 +++++++++++++----- .../harness/extensions/lcm/memory.gleam | 9 +- .../harness/extensions/notes/extension.gleam | 18 +- .../extensions/rolling/extension.gleam | 3 + .../extensions/snapcompact/extension.gleam | 4 +- src/albedo/harness/loop.gleam | 23 +- src/albedo/harness/runtime.gleam | 10 +- test/e2e/extensions_test.py | 34 ++- test/e2e/lcm_preparation_test.py | 6 +- test/e2e/retrieval_test.py | 2 +- test/e2e/rewind_test.py | 2 +- test/e2e/session_delete_test.py | 4 +- test/e2e/settings_test.py | 9 +- test/harness/compaction_projection_test.gleam | 2 +- test/harness/lcm_preparation_test.gleam | 4 +- test/harness/lcm_test.gleam | 8 +- test/harness/summary_finish_test.gleam | 56 ++++ 21 files changed, 480 insertions(+), 151 deletions(-) create mode 100644 test/harness/summary_finish_test.gleam diff --git a/robot-docs/compaction.md b/robot-docs/compaction.md index 1a4b39029..288ae41eb 100644 --- a/robot-docs/compaction.md +++ b/robot-docs/compaction.md @@ -2,7 +2,7 @@ Compaction changes only what a request shows the model. The durable transcript and forks always keep the full conversation, and a `/tree` rewind keeps what it removes in an archived session. -The default session uses `rolling`. Selecting another strategy (`snapcompact` or `lcm`) through `/extensions` disables the current one in the same reload. A strategy enabled by name, for a session or globally, displaces a default one it did not choose, so a new default strategy cannot break an older choice. A session with the built-in extensions keeps one compaction strategy enabled. The registry also permits a custom host with no compaction strategy installed. +The default session uses `rolling`. Selecting another strategy (`snapcompact`, `coding-lcm` or `persistent-agent`) through `/extensions` disables the current one in the same reload. A strategy enabled by name, for a session or globally, displaces a default one it did not choose, so a new default strategy cannot break an older choice. A session with the built-in extensions keeps one compaction strategy enabled. The registry also permits a custom host with no compaction strategy installed. `/compact` compacts now with the session's strategy. `/compact ` first makes the named strategy the session's own, as `/extensions` would, then compacts with it. Later requests read the projection that strategy saved. For example, `/compact rolling` before switching to a model without image input leaves a text summary that the new model can read. @@ -16,7 +16,7 @@ A strategy has two halves. `project` returns the request its saved state makes o Provider projection can combine several durable rows into one model input, split one row into several inputs, or omit a nonportable reasoning item. `projection.for_model` returns plain inputs. Durable source references belong to transcript reads; synthetic extension context and strategy summaries have no transcript reference. -`lcm` uses durable source rows for summary ranges and plain model inputs for its verbatim tail. It preserves every unsummarized user unit and the latest whole user/tool unit. Source references on live projected inputs would let future strategies cut history within those unit boundaries. +`coding-lcm` and `persistent-agent` use durable source rows for summary ranges and plain model inputs for their verbatim tail. It preserves every unsummarized user unit and the latest whole user/tool unit. Source references on live projected inputs would let future strategies cut history within those unit boundaries. Transcript rows carry an indexed `row_class`: `user`, `image_fit`, or `other`. Every user input, including notes and mail, starts a compaction unit; an image-fit notice does too. LCM counts uncovered units from this metadata before deciding whether to compact. It decodes eligible source payloads only when creating new leaf summaries. Reading saved LCM folds after a strategy switch also uses metadata rather than expanding the covered transcript. @@ -28,7 +28,7 @@ Text or list positions cannot identify rows reliably because messages can repeat `notes` is a layer over whichever strategy is active, enabled by default. At every compaction it asks the model, through the same summarizer call the strategies use, to rewrite its notes from the previous notes and the history that compaction just evicted. The instructions tell the model the budget (`budgetTokens`, default 2000) and say that the archive or summary already carries the story, so the notes keep exact identifiers, decisions, what is verified, open work and the next step, and drop what is finished. The output limit sits a quarter above the budget so a model slightly over is not cut off mid-sentence; nothing else truncates the notes. -The notes are plain text in `compaction_notes`, saved with the same user-message cut a strategy saves, and every later request starts with them under a short header that points to `transcript_grep` and `transcript_read`. They change only at a compaction, so the request prefix stays cached. They belong to the session, not the strategy, and survive a switch between strategies. +The notes are plain text in `compaction_notes`, saved with the same user-message cut a strategy saves, and every later request shows them under a short header that points to `transcript_grep` and `transcript_read`. A strategy reports how many leading inputs of its request are its stored folds (`View.folds`), and the notes go right after them: `coding-lcm` puts them after its summary nodes, so a compaction that appends a leaf and rewrites the notes leaves the provider's cache of the older nodes in place; `rolling` and `snapcompact` report none, so the notes lead their requests. They change only at a compaction, so the request prefix stays cached. A strategy can turn the layer off (`Strategy.notes`); `persistent-agent` does, because its newest memory ends with what is still open. They belong to the session, not the strategy, and survive a switch between strategies. What the strategy evicted is derived, not reported: history without the longest tail that the prepared request also ends with, moved forward to a user message. Only history after the saved cut is sent, in chunks of at most half the window, with the previous notes. A fork has no notes row, so its first compaction writes them from all it evicted. A rewritten transcript no longer matches the saved cut, so the notes are rewritten from scratch. @@ -50,15 +50,15 @@ When a compaction plugin commits a new projection — through `/compact` or the ## stored folds -A strategy reads folds another strategy stored through `context.prior(history)`, never by importing that strategy. It returns `Prior(folds, rest)`: the stored summaries, oldest first, and the history they do not cover. Without stored folds, `folds` is empty and `rest` is the history unchanged. The extension that owns the storage registers a `FoldPlugin`; the runtime applies every enabled provider in registry order, except a provider owned by the active strategy, which reads its own state. `lcm-memory` provides LCM's folds and `snapcompact-memory` the snapcompact archive, so each stays visible after a switch away. `lcm-memory` comes first, so the archive covers history past LCM's folds. `lcm` ignores `prior`. +A strategy reads folds another strategy stored through `context.prior(history)`, never by importing that strategy. It returns `Prior(folds, rest)`: the stored summaries, oldest first, and the history they do not cover. Without stored folds, `folds` is empty and `rest` is the history unchanged. The extension that owns the storage registers a `FoldPlugin` naming the strategies that write it (`owners`); the runtime applies every enabled provider in registry order, except one whose owners include the active strategy, which reads its own state. `lcm-memory` provides the LCM graph's folds, owned by both `coding-lcm` and `persistent-agent`, and `snapcompact-memory` the snapcompact archive, so each stays visible after a switch away. `lcm-memory` comes first, so the archive covers history past LCM's folds. The two LCM strategies read the graph themselves and use `prior` only before their first compaction. -## lcm +## coding-lcm -`lcm` implements the source-backed memory part of [Lossless Context Management](https://arxiv.org/html/2605.04050v1). It stores leaf summaries, condensed parent summaries, child links, and a covered source cursor in SQLite. The durable transcript supplies their source rows. The summary tree belongs to one session. A fork copies complete prefix summaries and their links with remapped row and node IDs. +`coding-lcm` (named `lcm` before `persistent-agent` shared its graph; a startup data migration renames sessions' choices, the global default and the `lcm` settings section) implements the source-backed memory part of [Lossless Context Management](https://arxiv.org/html/2605.04050v1). It stores leaf summaries, condensed parent summaries, child links, and a covered source cursor in SQLite. The durable transcript supplies their source rows. The summary tree belongs to one session. A fork copies complete prefix summaries and their links with remapped row and node IDs. -Below the trigger, `lcm` sends ordinary history without a summarizer call. Within a run, the trigger reads the input and output tokens the provider reported for the previous request, so it follows the model's own tokenizer; the first request of a run, and the request right after a compaction, have no reported count yet and use albedo's byte count. The trigger is `triggerPercent` of the window when it is set. Otherwise it is 80% of a window of 400k tokens or more and 75% of a smaller one, which leaves a small window more room for the reply. At the trigger, `lcm` keeps a verbatim tail: the newest steps within `tailPercent` (default 20%) of the window, always including the newest step. A step is a user message, a model response, or the tool results that follow one, so a cut can fall inside one long agentic turn but never between a tool call and its result. `lcm` folds every step between the frontier and that tail into one depth-0 leaf. The leaf's summarizer is given the frontier's summaries as what the reader already remembers, and asked to continue from them rather than repeat them; merges and the combining of parts are not. A request shows the frontier's nodes and then every transcript row after the leaf cursor, read from the transcript and converted the way a turn's history is for the provider carrying the request. A cut falls between steps, never inside one response's items, so those rows convert to exactly the end of the history whatever providers and protocols wrote it. Only those uncovered rows are decoded, never the folded ones. The newest user message stays verbatim even once its steps are folded, placed before the first node that reaches past it, so a long agentic turn keeps its task word for word. Seeding from another strategy checks that the converted rows from the cut equal that strategy's remaining history; when they do not, nothing is seeded and the compaction folds from the first row instead of failing. The summarizer request carries the evicted history, converted the same way, as the conversation it was, after any previous summary and before a closing turn that asks for the summary, through the same wire as a turn: a provider reads its own signed or encrypted reasoning as it would on a turn, and a foreign model's turns replay as that wire replays them. The session's tools ride along, because a provider may refuse tool calls in a request without tool definitions, and `tool_choice` is none. The request asks for no prompt cache write, because nothing sends that prefix again: Claude's wire then places no `cache_control` marks; providers that cache implicitly are unaffected. Size estimates and the verbatim fallback read the same history as text, with each step's readable reasoning, text and calls. Every leaf, merge and combination of parts is written as a spec in the same sections: Task, Settled (verified facts with how they were verified), Contracts (exact signatures, paths with lines, strings and commands), Changes, Next actions (the very next tool call first; an edit names its file and copies the exact text it replaces, so the agent can make it without re-reading; decided choices are stated as decided) and Open. Agents on DeepSWE runs re-read files their prose summaries had already described, and said they trust a summary that reads as settled facts and exact contracts; after each fold they also re-read the code they were about to change, which the copied edit text spares them. Summaries have no length budget. The output limit only guards against a runaway reply, so a large window makes a long summary and a small window makes a small leaf. One summarizer request reads at most 200k tokens, measured as the summarizer renders the items. A larger source is summarized in chronological parts of whole steps, and the part summaries are combined into the one node. If the summarizer returns nothing, for example because a transcript note told it to stay idle, the request is retried once with a request for plain prose. A second empty reply keeps the source itself as the node's text, so compaction always makes its node. A provider failure fails the compaction and saves nothing. A fold is due only when it can make room: the request is over the trigger and the rows a fold would take, everything before the verbatim tail, are at least as large as that tail, or the request has reached the window itself. When the pinned prompt and the tail already fill the window below the trigger, folding again every turn would free nothing and cost a summarizer call each time, so the request goes out as it is, the context inspector reports the status `window_too_small` with the reason, and the session is told once per run to raise its context window or lower `tailPercent`. After the leaf, `lcm` merges only under pressure, never by count. While the request is above half the trigger, the oldest frontier nodes are merged into one parent. Those are the fewest oldest nodes whose text covers the excess, at least two when there are two. Their depths and sizes may differ, and the parent sits one level above the deepest child. Older history therefore grows coarser first, and the newest summaries keep their detail longest. A merge must cut the summary text it replaces by at least a tenth, or it is discarded and relief stops; a frontier that is down to one node is recompressed at most once per compaction; and relief stops after 16 merges. If the request without its summaries (the pinned prompt plus the tail) already reaches half the trigger, relief aims only at the trigger, and if it reaches the trigger, relief does not merge at all, because merging cannot get below that floor. A forced `/compact` without a real window (from the session, the configuration or a catalog), or whose tail would hold the whole history, keeps the newest user turn verbatim and folds everything before it; a session that is a single turn keeps only its newest step. The children stay in SQLite. A session that switches to `lcm` from another strategy is not summarized from its first row. Until `lcm` compacts, the request shows what the other strategy's stored folds made of the history, for example snapcompact's archive pages and the rows after them. The first compaction then writes one pointer node, with no summarizer call, over the rows those folds cover, and it folds the rows that were live after them into one leaf. The original rows remain available. +Below the trigger, `coding-lcm` sends ordinary history without a summarizer call. Within a run, the trigger reads the input and output tokens the provider reported for the previous request, so it follows the model's own tokenizer; the first request of a run, and the request right after a compaction, have no reported count yet and use albedo's byte count. The trigger is `triggerPercent` of the window when it is set. Otherwise it is 80% of a window of 400k tokens or more and 75% of a smaller one, which leaves a small window more room for the reply. At the trigger, `coding-lcm` keeps a verbatim tail: the newest steps within `tailPercent` (default 20%) of the window, always including the newest step. A step is a user message, a model response, or the tool results that follow one, so a cut can fall inside one long agentic turn but never between a tool call and its result. `coding-lcm` folds every step between the frontier and that tail into one depth-0 leaf. The leaf's summarizer is given the frontier's summaries as what the reader already remembers, and asked to continue from them rather than repeat them; merges and the combining of parts are not. A request shows the frontier's nodes and then every transcript row after the leaf cursor, read from the transcript and converted the way a turn's history is for the provider carrying the request. A cut falls between steps, never inside one response's items, so those rows convert to exactly the end of the history whatever providers and protocols wrote it. Only those uncovered rows are decoded, never the folded ones. The newest user message stays verbatim even once its steps are folded, placed before the first node that reaches past it, so a long agentic turn keeps its task word for word. Seeding from another strategy checks that the converted rows from the cut equal that strategy's remaining history; when they do not, nothing is seeded and the compaction folds from the first row instead of failing. The summarizer request carries the evicted history, converted the same way, as the conversation it was, after any previous summary and before a closing turn that asks for the summary, through the same wire as a turn: a provider reads its own signed or encrypted reasoning as it would on a turn, and a foreign model's turns replay as that wire replays them. The session's tools ride along, because a provider may refuse tool calls in a request without tool definitions, and `tool_choice` is none. The request asks for no prompt cache write, because nothing sends that prefix again: Claude's wire then places no `cache_control` marks; providers that cache implicitly are unaffected. Size estimates and the verbatim fallback read the same history as text, with each step's readable reasoning, text and calls. Every leaf, merge and combination of parts is written as a spec in the same sections: Task, Settled (verified facts with how they were verified), Contracts (exact signatures, paths with lines, strings and commands), Changes, Next actions (the very next tool call first; an edit names its file and copies the exact text it replaces, so the agent can make it without re-reading; decided choices are stated as decided) and Open. Agents on DeepSWE runs re-read files their prose summaries had already described, and said they trust a summary that reads as settled facts and exact contracts; after each fold they also re-read the code they were about to change, which the copied edit text spares them. Summaries have no length budget. The output limit only guards against a runaway reply, so a large window makes a long summary and a small window makes a small leaf. One summarizer request reads at most 200k tokens, measured as the summarizer renders the items. A larger source is summarized in chronological parts of whole steps, and the part summaries are combined into the one node. If the summarizer returns nothing, for example because a transcript note told it to stay idle, or its reply stopped before it finished (a refusal, a content filter, or its output limit reached while the reply was still short, which is how a reply ends when its thinking spent the budget; `compaction.reply_text`), the request is retried once with a request for plain prose. A long reply cut at its limit is kept and says where it stopped. A second empty reply keeps the source itself as the node's text, so compaction always makes its node. A provider failure fails the compaction and saves nothing. A fold is due only when it can make room: the request is over the trigger and the rows a fold would take, everything before the verbatim tail, are at least as large as that tail, or the request has reached the window itself. When the pinned prompt and the tail already fill the window below the trigger, folding again every turn would free nothing and cost a summarizer call each time, so the request goes out as it is, the context inspector reports the status `window_too_small` with the reason, and the session is told once per run to raise its context window or lower `tailPercent`. Every budget a compaction measures (the tail, the floor and landing of relief, and the fit check) is in provider tokens: the byte estimate of each part is scaled by the provider's count for the previous request over the estimate of the request it replaces (`compaction.scale`, never below one, at most four), because byte estimates miss dense tool schemas, replayed reasoning and images. Before that correction a session whose estimate sat just under half the trigger while the provider counted far more never merged at all. After the leaf, `coding-lcm` merges only under pressure, never by count. While the request is above half the trigger, the oldest frontier nodes are merged into one parent. Those are the fewest oldest nodes whose text covers the excess, at least two when there are two. Their depths and sizes may differ, and the parent sits one level above the deepest child. Older history therefore grows coarser first, and the newest summaries keep their detail longest. A merge must cut the summary text it replaces by at least a tenth, or it is discarded and relief stops; a frontier that is down to one node is recompressed at most once per compaction; and relief stops after 16 merges. If the request without its summaries (the pinned prompt plus the tail) already reaches half the trigger, relief aims only at the trigger, and if it reaches the trigger, relief does not merge at all, because merging cannot get below that floor. A forced `/compact` without a real window (from the session, the configuration or a catalog), or whose tail would hold the whole history, keeps the newest user turn verbatim and folds everything before it; a session that is a single turn keeps only its newest step. The children stay in SQLite. A session that switches to `coding-lcm` from another strategy is not summarized from its first row. Until `coding-lcm` compacts, the request shows what the other strategy's stored folds made of the history, for example snapcompact's archive pages and the rows after them. The first compaction then writes one pointer node, with no summarizer call, over the rows those folds cover, and it folds the rows that were live after them into one leaf. The original rows remain available. -The default-enabled `lcm-memory` extension provides four read-only tools. `lcm_list` pages through every stored fold in the current session, including nodes absent from the request view. `lcm_grep` searches literal text in raw history and summaries with paged results and optional node scope. `lcm_describe` returns a node's source range, children, child segments with summaries, and summary. `lcm_expand` reads bounded pages of the original text rows covered by a node. These tools remain enabled when the session switches from `lcm` to `rolling`. Image hashes and metadata remain in transcript rows until compaction elides a tool-output image, which leaves a text marker; the text tools show whichever remains. The extension implements hierarchical memory. It does not implement the paper's large-file dispatcher, map operators, or subagent-only expansion. +The default-enabled `lcm-memory` extension provides four read-only tools. `lcm_list` pages through every stored fold in the current session, including nodes absent from the request view. `lcm_grep` searches literal text in raw history and summaries with paged results and optional node scope. `lcm_describe` returns a node's source range, children, child segments with summaries, and summary. `lcm_expand` reads bounded pages of the original text rows covered by a node. These tools remain enabled when the session switches from `coding-lcm` to `rolling`. Image hashes and metadata remain in transcript rows until compaction elides a tool-output image, which leaves a text marker; the text tools show whichever remains. The extension implements hierarchical memory. It does not implement the paper's large-file dispatcher, map operators, or subagent-only expansion. Search pages actual rows rather than numeric sequence intervals, so deleted sequence gaps do not create empty scan windows. A session-scoped search uses its session index and excludes unrelated sessions before paging. Cross-session search pages global rows before applying its caller and workspace filters, bounding each scan even when few sessions match. SQLite narrows candidates in batches of at most 2,048 rows; Unicode case-insensitive matching stays in Gleam. Paged searches count every matching row while keeping only the requested result texts. LCM source and summary matches have separate counts and pages at the same offset. `lcm_list` counts nodes and selects its page in SQL, including each returned node's frontier flag. @@ -66,10 +66,10 @@ Search pages actual rows rather than numeric sequence intervals, so deleted sequ Every retrieval tool shows a row through `tool.row_text`: `[user]`, `[assistant]` or `[tool id]` and then its text. A provider output is rendered as what a person reads: its visible text, `[thinking]` once, and each `[call name]` with its arguments unescaped (a flat object prints as `key: value` lines, a multi-line value on the lines after `key:`; any other arguments stay as sent). Signatures, encrypted reasoning and the copies a provider repeats its output in are left out of the text, and an item that holds only such data reads `(provider data only, N bytes)`. The durable row keeps them; compaction and snapcompact render history with their own functions. Search matches this text, so it finds words in messages, reasoning and call arguments but not a row's label or a provider's field names. A pattern's longest stretch free of quotes, backslashes and control characters narrows the SQLite candidates, because stored provider JSON escapes those; the rendered text then decides. `transcript_grep` and `lcm_grep` rows carry `kind` (`user`, `assistant`, `tool`), and `transcript_grep` takes `after_seq` and `before_seq` to search only the rows after and before a seq. A session's search of its own transcript (the retrieval tools, and `search_messages` on itself) leaves out the call that runs it: `search.running_call` finds the newest assistant row when it holds calls, which is committed before the call runs and is followed only by results, so the search would otherwise count its own call. -The `lcm` section in `$ALBEDO_HOME/extensions.json` accepts these settings: +The `coding-lcm` section in `$ALBEDO_HOME/extensions.json` accepts these settings: ```json -{ "lcm": { "contextWindowTokens": 200000, "triggerPercent": 80, "tailPercent": 20 } } +{ "coding-lcm": { "contextWindowTokens": 200000, "triggerPercent": 80, "tailPercent": 20 } } ``` All three settings are optional, and `triggerPercent` defaults to the window-sized trigger above. `contextWindowTokens` is also optional. Without an explicit setting or catalogued window, automatic LCM compaction stays off; `/compact` can still force it. The estimate uses byte counts. The newest whole unit can exceed the available window. In that case preparation reports the limit without discarding part of the unit. @@ -89,7 +89,7 @@ Each rolling compaction combines the previous summary with newly evicted history The saved cut counts user messages, not projected items. Provider projection can merge or drop assistant output, but it keeps every user message in order, so the summary still applies after a provider or model change. A fingerprint over the evicted user messages resets the state when the transcript no longer matches. A cut saved as an item count, before this format, is still checked the old way once and then rewritten in the new form. -After a switch from `lcm` to `rolling`, rolling reads the stored LCM summary nodes and the unsummarized tail as its source history. It does not expand covered rows to rebuild the LCM summary. If new assistant or tool rows follow the covered cursor without a new user row, rolling retains their whole conversation unit; that unit can overlap the fold. A later rolling summary can omit details from an LCM node. `lcm_list`, `lcm_describe`, and `lcm_expand` still reach the stored node and its original rows. Switching back to `lcm` uses its saved nodes and the durable transcript; it does not summarize the rolling summary. +After a switch from `coding-lcm` to `rolling`, rolling reads the stored LCM summary nodes and the unsummarized tail as its source history. It does not expand covered rows to rebuild the LCM summary. If new assistant or tool rows follow the covered cursor without a new user row, rolling retains their whole conversation unit; that unit can overlap the fold. A later rolling summary can omit details from an LCM node. `lcm_list`, `lcm_describe`, and `lcm_expand` still reach the stored node and its original rows. Switching back to `coding-lcm` uses its saved nodes and the durable transcript; it does not summarize the rolling summary. ## snapcompact diff --git a/src/albedo/harness/albedo_extension_settings.erl b/src/albedo/harness/albedo_extension_settings.erl index d9c1eb4f9..a079b3ce7 100644 --- a/src/albedo/harness/albedo_extension_settings.erl +++ b/src/albedo/harness/albedo_extension_settings.erl @@ -1,6 +1,7 @@ -module(albedo_extension_settings). -include_lib("kernel/include/file.hrl"). --export([home/0, read/1, set_enabled/3, set_enabled_many/2, set_entry/4, remove_entry/3]). +-export([home/0, read/1, set_enabled/3, set_enabled_many/2, set_entry/4, remove_entry/3, + rename_key/4]). -define(MAX_BYTES, 1048576). @@ -80,3 +81,35 @@ set_entry_locked(Home, Section, Key, Value) -> catch _:_ -> {error, <<"extensions.json is not a valid settings object">>} end. + +%% Moves `Old` to `New` in the top-level object (`root`) or in one section +%% (`{section, Name}`), when `Old` is there and `New` is not, so a renamed +%% extension keeps its settings and its global default. Answers whether it +%% moved. +rename_key(Home, Scope, Old, New) -> + albedo_settings_lock:with_lock(Home, fun() -> + try + {ok, Bytes} = read_locked(Home), + Sections = case Bytes of <<>> -> #{}; _ -> json:decode(Bytes) end, + true = is_map(Sections), + Entries = case Scope of + root -> Sections; + {section, Name} -> + case maps:get(Name, Sections, #{}) of Map when is_map(Map) -> Map; _ -> #{} end + end, + case {maps:find(Old, Entries), maps:is_key(New, Entries)} of + {{ok, Value}, false} -> + Moved = maps:put(New, Value, maps:remove(Old, Entries)), + Updated = case Scope of + root -> Moved; + {section, Section} -> Sections#{Section => Moved} + end, + case albedo_credentials:write(filename:join(Home, <<"extensions.json">>), Updated) of + ok -> {ok, true}; + _ -> {error, <<"could not save extensions.json">>} + end; + _ -> {ok, false} + end + catch _:_ -> {error, <<"extensions.json is not a valid settings object">>} + end + end, fun() -> {error, <<"settings store is busy">>} end). diff --git a/src/albedo/harness/compaction.gleam b/src/albedo/harness/compaction.gleam index 8b9c7a6aa..d1607347a 100644 --- a/src/albedo/harness/compaction.gleam +++ b/src/albedo/harness/compaction.gleam @@ -37,6 +37,43 @@ pub const summary_instructions = /// fail the compaction with it. pub const empty_summary = "summarizer provider returned no text" +/// How a summarizer error begins when the provider stopped the reply before +/// it finished (a refusal, a content filter, or an output limit reached +/// before any usable text), so the partial text is never kept as a summary. +pub const incomplete_summary = "summarizer reply stopped before it finished" + +/// Whether `reason` is a summarizer error a strategy can recover from the +/// way it recovers from an empty reply. +pub fn unfinished_summary(reason: String) -> Bool { + reason == empty_summary || string.starts_with(reason, incomplete_summary) +} + +/// A reply's text as a summary may keep it. A refusal or a filter keeps +/// none, and neither does an output limit reached before much text, which is +/// how a reply whose thinking spent its whole budget ends; a long reply cut +/// at the limit keeps what it wrote and says where it stopped. +pub fn reply_text( + text: String, + finish: types.Finish, +) -> Result(String, String) { + let text = string.trim(text) + case text, finish { + "", _ -> Error(empty_summary) + _, types.Complete | _, types.ToolCalls -> Ok(text) + _, types.LengthLimit -> + case text_scalars.length(text) >= kept_cut_off_chars { + True -> Ok(text <> "\n\n[the reply reached its output limit here]") + False -> Error(incomplete_summary <> ": its output limit came first") + } + _, types.ContentFiltered -> + Error(incomplete_summary <> ": a content filter stopped it") + _, types.OtherFinish(reason) -> Error(incomplete_summary <> ": " <> reason) + } +} + +/// The shortest reply cut at its output limit that is still kept. +const kept_cut_off_chars = 2000 + /// A context window a catalog or configuration actually reported, with the /// provenance a strategy must show rather than an assumed model limit. pub type Capacity { @@ -110,9 +147,10 @@ pub type Prior { pub type Folds { Folds( name: String, - /// The strategy that writes these folds. It reads its own state directly, - /// so the runtime leaves this provider out while that strategy is active. - owner: String, + /// The strategies that write these folds. They read their own state + /// directly, so the runtime leaves this provider out while one of them + /// is active. + owners: List(String), apply: fn(store.Store, String, Project, List(types.Input)) -> Result(Prior, String), ) @@ -405,6 +443,10 @@ pub type Prepared { /// True only when this preparation committed a new compaction, not when /// it reused a saved projection. Triggers post-compaction cleanup. compacted: Bool, + /// How many leading inputs are the strategy's stored folds. They change + /// only when it compacts, so a layer puts what it adds after them and a + /// compaction rewrites the provider's cache from there, not from the top. + folds: Int, ) } @@ -500,7 +542,13 @@ pub type Notes { /// What a strategy would send for one request from its saved state, and /// whether that request reached its trigger. pub type View { - View(inputs: List(types.Input), observation: Option(Observation), due: Bool) + View( + inputs: List(types.Input), + observation: Option(Observation), + due: Bool, + /// How many leading inputs are stored folds; see `Prepared`. + folds: Int, + ) } /// Receives chronological history before each model request. Implementations @@ -515,6 +563,9 @@ pub type Strategy { /// Folds history into the saved state now, because a projection was due /// or `context.force` asks; answers whether the saved state changed. compact: fn(Context, List(types.Input)) -> Result(Bool, String), + /// Whether notes layers run over this strategy. One that keeps its own + /// working notes in what it folds turns them off. + notes: Bool, ) } @@ -535,7 +586,7 @@ pub fn prepare( Context(..viewing, reported: None), history, )) - Ok(Prepared(view.inputs, view.observation, changed)) + Ok(Prepared(view.inputs, view.observation, changed, view.folds)) } case context.force { True -> compacted() @@ -543,7 +594,7 @@ pub fn prepare( use view <- result.try(strategy.project(viewing, history)) case view.due { True -> compacted() - False -> Ok(Prepared(view.inputs, view.observation, False)) + False -> Ok(Prepared(view.inputs, view.observation, False, view.folds)) } } } @@ -561,7 +612,7 @@ pub fn project( Context(..context, force: False), history, )) - Prepared(view.inputs, view.observation, False) + Prepared(view.inputs, view.observation, False, view.folds) } /// A deliberately approximate request-size estimate. It is used only when a @@ -640,6 +691,32 @@ pub fn estimate_pinned(instructions: String, tools: List(types.Tool)) -> Int { 16 + estimate_text(instructions) + estimate_tools(tools) } +/// Provider tokens per thousand estimated ones: the provider's count for the +/// previous request over the estimate of the request now, which differs from +/// it only by what arrived since. Byte estimates miss dense tool schemas, +/// replayed reasoning and images, so a budget measured in them alone can sit +/// far below what the provider counts. A thousand, meaning no correction, +/// until a run has a count, and never less: a count under the estimate keeps +/// the estimate, since an undercount is the case that overfills a window. +/// Bounded above so one odd report cannot run away. +pub fn scale(reported: Option(Int), estimated: Int) -> Int { + case reported { + Some(tokens) if estimated > 0 -> + int.clamp(tokens * 1000 / estimated, min: 1000, max: 4000) + _ -> 1000 + } +} + +/// An estimate in provider tokens, at `scale` per thousand. +pub fn scaled(estimated: Int, scale: Int) -> Int { + estimated * scale / 1000 +} + +/// Provider tokens as the estimate that measures them, at `scale`. +pub fn unscaled(tokens: Int, scale: Int) -> Int { + tokens * 1000 / int.max(scale, 1) +} + /// Where a saved compaction splits history: after `users` user messages. Each /// provider projection keeps user inputs verbatim and in order, merging or /// dropping only assistant output, so a cut counted in user messages survives diff --git a/src/albedo/harness/extensions/commands/extension.gleam b/src/albedo/harness/extensions/commands/extension.gleam index 669d0a1fd..c8f7993b3 100644 --- a/src/albedo/harness/extensions/commands/extension.gleam +++ b/src/albedo/harness/extensions/commands/extension.gleam @@ -321,7 +321,7 @@ fn compact() -> Command { "strategy", "compaction strategy to switch this session to; omit to keep the active one", False, - ["snapcompact", "rolling", "lcm"], + ["snapcompact", "rolling", "coding-lcm"], ), ], False, diff --git a/src/albedo/harness/extensions/lcm/extension.gleam b/src/albedo/harness/extensions/lcm/extension.gleam index 93d8751fa..8de9eeee5 100644 --- a/src/albedo/harness/extensions/lcm/extension.gleam +++ b/src/albedo/harness/extensions/lcm/extension.gleam @@ -1,5 +1,7 @@ -//// Lossless context management: source-backed summaries plus a verbatim tail. -//// All summary nodes are derived views over immutable transcript rows. +//// Lossless context management for coding work (`coding-lcm`): source-backed +//// summaries written as specs, plus a verbatim tail. All summary nodes are +//// derived views over immutable transcript rows; the graph they form is +//// shared with `persistent-agent`, which writes the same nodes as memories. import albedo/daemon/conversation import albedo/daemon/message_content @@ -17,6 +19,7 @@ import gleam/list import gleam/option.{type Option, None, Some} import gleam/result import gleam/string +import sqlight /// Room for a summary of any length: a guard against a runaway reply, not a /// budget the summary is squeezed into. @@ -35,6 +38,16 @@ pub type Config { ) } +/// This strategy's name. It was `lcm` before `persistent-agent` shared its +/// graph; a session or default that still names `lcm` is renamed at startup. +pub const name = "coding-lcm" + +/// The name sessions and settings used before the rename. +pub const former_name = "lcm" + +/// The strategies that write the LCM graph and read it themselves. +pub const writers = [name, "persistent-agent"] + pub fn configured_extension(config: Config) -> harness_extension.Extension { bundle(fn() { validate(config) }) } @@ -51,29 +64,71 @@ fn bundle( resolve: fn() -> Result(Config, String), ) -> harness_extension.Extension { harness_extension.Extension( - "lcm", - "Source-backed hierarchical summaries with bounded history retrieval", + name, + "Source-backed hierarchical summaries for coding work, with bounded history retrieval", ["lcm-memory"], [ - harness_extension.CompactionPlugin( - compaction.Strategy( - "lcm", - fn(context, history) { - use config <- result.try(resolve()) - project(config, context, history) - }, - fn(context, history) { - use config <- result.try(resolve()) - compact(config, context, history) - }, - ), - ), + harness_extension.CompactionPlugin(compaction.Strategy( + name, + fn(context, history) { + use config <- result.try(resolve()) + project(config, context, history) + }, + fn(context, history) { + use config <- result.try(resolve()) + compact(config, context, history) + }, + True, + )), harness_extension.CleanPlugin(graph.forget_session), + harness_extension.MigrationPlugin(harness_extension.DataMigration( + "coding_lcm_name", + rename_former, + )), ], graph.initialise, ) } +/// Sessions, the global default, and the settings section that still name +/// `lcm` take the new name. Idempotent: once renamed, nothing matches. +fn rename_former(ledger: store.Store, _backup: String) -> Result(Int, String) { + let home = settings.home() + use _ <- result.try(rename_key(home, Root, former_name, name)) + use _ <- result.try(rename_key(home, Section("enabled"), former_name, name)) + store.query(ledger, fn(db) { + store.transaction(db, fn() { + use renamed <- result.try(store.rows( + db, + "UPDATE OR IGNORE session_extensions SET name=?2 WHERE name=?1 RETURNING session", + [sqlight.text(former_name), sqlight.text(name)], + decode.field(0, decode.string, decode.success), + )) + // A session that already chose the new name keeps its own choice. + use _ <- result.try( + store.run(db, "DELETE FROM session_extensions WHERE name=?", [ + sqlight.text(former_name), + ]), + ) + Ok(list.length(renamed)) + }) + }) +} + +/// Where `rename_key` looks: the top level of extensions.json, or one section. +type Scope { + Root + Section(String) +} + +@external(erlang, "albedo_extension_settings", "rename_key") +fn rename_key( + home: String, + scope: Scope, + old: String, + new: String, +) -> Result(Bool, String) + /// Stored LCM folds for another strategy's source history after a strategy /// change. The graph stays fixed while LCM is inactive, so a strategy's source /// hashes continue to refer to the same folded prefix as new turns arrive. @@ -145,8 +200,8 @@ fn tail() -> settings.Setting(Int) { fn config_section() -> settings.Section(Config) { settings.section( - "lcm", - "Lossless context compaction (LCM)", + name, + "Coding context compaction (LCM)", settings.Context, [ settings.field(window()), @@ -165,7 +220,7 @@ fn config_section() -> settings.Section(Config) { fn validate(config: Config) -> Result(Config, String) { compaction.validate_window( - "lcm", + name, config.context_window_tokens, option.unwrap(config.trigger_percent, small_window_trigger), config.tail_percent, @@ -189,11 +244,11 @@ const small_window_trigger = 75 /// Why a request over the trigger is sent without folding. pub const window_too_small = - "the window is too small for this model's prompt and verbatim tail: a fold would evict less than the tail it keeps, so it cannot make room; raise the session's context window or lower lcm tailPercent" + "the window is too small for this model's prompt and verbatim tail: a fold would evict less than the tail it keeps, so it cannot make room; raise the session's context window or lower coding-lcm tailPercent" -/// Tokens of the steps in `inputs` that a fold with a `budget`-token tail -/// would evict. -fn foldable_tokens(inputs: List(types.Input), budget: Int) -> Int { +/// Estimated tokens of the steps in `inputs` that a fold with a tail of +/// `budget` estimated tokens would evict. +pub fn foldable_tokens(inputs: List(types.Input), budget: Int) -> Int { let steps = compaction.split_steps(inputs, fn(input) { input }) let kept = steps @@ -219,24 +274,23 @@ fn project( // Until the first compaction seeds the graph, the request is what the // previous strategy's stored folds already made of this history. // `rows` is the part of it a fold could take: everything but summaries. - use #(current, rows) <- result.try(case frontier { + use #(prior, rows) <- result.try(case frontier { [] -> context.prior(history) - |> result.map(fn(prior) { - #(list.append(prior.folds, prior.rest), prior.rest) - }) - _ -> Ok(#(projection(frontier, history, uncovered), uncovered.tail)) + |> result.map(fn(prior) { #(prior, prior.rest) }) + _ -> Ok(#(split(frontier, history, uncovered), uncovered.tail)) }) + let current = list.append(prior.folds, prior.rest) + let folds = list.length(prior.folds) + let estimated = context.pinned_tokens + compaction.estimate_inputs(current) + let scale = compaction.scale(context.reported, estimated) // The provider's count for the previous request, once this run has one. let #(measured, measure) = case context.reported { Some(tokens) -> #( tokens, "reported by the provider for the previous request", ) - None -> #( - context.pinned_tokens + compaction.estimate_inputs(current), - "estimated from current request projection", - ) + None -> #(estimated, "estimated from current request projection") } case window { None -> @@ -251,6 +305,7 @@ fn project( history, False, option.is_some(context.reported), + folds, )) Some(compaction.Capacity(tokens: capacity, source: capacity_source)) -> { use _ <- result.try(compaction.fits_pinned(context, capacity)) @@ -260,8 +315,10 @@ fn project( // the pinned prompt and the tail already fill the window below the // trigger. Folding again every turn would only cost a summarizer call, // so the request goes out as it is until there is that much to fold or - // the window itself is reached. - let budget = capacity * config.tail_percent / 100 + // the window itself is reached. The tail's share is of provider + // tokens, so it is measured in estimates at this session's scale. + let budget = + compaction.unscaled(capacity * config.tail_percent / 100, scale) let helps = foldable_tokens(rows, budget) >= budget || measured >= capacity Ok(view( @@ -287,6 +344,7 @@ fn project( history, over && helps, option.is_some(context.reported), + folds, )) } } @@ -309,6 +367,18 @@ fn compact( "no configured or catalogued context window to compact against", )) use _ <- result.try(compaction.fits_pinned(context, capacity)) + // The provider's count for the request this compaction replaces, over + // its estimate: every budget below is in provider tokens. + use scale <- result.try(case context.reported { + None -> Ok(1000) + Some(_) -> { + use before <- result.try(current_request(context, history)) + Ok(compaction.scale( + context.reported, + context.pinned_tokens + compaction.estimate_inputs(before), + )) + } + }) use _ <- result.try(case previous { [] -> seed(context, history, snapshot) _ -> Ok(False) @@ -334,7 +404,10 @@ fn compact( || option.is_some(context.capacity) let eligible = case known, - before_tail(uncovered, capacity * config.tail_percent / 100) + before_tail( + uncovered, + compaction.unscaled(capacity * config.tail_percent / 100, scale), + ) { True, [_, ..] as rows -> rows _, _ if context.force -> before_newest_turn(uncovered) @@ -350,26 +423,67 @@ fn compact( }) use Saved(frontier:, ..) as state <- result.try(saved(context)) use uncovered <- result.try(shown(context, state)) + let pressure = Pressure(context, history, uncovered, scale) use frontier <- result.try( - case landing(frontier, history, uncovered, context, capacity, config) { - Some(landing) -> - relieve(context, frontier, history, uncovered, landing, pressure_passes) + case landing(pressure, frontier, capacity, config) { + Some(landing) -> relieve(pressure, frontier, landing, pressure_passes) None -> Ok(frontier) }, ) - let next = projection(frontier, history, uncovered) use _ <- result.try(compaction.require( - context.pinned_tokens + compaction.estimate_inputs(next) < capacity - || context.force, + requested(pressure, frontier) < capacity || context.force, "LCM summaries and the newest conversation/tool unit do not fit the context window", )) Ok(frontier != previous) } +/// What relief measures a frontier against: the history it projects, the +/// rows after the leaf cursor, and the session's provider tokens per +/// thousand estimated ones. +type Pressure { + Pressure( + context: compaction.Context, + history: List(types.Input), + uncovered: Uncovered, + scale: Int, + ) +} + +/// The request `frontier` makes, in provider tokens. +fn requested(pressure: Pressure, frontier: List(graph.Node)) -> Int { + compaction.scaled( + pressure.context.pinned_tokens + + compaction.estimate_inputs(projection( + frontier, + pressure.history, + pressure.uncovered, + )), + pressure.scale, + ) +} + +/// The request the saved state makes now, before this compaction changes +/// it: what the previous request sent, plus what arrived since. +fn current_request( + context: compaction.Context, + history: List(types.Input), +) -> Result(List(types.Input), String) { + use Saved(frontier:, ..) as state <- result.try(saved(context)) + case frontier { + [] -> + context.prior(history) + |> result.map(fn(prior) { list.append(prior.folds, prior.rest) }) + _ -> { + use uncovered <- result.try(shown(context, state)) + Ok(projection(frontier, history, uncovered)) + } + } +} + /// The rows before the verbatim tail: the newest steps that fit `budget` /// tokens, and at least the newest step, stay out of the fold. Steps cut /// inside a turn too, so one long agentic turn still folds its older work. -fn before_tail( +pub fn before_tail( rows: List(transcript.SourcedEntry), budget: Int, ) -> List(transcript.SourcedEntry) { @@ -388,7 +502,7 @@ fn before_tail( /// The rows before the newest user message, for a forced compaction that /// keeps the newest turn whole; inside a session that is a single turn, the /// rows before its newest step. -fn before_newest_turn( +pub fn before_newest_turn( rows: List(transcript.SourcedEntry), ) -> List(transcript.SourcedEntry) { let turns = @@ -401,22 +515,23 @@ fn before_newest_turn( } } -/// Where relief aims: half the trigger, or the trigger itself when the -/// request without its summaries already reaches half. Merging cannot get -/// below that floor, so with the floor at the trigger there is no relief. +/// Where relief aims, in provider tokens: half the trigger, or the trigger +/// itself when the request without its summaries already reaches half. +/// Merging cannot get below that floor, so with the floor at the trigger +/// there is no relief. fn landing( + pressure: Pressure, frontier: List(graph.Node), - history: List(types.Input), - uncovered: Uncovered, - context: compaction.Context, capacity: Int, config: Config, ) -> Option(Int) { let trigger = capacity * trigger_percent(config, capacity) / 100 let floor = - context.pinned_tokens - + compaction.estimate_inputs(projection(frontier, history, uncovered)) - - compaction.estimate_inputs(list.map(frontier, node_input)) + requested(pressure, frontier) + - compaction.scaled( + compaction.estimate_inputs(list.map(frontier, node_input)), + pressure.scale, + ) case floor < trigger / 2, floor < trigger { True, _ -> Some(trigger / 2) False, True -> Some(trigger) @@ -430,18 +545,16 @@ fn landing( /// replaces by a tenth; one that does not, a frontier with nothing left to /// merge, or a lone node already recompressed once, ends it. fn relieve( - context: compaction.Context, + pressure: Pressure, frontier: List(graph.Node), - history: List(types.Input), - uncovered: Uncovered, landing: Int, passes: Int, ) -> Result(List(graph.Node), String) { - let estimated = - context.pinned_tokens - + compaction.estimate_inputs(projection(frontier, history, uncovered)) - use <- bool.guard(estimated <= landing || passes == 0, Ok(frontier)) - case oldest_batch(frontier, estimated - landing, 0, []) { + let context = pressure.context + let requested = requested(pressure, frontier) + use <- bool.guard(requested <= landing || passes == 0, Ok(frontier)) + let excess = compaction.unscaled(requested - landing, pressure.scale) + case oldest_batch(frontier, excess, 0, []) { [] -> Ok(frontier) batch -> { let inputs = list.map(batch, node_input) @@ -469,7 +582,7 @@ fn relieve( use next <- result.try(graph.frontier(context.store, context.session)) case batch { [_] -> Ok(next) - _ -> relieve(context, next, history, uncovered, landing, passes - 1) + _ -> relieve(pressure, next, landing, passes - 1) } } } @@ -505,7 +618,7 @@ fn oldest_batch( /// summarizer call, and the compaction that seeded it folds the rows that /// were live after them like any other. Answers whether it seeded: only an /// empty graph with another strategy's folds over a prefix of `history` does. -fn seed( +pub fn seed( context: compaction.Context, history: List(types.Input), snapshot: conversation.Snapshot, @@ -559,12 +672,12 @@ fn seed( } } -const archived_pointer = +pub const archived_pointer = "Earlier history, archived by the compaction strategy this session used before LCM and not summarized here. lcm_grep and lcm_expand on this node, or transcript_grep and transcript_read, reach the original rows." /// The session's saved graph against its transcript: the append boundary, /// the last row the graph covers, its frontier, and the rows after it. -type Saved { +pub type Saved { Saved( snapshot: conversation.Snapshot, covered: Int, @@ -576,11 +689,11 @@ type Saved { /// What a request shows of the rows the frontier does not cover: those rows /// as the request's provider reads them, and the newest user message when /// the frontier has folded it. -type Uncovered { +pub type Uncovered { Uncovered(tail: List(types.Input), task: Option(#(Int, types.Input))) } -fn saved(context: compaction.Context) -> Result(Saved, String) { +pub fn saved(context: compaction.Context) -> Result(Saved, String) { use snapshot <- result.try(conversation.snapshot( context.store, context.session, @@ -597,7 +710,7 @@ fn saved(context: compaction.Context) -> Result(Saved, String) { /// What a request built on `saved` shows of the rows its frontier does not /// cover; nothing to read while the frontier is empty. -fn shown( +pub fn shown( context: compaction.Context, saved: Saved, ) -> Result(Uncovered, String) { @@ -656,10 +769,11 @@ fn view( original: List(types.Input), due: Bool, reported: Bool, + folds: Int, ) -> compaction.View { let observation = compaction.observation( - "lcm", + name, status, source, case frontier { @@ -683,7 +797,7 @@ fn view( ) False -> observation } - compaction.View(inputs, Some(observation), due) + compaction.View(inputs, Some(observation), due, folds) } fn projection( @@ -808,6 +922,26 @@ fn summary( inputs: List(types.Input), instructions: String, render: fn(types.Input) -> Result(String, Nil), +) -> Result(String, String) { + summary_with( + context, + previous, + inputs, + instructions, + parts_instructions, + render, + ) +} + +/// `summary`, with `combine` the instructions that join a large source's +/// part summaries into one. +pub fn summary_with( + context: compaction.Context, + previous: Option(String), + inputs: List(types.Input), + instructions: String, + combine: String, + render: fn(types.Input) -> Result(String, Nil), ) -> Result(String, String) { let parts = compaction.split_steps(inputs, fn(input) { input }) @@ -838,7 +972,7 @@ fn summary( summary_cost(partials) >= summary_cost(inputs), Error("the summaries of its parts did not reduce the source"), ) - summary(context, None, partials, parts_instructions, node_text) + summary_with(context, None, partials, combine, combine, node_text) } } } @@ -905,8 +1039,11 @@ fn attempt_summary( )) { Ok(summary) -> Ok(string.trim(summary)) - Error(reason) if reason == compaction.empty_summary -> Ok("") - Error(reason) -> Error(reason) + Error(reason) -> + case compaction.unfinished_summary(reason) { + True -> Ok("") + False -> Error(reason) + } } } @@ -925,7 +1062,7 @@ fn kept_verbatim( } /// A transcript row as the conversation shows it. -fn source_text(input: types.Input) -> Result(String, Nil) { +pub fn source_text(input: types.Input) -> Result(String, Nil) { case input { types.User(text) | types.UserImage(text, _) -> Ok("[user] " <> text) types.ToolOutput(id, output, _) -> @@ -938,7 +1075,7 @@ fn source_text(input: types.Input) -> Result(String, Nil) { } /// A child node's summary, already labelled by `node_input`. -fn node_text(input: types.Input) -> Result(String, Nil) { +pub fn node_text(input: types.Input) -> Result(String, Nil) { case input { types.User(text) -> Ok(text) _ -> Error(Nil) diff --git a/src/albedo/harness/extensions/lcm/memory.gleam b/src/albedo/harness/extensions/lcm/memory.gleam index 4d68d3579..25ecb4970 100644 --- a/src/albedo/harness/extensions/lcm/memory.gleam +++ b/src/albedo/harness/extensions/lcm/memory.gleam @@ -18,8 +18,13 @@ pub fn extension() -> extension.Extension { [], [], ), - // Other strategies see stored folds through their compaction context. - extension.FoldPlugin(compaction.Folds("lcm", "lcm", lcm.stored_prior)), + // Other strategies see stored folds through their compaction context; + // the strategies that write the graph read it themselves. + extension.FoldPlugin(compaction.Folds( + "lcm", + lcm.writers, + lcm.stored_prior, + )), ], graph.initialise, ) diff --git a/src/albedo/harness/extensions/notes/extension.gleam b/src/albedo/harness/extensions/notes/extension.gleam index 91dee7e4d..6b66f47bf 100644 --- a/src/albedo/harness/extensions/notes/extension.gleam +++ b/src/albedo/harness/extensions/notes/extension.gleam @@ -1,8 +1,9 @@ //// Notes the model writes for itself at every compaction, over whichever //// strategy is active. The strategy decides what leaves the request; this //// layer asks the model what from that history it still needs, and keeps the -//// answer as plain text at the head of every later request. The durable -//// transcript is an input only: the notes live in their own table. +//// answer as plain text right after the strategy's stored folds in every +//// later request. The durable transcript is an input only: the notes live in +//// their own table. import albedo/daemon/note import albedo/daemon/store @@ -95,9 +96,11 @@ pub fn initialise(ledger: store.Store) -> Result(Nil, String) { store.query(ledger, fn(db) { store.exec(db, schema) }) } -/// Rewrites the notes when the strategy just compacted, then puts them ahead -/// of everything it prepared. A failed rewrite keeps the old notes and says -/// so in the observation, so a compaction already committed never fails. +/// Rewrites the notes when the strategy just compacted, then puts them right +/// after the strategy's stored folds: those change only when it compacts, so +/// rewritten notes leave the provider's cache of the folds before them. A +/// failed rewrite keeps the old notes and says so in the observation, so a +/// compaction already committed never fails. fn apply( context: compaction.Context, history: List(types.Input), @@ -111,7 +114,10 @@ fn apply( False -> Ok(#(saved, None)) }) let inputs = case saved { - Some(Saved(_, text)) -> [handoff(text), ..prepared.inputs] + Some(Saved(_, text)) -> { + let #(folds, rest) = list.split(prepared.inputs, prepared.folds) + list.flatten([folds, [handoff(text)], rest]) + } None -> prepared.inputs } Ok( diff --git a/src/albedo/harness/extensions/rolling/extension.gleam b/src/albedo/harness/extensions/rolling/extension.gleam index a40c31860..4a9676dc1 100644 --- a/src/albedo/harness/extensions/rolling/extension.gleam +++ b/src/albedo/harness/extensions/rolling/extension.gleam @@ -159,6 +159,7 @@ fn strategy(resolve: fn() -> Result(Config, String)) -> compaction.Strategy { use config <- result.try(resolve()) compact(config, context, history) }, + True, ) } @@ -210,6 +211,8 @@ fn project( list.length(current.inputs), )), due, + // Its summary is rewritten at every compaction, so notes stay first. + 0, ) } case diff --git a/src/albedo/harness/extensions/snapcompact/extension.gleam b/src/albedo/harness/extensions/snapcompact/extension.gleam index 13369acee..14a2a52f1 100644 --- a/src/albedo/harness/extensions/snapcompact/extension.gleam +++ b/src/albedo/harness/extensions/snapcompact/extension.gleam @@ -286,7 +286,7 @@ pub fn memory() -> extension.Extension { ), extension.FoldPlugin(compaction.Folds( "snapcompact", - "snapcompact", + ["snapcompact"], // The archive cut is counted in user messages, which no provider's // conversion changes. fn(ledger, session, _, history) { @@ -362,6 +362,7 @@ fn strategy_with( _ -> visual_compact(valid, context, history) } }, + True, ) } @@ -512,6 +513,7 @@ fn visual_project( survey.current, ), survey.triggered && newly_evicted != [], + 0, )) } diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index a0d8d984b..87416e7bb 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -1565,18 +1565,17 @@ fn summarize( <> describe(state.upstream, model, error) }), ) - let text = - turn.output - |> list.filter_map(fn(item) { - message_content.visible_assistant_text(types.Replay(item)) - |> option.to_result(Nil) - }) - |> string.join("") - |> string.trim - case text { - "" -> Error(compaction.empty_summary) - value -> Ok(value) - } + compaction.reply_text(visible_text(turn), turn.finish) +} + +/// What a reply shows a reader: its visible text, without reasoning. +fn visible_text(turn: types.Turn) -> String { + turn.output + |> list.filter_map(fn(item) { + message_content.visible_assistant_text(types.Replay(item)) + |> option.to_result(Nil) + }) + |> string.join("") } /// The turn that closes a summarizer request: everything before it is the diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 6a69e194d..a83946b31 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1821,7 +1821,7 @@ fn view_scoped( )) case extension.compaction(enabled) { None if force -> Error("no compaction strategy is enabled") - None -> Ok(compaction.Prepared(history, None, False)) + None -> Ok(compaction.Prepared(history, None, False, 0)) Some(strategy) -> { let context = compaction.Context( @@ -1836,7 +1836,7 @@ fn view_scoped( summarize, compaction.compose_prior( list.filter(extension.folds(enabled), fn(folds) { - folds.owner != strategy.name + !list.contains(folds.owners, strategy.name) }), runtime.ledger, prepared.id, @@ -1852,7 +1852,11 @@ fn view_scoped( // does, naming itself, rather than killing the turn's process. protect.guarded(fn() { use prepared <- result.try(view(strategy, context, history)) - list.try_fold(extension.notes(enabled), prepared, fn(prepared, layer) { + let layers = case strategy.notes { + True -> extension.notes(enabled) + False -> [] + } + list.try_fold(layers, prepared, fn(prepared, layer) { case prepared.compacted { True -> layer.compact(context, history, prepared) False -> layer.project(context, history, prepared) diff --git a/test/e2e/extensions_test.py b/test/e2e/extensions_test.py index 7e8eb7071..e15050ed3 100644 --- a/test/e2e/extensions_test.py +++ b/test/e2e/extensions_test.py @@ -904,8 +904,8 @@ class ExtensionTests(unittest.TestCase): def test_compacting_a_session_that_never_ran_a_cell_opens_no_kernel(self): self.turn("first turn") self.turn("second turn") - self.change({"selection": {"extensions": {"lcm": True}}}) - report = self.compact("lcm") + self.change({"selection": {"extensions": {"coding-lcm": True}}}) + report = self.compact("coding-lcm") self.assertEqual(report["state"], "compacted", report) self.assertEqual(self.snapshot()["kernel"]["state"], "none") @@ -915,12 +915,12 @@ class ExtensionTests(unittest.TestCase): # A cell opens the kernel the compaction must keep. self.turn("hot probe before reload", expected=2) before = self.snapshot()["kernel"]["instance_id"] - self.change({"selection": {"extensions": {"lcm": True}}}) + self.change({"selection": {"extensions": {"coding-lcm": True}}}) # Saving is separate from applying. Named compaction must compare with # the loaded strategy, even when the desired choice already matches. - report = self.compact("lcm") + report = self.compact("coding-lcm") self.assertTrue(report["selection_applied"], report) - self.assertEqual(report["effective_strategy"], "lcm", report) + self.assertEqual(report["effective_strategy"], "coding-lcm", report) self.assertEqual(report["state"], "compacted", report) after = self.snapshot()["kernel"]["instance_id"] self.assertEqual(after, before) @@ -1005,19 +1005,19 @@ class ExtensionTests(unittest.TestCase): self.assertEqual(refused["state"], "failed") self.assertFalse(refused["selection_applied"]) self.assertIsNotNone(refused["failure"]) - self.assertFalse(self.extensions()["lcm"]) - result = self.compact("lcm") + self.assertFalse(self.extensions()["coding-lcm"]) + result = self.compact("coding-lcm") self.assertEqual( - (result["effective_strategy"], result["state"]), ("lcm", "compacted") + (result["effective_strategy"], result["state"]), ("coding-lcm", "compacted") ) self.assertTrue(result["selection_applied"]) self.assertIsNone(result["failure"]) - self.assertEqual(result["observation"]["strategy"], "lcm") - self.assertTrue(self.extensions()["lcm"]) + self.assertEqual(result["observation"]["strategy"], "coding-lcm") + self.assertTrue(self.extensions()["coding-lcm"]) self.assertFalse(self.extensions()["rolling"]) - self.change({"selection": {"extensions": {"lcm": False}}}) + self.change({"selection": {"extensions": {"coding-lcm": False}}}) configured = self.get(f"/sessions/{self.sid}?view=configuration") - self.assertFalse(configured["selection"]["extensions"]["lcm"]) + self.assertFalse(configured["selection"]["extensions"]["coding-lcm"]) refused_reload = self.reload() self.assertEqual(refused_reload["session"]["state"], "failed") self.assertIsNotNone(refused_reload["session"]["failure"]) @@ -1030,19 +1030,21 @@ class ExtensionTests(unittest.TestCase): self.assertIn("LCM summary node #", json.dumps(requests[0]["input"])) self.assertIn("source_count", self.output(requests[-1])) self.assertIn("first turn", self.output(requests[-1])) - self.change({"selection": {"extensions": {"lcm": True}}}) + self.change({"selection": {"extensions": {"coding-lcm": True}}}) self.assertEqual(self.reload()["session"]["state"], "applied") configuration_url = f"/sessions/{self.sid}?view=configuration" before_conflict = self.get(configuration_url) with self.assertRaises(urllib.error.HTTPError) as conflict: - self.change({"selection": {"extensions": {"lcm": True, "rolling": True}}}) + self.change( + {"selection": {"extensions": {"coding-lcm": True, "rolling": True}}} + ) self.assertEqual(conflict.exception.code, 400) self.assertEqual(json.load(conflict.exception)["code"], "selection_conflict") self.assertEqual(self.get(configuration_url), before_conflict) self.change({"selection": {"extensions": {"rolling": True}}}) self.assertEqual(self.reload()["session"]["state"], "applied") self.assertTrue(self.extensions()["rolling"]) - self.assertFalse(self.extensions()["lcm"]) + self.assertFalse(self.extensions()["coding-lcm"]) (request,) = self.turn("folded under rolling") self.assertIn("LCM summary node #", json.dumps(request["input"])) requests = self.turn("fold list probe", expected=2) @@ -1053,7 +1055,7 @@ class ExtensionTests(unittest.TestCase): ) self.restart() self.assertTrue(self.extensions()["rolling"]) - self.assertFalse(self.extensions()["lcm"]) + self.assertFalse(self.extensions()["coding-lcm"]) (request,) = self.turn("folded after restart") self.assertIn("LCM summary node #", json.dumps(request["input"])) diff --git a/test/e2e/lcm_preparation_test.py b/test/e2e/lcm_preparation_test.py index ef3823eb5..70daaa30b 100644 --- a/test/e2e/lcm_preparation_test.py +++ b/test/e2e/lcm_preparation_test.py @@ -27,7 +27,7 @@ class LcmPreparationTests(unittest.TestCase): app.idle(session) with app.api( f"/sessions/{session}/compaction", - {"strategy": "lcm"}, + {"strategy": "coding-lcm"}, ) as response: result = json.load(response) self.assertEqual(result["state"], "compacted") @@ -49,7 +49,7 @@ class LcmPreparationTests(unittest.TestCase): self.assertEqual(calls, outputs) with app.api(f"/sessions/{session}/context") as response: observation = json.load(response)["compaction"] - self.assertEqual(observation["strategy"], "lcm") + self.assertEqual(observation["strategy"], "coding-lcm") def test_summarizer_reads_the_evicted_turns_as_their_own_conversation(self): sealed = "SEALED-REASONING-BLOB" @@ -103,7 +103,7 @@ class LcmPreparationTests(unittest.TestCase): app.idle(session) with app.api( f"/sessions/{session}/compaction", - {"strategy": "lcm"}, + {"strategy": "coding-lcm"}, ) as response: self.assertEqual(json.load(response)["state"], "compacted") summarizer = next( diff --git a/test/e2e/retrieval_test.py b/test/e2e/retrieval_test.py index b107de619..10385c92b 100644 --- a/test/e2e/retrieval_test.py +++ b/test/e2e/retrieval_test.py @@ -209,7 +209,7 @@ print('RETRIEVAL_BOUNDS_OK') self.turn(self.session, prompt) with self.app.api( f"/sessions/{self.session}/compaction", - {"strategy": "lcm"}, + {"strategy": "coding-lcm"}, ) as response: result = json.load(response) self.assertEqual(result["state"], "compacted") diff --git a/test/e2e/rewind_test.py b/test/e2e/rewind_test.py index 309077dd4..109d76f2b 100644 --- a/test/e2e/rewind_test.py +++ b/test/e2e/rewind_test.py @@ -279,7 +279,7 @@ class RewindStoredStateTest(IntegrationScenario): app.prompt(session, prompt + " " + "x" * 6000).close() app.idle(session) with app.api( - f"/sessions/{session}/compaction", {"strategy": "lcm"}, method="POST" + f"/sessions/{session}/compaction", {"strategy": "coding-lcm"}, method="POST" ) as response: self.assertEqual(json.load(response)["state"], "compacted") app.idle(session) diff --git a/test/e2e/session_delete_test.py b/test/e2e/session_delete_test.py index 36df0640f..93deef408 100644 --- a/test/e2e/session_delete_test.py +++ b/test/e2e/session_delete_test.py @@ -194,8 +194,8 @@ class SessionDeleteTests(unittest.TestCase): def test_deletion_clears_compaction_work_and_schedule_rows(self): for strategy, table, then in ( ("rolling", "compaction_notes", None), - ("lcm", "lcm_compaction_node", None), - ("lcm", "lcm_compaction_node", "rolling"), + ("coding-lcm", "lcm_compaction_node", None), + ("coding-lcm", "lcm_compaction_node", "rolling"), ("snapcompact", "snapcompact_archive", None), ): with self.subTest(strategy=strategy, then=then): diff --git a/test/e2e/settings_test.py b/test/e2e/settings_test.py index 5baec5a37..ef45d68f5 100644 --- a/test/e2e/settings_test.py +++ b/test/e2e/settings_test.py @@ -487,14 +487,19 @@ class SettingsTest(unittest.TestCase): before_settings = json.load(response) before_etag = response.headers["ETag"] with self.assertRaises(urllib.error.HTTPError) as conflict: - self.patch("extensions", {"defaults": {"lcm": True, "rolling": True}}) + self.patch( + "extensions", {"defaults": {"coding-lcm": True, "rolling": True}} + ) self.assertEqual(conflict.exception.code, 400) self.assertEqual(json.load(conflict.exception)["code"], "selection_conflict") self.assertEqual(extension_file.read_bytes(), before_bytes) with self.app.api("/settings?group=extensions") as response: self.assertEqual(json.load(response), before_settings) self.assertEqual(response.headers["ETag"], before_etag) - for selected, displaced in [("lcm", "rolling"), ("rolling", "lcm")]: + for selected, displaced in [ + ("coding-lcm", "rolling"), + ("rolling", "coding-lcm"), + ]: self.patch("extensions", {"defaults": {selected: True}}) session = self.app.session() effective = self.read(f"/sessions/{session}?tail=0")["selection"][ diff --git a/test/harness/compaction_projection_test.gleam b/test/harness/compaction_projection_test.gleam index eb166b4c2..ca1703c33 100644 --- a/test/harness/compaction_projection_test.gleam +++ b/test/harness/compaction_projection_test.gleam @@ -35,7 +35,7 @@ pub fn lcm_projection_writes_nothing_test() -> Nil { memory.extension(), lcm.configured_extension(lcm.Config(Some(100_000), Some(90), 1)), ], - ["lcm-memory", "lcm"], + ["lcm-memory", "coding-lcm"], ) } diff --git a/test/harness/lcm_preparation_test.gleam b/test/harness/lcm_preparation_test.gleam index 02d41bb2c..25d5a5cd4 100644 --- a/test/harness/lcm_preparation_test.gleam +++ b/test/harness/lcm_preparation_test.gleam @@ -28,7 +28,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> let assert Ok(host) = runtime.start_with_config( ":memory:", - extensions.Config(installed, ["lcm-memory", "lcm"]), + extensions.Config(installed, ["lcm-memory", "coding-lcm"]), ) let ledger = runtime.ledger(host) let assert Ok(_) = conversation.initialise(ledger) @@ -126,7 +126,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> next, ) }) - failed |> should.equal(Error("compaction lcm: summary unavailable")) + failed |> should.equal(Error("compaction coding-lcm: summary unavailable")) // Only the uncovered rows, the newest turn included to size the tail. decodes |> should.equal(3) graph.last_seq(ledger, "preparation") |> should.equal(Ok(last.source.seq)) diff --git a/test/harness/lcm_test.gleam b/test/harness/lcm_test.gleam index c7edf3e6d..06722d9b8 100644 --- a/test/harness/lcm_test.gleam +++ b/test/harness/lcm_test.gleam @@ -38,7 +38,7 @@ fn host_with( ":memory:", extensions.Config(installed, [ "lcm-memory", - "lcm", + "coding-lcm", ..list.map(others, fn(other) { other.name }) ]), ) @@ -564,7 +564,7 @@ fn archive() -> extension.Extension { [], [ extension.FoldPlugin( - compaction.Folds("archive", "archive", fn(_, _, _, history) { + compaction.Folds("archive", ["archive"], fn(_, _, _, history) { let assert Ok(#(_, rest)) = compaction.resume(history, compaction.cut_of(list.take(history, 4))) Ok(compaction.Prior([types.User("[archive pages]")], rest)) @@ -626,7 +626,7 @@ fn mismatched_archive() -> extension.Extension { [], [ extension.FoldPlugin( - compaction.Folds("archive", "archive", fn(_, _, _, history) { + compaction.Folds("archive", ["archive"], fn(_, _, _, history) { let assert Ok(#(_, [_, ..rest])) = compaction.resume(history, compaction.cut_of(list.take(history, 4))) Ok( @@ -725,7 +725,7 @@ fn tight(capacity: Int, tail: Int) -> #(runtime.Runtime, runtime.Session) { let assert Ok(host) = runtime.start_with_config( ":memory:", - extensions.Config(installed, ["lcm-memory", "lcm"]), + extensions.Config(installed, ["lcm-memory", "coding-lcm"]), ) let ledger = runtime.ledger(host) let assert Ok(_) = conversation.initialise(ledger) diff --git a/test/harness/summary_finish_test.gleam b/test/harness/summary_finish_test.gleam new file mode 100644 index 000000000..b98a6b325 --- /dev/null +++ b/test/harness/summary_finish_test.gleam @@ -0,0 +1,56 @@ +//// A summarizer reply that stopped early must never be kept as a summary: +//// a refusal or a filter keeps nothing, and so does an output limit reached +//// while the reply was still short, which is how a reply ends when its +//// thinking spent the budget. Each provider maps its own stop reasons onto +//// `types.Finish`, and the fake E2E provider can produce only a few of them, +//// so this covers every finish against the one rule they all reach. + +import albedo/harness/compaction +import albedo/openai_api/types +import gleam/string +import gleeunit/should + +pub fn a_finished_reply_is_kept_trimmed_test() -> Nil { + compaction.reply_text(" remembered ", types.Complete) + |> should.equal(Ok("remembered")) + compaction.reply_text("remembered", types.ToolCalls) + |> should.equal(Ok("remembered")) +} + +pub fn an_empty_reply_is_empty_whatever_stopped_it_test() -> Nil { + compaction.reply_text(" ", types.Complete) + |> should.equal(Error(compaction.empty_summary)) + compaction.reply_text("", types.OtherFinish("refusal")) + |> should.equal(Error(compaction.empty_summary)) +} + +pub fn a_refused_or_filtered_reply_keeps_nothing_test() -> Nil { + let assert Error(refused) = + compaction.reply_text( + "# Session memory\n\nThe user is ana (DM channel `1560837207336689", + types.OtherFinish("refusal"), + ) + compaction.unfinished_summary(refused) |> should.be_true + let assert Error(filtered) = + compaction.reply_text("partial", types.ContentFiltered) + compaction.unfinished_summary(filtered) |> should.be_true +} + +pub fn a_short_reply_cut_at_its_limit_keeps_nothing_test() -> Nil { + let assert Error(reason) = + compaction.reply_text("a title and half a line", types.LengthLimit) + compaction.unfinished_summary(reason) |> should.be_true +} + +pub fn a_long_reply_cut_at_its_limit_says_where_it_stopped_test() -> Nil { + let long = string.repeat("remembered ", 400) + let assert Ok(kept) = compaction.reply_text(long, types.LengthLimit) + string.starts_with(kept, "remembered") |> should.be_true + string.ends_with(kept, "[the reply reached its output limit here]") + |> should.be_true +} + +pub fn other_errors_are_not_recoverable_test() -> Nil { + compaction.unfinished_summary("summarizer provider request failed: 500") + |> should.be_false +} -- knotmirror 0.0.1