diff --git a/robot-docs/compaction.md b/robot-docs/compaction.md index a808df46e..24c21fba6 100644 --- a/robot-docs/compaction.md +++ b/robot-docs/compaction.md @@ -40,6 +40,8 @@ A failed rewrite keeps the old notes, logs once, and says so in the `/context` o A `/reload` adds a `capabilities changed` note that carries the extension context, and the next compaction rebuilds the system prompt. Every strategy leaves such notes out of what it evicts: `snapcompact` omits them from the archive, and the summarizer, which rolling, LCM and `notes` share, never reads them. The summarizer sees an assistant turn as its text and calls, not raw provider JSON, and skips encrypted reasoning. Notes still in the verbatim tail stay, because they are how the model learns of a reload while the old prompt is pinned. +A daemon restart, or an unload that drops the session's prepared composition, reads the extension context again, the way a reload does. The session keeps the prompt the model last knew it by (`known_instructions`, `known_context`, and a hash of the tools in `known_tools` on `sessions`) and compares the fresh prompt against it when a kernel is adopted: an unchanged prompt needs nothing; a changed one with the same tools is pinned with the same `capabilities changed` note a reload adds; a changed tool set misses the cache anyway, so the current prompt goes out. The pin starts at the head the last prepared request reported (`prepared_head`), so a session that compacted before the restart keeps it until its next compaction. + ## image payload lifecycle When a compaction plugin commits a new projection — through `/compact` or the automatic trigger — it signals cleanup before the next provider request. Tool-output images absent from that projection are elided: the transcript row and its Python cell keep their text and gain `[image elided and is no longer available]`, and each payload is deleted once no transcript row or pinned prompt names its hash. Tool outputs in the verbatim tail keep their images. User uploads are never elided, because their hashes are part of the saved compaction cut. Reusing a saved projection does not trigger cleanup; neither do ordinary turns or failed compactions. diff --git a/src/albedo/daemon/conversation.gleam b/src/albedo/daemon/conversation.gleam index c00994b16..1153d27fd 100644 --- a/src/albedo/daemon/conversation.gleam +++ b/src/albedo/daemon/conversation.gleam @@ -1862,6 +1862,83 @@ pub fn clear_prompt_pin(store: store.Store, id: String) -> Result(Nil, String) { ) } +/// The prompt the model last knew the session by, sent or announced in a +/// capability note, and a hash of the tools offered beside it. A prompt +/// prepared afresh after a restart or an unload is compared against it. +pub fn known_prompt( + store: store.Store, + id: String, +) -> Result(Option(#(PinnedPrompt, String)), String) { + use rows <- result.try( + store.read( + store, + "SELECT known_instructions, known_context, known_tools FROM sessions WHERE id=? AND known_instructions IS NOT NULL", + [sqlight.text(id)], + { + use instructions <- decode.field(0, decode.string) + use context <- decode.field(1, decode.bit_array) + use tools <- decode.field(2, decode.string) + decode.success(#(instructions, context, tools)) + }, + ), + ) + case rows { + [#(instructions, context, tools)] -> + Ok( + unpack_list(context, images.reader(store)) + |> result.map(fn(context) { + #(PinnedPrompt(instructions, context), tools) + }) + |> option.from_result, + ) + _ -> Ok(None) + } +} + +pub fn remember_prompt( + store: store.Store, + id: String, + prompt: PinnedPrompt, + tools: String, +) -> Result(Nil, String) { + store.write( + store, + "UPDATE sessions SET known_instructions=?, known_context=?, known_tools=? WHERE id=?", + [ + sqlight.text(prompt.instructions), + sqlight.blob(pack_list(prompt.context)), + sqlight.text(tools), + sqlight.text(id), + ], + ) +} + +/// How many original inputs the session's last prepared request had +/// compaction stand in for: the baseline a pin made after a restart starts at. +pub fn prepared_head( + store: store.Store, + id: String, +) -> Result(Option(Int), String) { + store.read( + store, + "SELECT prepared_head FROM sessions WHERE id=? AND prepared_head IS NOT NULL", + [sqlight.text(id)], + decode.field(0, decode.int, decode.success), + ) + |> result.map(fn(rows) { list.first(rows) |> option.from_result }) +} + +pub fn save_prepared_head( + store: store.Store, + id: String, + head: Int, +) -> Result(Nil, String) { + store.write(store, "UPDATE sessions SET prepared_head=? WHERE id=?", [ + sqlight.int(head), + sqlight.text(id), + ]) +} + /// The entries inputs committed together become. A response's thinking time /// goes on its first input that shows the thinking, so it is counted once. pub fn entries( diff --git a/src/albedo/daemon/migrations/conversation_columns.gleam b/src/albedo/daemon/migrations/conversation_columns.gleam index 8b54f8354..62fd68926 100644 --- a/src/albedo/daemon/migrations/conversation_columns.gleam +++ b/src/albedo/daemon/migrations/conversation_columns.gleam @@ -25,6 +25,10 @@ pub fn apply(db: sqlight.Connection) -> Result(Nil, String) { #("pinned_instructions", "TEXT"), #("pinned_context", "BLOB"), #("pinned_head", "INTEGER"), + #("known_instructions", "TEXT"), + #("known_context", "BLOB"), + #("known_tools", "TEXT"), + #("prepared_head", "INTEGER"), #("name", "TEXT"), #("input_order", "INTEGER NOT NULL DEFAULT 0"), #("created_at", "INTEGER"), diff --git a/src/albedo/daemon/requests.gleam b/src/albedo/daemon/requests.gleam index 016deda25..dd777f2df 100644 --- a/src/albedo/daemon/requests.gleam +++ b/src/albedo/daemon/requests.gleam @@ -132,22 +132,28 @@ pub fn direct_prefix( fn head_hash(instructions: String, tools: List(types.Tool)) -> String { json.object([ #("instructions", json.string(instructions)), - #( - "tools", - json.array(tools, fn(tool) { - json.object([ - #("name", json.string(tool.name)), - #("description", json.string(tool.description)), - #("parameters", tool.parameters), - #("strict", json.bool(tool.strict)), - ]) - }), - ), + #("tools", tools_json(tools)), ]) |> json.to_string |> hash } +/// The hash of the tools a request offers, as its head hash encodes them. +pub fn tools_hash(tools: List(types.Tool)) -> String { + tools_json(tools) |> json.to_string |> hash +} + +fn tools_json(tools: List(types.Tool)) -> Json { + json.array(tools, fn(tool) { + json.object([ + #("name", json.string(tool.name)), + #("description", json.string(tool.description)), + #("parameters", tool.parameters), + #("strict", json.bool(tool.strict)), + ]) + }) +} + /// The hash of a run of inputs, as request rows identify them. fn inputs_hash(inputs: List(types.Input)) -> String { inputs diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 43169686f..b471d75e7 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -21,6 +21,7 @@ import albedo/daemon/session_configure import albedo/daemon/session_extensions import albedo/daemon/session_history import albedo/daemon/session_namespace +import albedo/daemon/session_prompt import albedo/daemon/session_provider import albedo/daemon/session_run import albedo/daemon/session_state @@ -313,6 +314,10 @@ pub fn start( runtime.ledger(host), info.id, )) + use prepared_head <- result.try(conversation.prepared_head( + runtime.ledger(host), + info.id, + )) case conversation.resumable(info.stage) { True -> process.send(self, Resume) False -> Nil @@ -351,7 +356,7 @@ pub fn start( Some(#(prompt, head)) -> loop.Pinned(prompt, Some(head)) None -> loop.Unpinned }, - prepared_head: None, + prepared_head: prepared_head, last_touch: clock.monotonic_ms(), booting: None, blocked_until: 0, @@ -1569,15 +1574,11 @@ fn handle( True, Some(head), loop.Pinned(prompt, _) -> actor.continue( session_state.State( - ..state, + ..prepared(state, head), pin: loop.Pinned(prompt, Some(head)), - prepared_head: Some(head), ), ) - True, Some(head), loop.Unpinned -> - actor.continue( - session_state.State(..state, prepared_head: Some(head)), - ) + True, Some(head), loop.Unpinned -> actor.continue(prepared(state, head)) True, None, loop.Pinned(..) -> case conversation.clear_prompt_pin( @@ -2203,6 +2204,34 @@ fn adopt(state: State, kernel: runtime.Session) -> State { session_history.ensure_history(state) |> result.unwrap(state) |> session_namespace.adopt(kernel) + |> session_prompt.reconcile_prompt +} + +/// Records the head a prepared request reported. It moves when compaction +/// does, and is saved then, so a pin made after a restart starts at it. +fn prepared(state: State, head: Int) -> State { + let moved = state.prepared_head != Some(head) + let state = session_state.State(..state, prepared_head: Some(head)) + case moved { + False -> state + True -> + case + conversation.save_prepared_head( + runtime.ledger(state.host), + state.info.id, + head, + ) + { + Ok(_) -> state + Error(error) -> + session_state.emit( + state, + view.error( + "the prepared request head could not be saved: " <> error, + ), + ) + } + } } fn kernel_opened( diff --git a/src/albedo/daemon/session_extensions.gleam b/src/albedo/daemon/session_extensions.gleam index bd98f85ac..5e9a3a3d0 100644 --- a/src/albedo/daemon/session_extensions.gleam +++ b/src/albedo/daemon/session_extensions.gleam @@ -94,7 +94,10 @@ pub fn change( } False -> session_prompt.reset_prompt_cache(state, namespace) } - #(state, runtime.extension_summaries(state.host, state.info.id)) + #( + session_prompt.remember_prompt(state), + runtime.extension_summaries(state.host, state.info.id), + ) } } } @@ -160,6 +163,7 @@ pub fn reload( ) } } + let state = session_prompt.remember_prompt(state) let warnings = list.append(warnings, case kernel { Some(kernel) -> runtime.warnings(kernel) diff --git a/src/albedo/daemon/session_prompt.gleam b/src/albedo/daemon/session_prompt.gleam index 1434df19d..1e15f0c9e 100644 --- a/src/albedo/daemon/session_prompt.gleam +++ b/src/albedo/daemon/session_prompt.gleam @@ -3,6 +3,7 @@ import albedo/daemon/conversation import albedo/daemon/events as view import albedo/daemon/note +import albedo/daemon/requests import albedo/daemon/session_history import albedo/daemon/session_state import albedo/harness/loop @@ -160,6 +161,89 @@ fn changes(previous: String, current: String) -> String { } } +/// Saves the prompt the model now knows the session by, so a composition +/// prepared afresh can be compared against it. +pub fn remember_prompt( + state: session_state.State(message), +) -> session_state.State(message) { + case state.kernel, runtime.peek_prompt(state.host, state.info.id) { + Some(kernel), Some(#(instructions, context)) -> + case + conversation.remember_prompt( + runtime.ledger(state.host), + state.info.id, + conversation.PinnedPrompt(instructions, context), + requests.tools_hash(runtime.tools(kernel)), + ) + { + Ok(_) -> state + Error(error) -> + session_state.emit( + state, + view.error("the session prompt could not be saved: " <> error), + ) + } + _, _ -> state + } +} + +/// A kernel arrived, maybe with a composition prepared afresh after a daemon +/// restart or an unload, which read its context again. The model still knows +/// the prompt it was last told: an unchanged one needs nothing, a changed one +/// with the same tools is pinned and announced as a live reload would be, and +/// a changed tool set misses the cache anyway, so the current prompt is used. +pub fn reconcile_prompt( + state: session_state.State(message), +) -> session_state.State(message) { + let current = + runtime.peek_prompt(state.host, state.info.id) + |> option.map(fn(prompt) { conversation.PinnedPrompt(prompt.0, prompt.1) }) + let tools = + option.map(state.kernel, fn(kernel) { + requests.tools_hash(runtime.tools(kernel)) + }) + case conversation.known_prompt(runtime.ledger(state.host), state.info.id) { + Error(error) -> + session_state.emit( + state, + view.error("the saved session prompt could not be read: " <> error), + ) + Ok(Some(#(known, known_tools))) if Some(known_tools) == tools -> + case Some(known) == current { + True -> state + False -> pin_known_prompt(state, known) + } + Ok(_) -> remember_prompt(state) + } +} + +fn pin_known_prompt( + state: session_state.State(message), + known: conversation.PinnedPrompt, +) -> session_state.State(message) { + case pin_changed_prompt(state, Some(#(known.instructions, known.context))) { + // Without history there is no cached prompt to keep. + Ok(#(state, "")) -> state + Ok(#(state, detail)) -> + session_state.emit( + state, + view.note( + "daemon", + "the session prompt changed while unloaded" <> detail, + ), + ) + Error(error) -> + session_state.emit( + state, + view.error( + "the session prompt changed while unloaded, but the capability notice could not be saved: " + <> error, + ), + ) + } + |> remember_prompt +} + /// Pin the old prompt until compaction, while reporting live capability changes. pub fn pin_changed_prompt( state: session_state.State(message), diff --git a/test/e2e/extensions_test.py b/test/e2e/extensions_test.py index 9d5673272..a8a363588 100644 --- a/test/e2e/extensions_test.py +++ b/test/e2e/extensions_test.py @@ -709,6 +709,43 @@ class ExtensionTests(unittest.TestCase): (request,) = self.turn("pin stays released") self.assertIn("another live skill", request["instructions"]) + # exclusive: restarts the daemon + @exclusive + def test_restart_keeps_sent_system_prompt_until_compaction(self): + for index in range(3): + self.turn(f"older turn {index}") + self.compact() + self.app.idle(self.sid) + (sent,) = self.turn("turn after compaction") + self.assertIn("[older conversation summary;", json.dumps(sent["input"])) + self.skill.write_text( + SKILL.replace( + "catalog-only fixture description", "edited while the daemon was down" + ) + ) + self.restart() + (request,) = self.turn("first turn after restart") + self.assertEqual(request["instructions"], sent["instructions"]) + updates = [ + item["content"] + for item in request["input"] + if item.get("role") == "user" + and "capabilities changed" in str(item.get("content", "")) + ] + self.assertEqual(len(updates), 1) + self.assertIn("edited while the daemon was down", updates[0]) + self.restart() + (request,) = self.turn("unchanged restart") + self.assertEqual(request["instructions"], sent["instructions"]) + self.assertEqual( + sum( + "capabilities changed" in str(item.get("content", "")) + for item in request["input"] + if item.get("role") == "user" + ), + 1, + ) + # exclusive: changes global compaction settings and restarts the daemon @exclusive def test_auto_compaction_releases_pin_on_first_turn_after_restart(self):