From 1409e1078250bdd367abc858392fca21d7591615 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:14:12 +0000 Subject: [PATCH 01/24] [db] Store the agent's conversations and their turns in migration 7 The agent's session and its turns live in a new agent schema, retained by the conversation-record profile: a session belongs to the caller's environment, subject and view, and each turn is one exchange, its retrieval event stored metadata-only so a restore rebuilds it exactly. No route reads them yet. Co-Authored-By: Claude Code --- .../compass.db/types/agent_session_row.hpp | 52 +++++ .../types/agent_session_row_codec.hpp | 88 ++++++++ .../compass.db/types/agent_turn_row.hpp | 97 +++++++++ .../compass.db/types/agent_turn_row_codec.hpp | 118 ++++++++++ .../modeling/compass.db.agent_session.org | 130 +++++++++++ .../modeling/compass.db.agent_turn.org | 202 ++++++++++++++++++ .../compass.db/modeling/compass.db.schema.org | 3 +- .../modeling/component_overview.org | 7 + projects/compass.db/sql/schema.sql | 37 ++++ projects/compass.db/src/CMakeLists.txt | 2 + projects/compass.db/src/ops/migrations.cpp | 39 ++++ .../src/types/agent_session_row_codec.cpp | 39 ++++ .../src/types/agent_turn_row_codec.cpp | 39 ++++ projects/compass.db/tests/CMakeLists.txt | 2 + .../types_agent_session_row_codec_tests.cpp | 84 ++++++++ .../types_agent_turn_row_codec_tests.cpp | 84 ++++++++ .../variability_conversation_record.org | 35 +++ 17 files changed, 1057 insertions(+), 1 deletion(-) create mode 100644 projects/compass.db/include/compass.db/types/agent_session_row.hpp create mode 100644 projects/compass.db/include/compass.db/types/agent_session_row_codec.hpp create mode 100644 projects/compass.db/include/compass.db/types/agent_turn_row.hpp create mode 100644 projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp create mode 100644 projects/compass.db/modeling/compass.db.agent_session.org create mode 100644 projects/compass.db/modeling/compass.db.agent_turn.org create mode 100644 projects/compass.db/src/types/agent_session_row_codec.cpp create mode 100644 projects/compass.db/src/types/agent_turn_row_codec.cpp create mode 100644 projects/compass.db/tests/types_agent_session_row_codec_tests.cpp create mode 100644 projects/compass.db/tests/types_agent_turn_row_codec_tests.cpp create mode 100644 projects/modeling/variability_conversation_record.org diff --git a/projects/compass.db/include/compass.db/types/agent_session_row.hpp b/projects/compass.db/include/compass.db/types/agent_session_row.hpp new file mode 100644 index 00000000..561fc656 --- /dev/null +++ b/projects/compass.db/include/compass.db/types/agent_session_row.hpp @@ -0,0 +1,52 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_row.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_DB_TYPES_AGENT_SESSION_ROW_HPP +#define COMPASS_DB_TYPES_AGENT_SESSION_ROW_HPP + +#include +#include +#include + +namespace compass::db::types { + +/** + * @brief One conversation of the compass agent. + * + * A row of agent.agent_session. + */ +struct agent_session_row { + std::string environment; + std::string subject; + std::optional actor; + std::string view_name; + std::optional title; + std::chrono::sys_time updated_at; + + bool operator==(const agent_session_row&) const = default; +}; + +} + +#endif diff --git a/projects/compass.db/include/compass.db/types/agent_session_row_codec.hpp b/projects/compass.db/include/compass.db/types/agent_session_row_codec.hpp new file mode 100644 index 00000000..2605174e --- /dev/null +++ b/projects/compass.db/include/compass.db/types/agent_session_row_codec.hpp @@ -0,0 +1,88 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_DB_TYPES_AGENT_SESSION_ROW_CODEC_HPP +#define COMPASS_DB_TYPES_AGENT_SESSION_ROW_CODEC_HPP + +#include "compass.db/codec/text_form.hpp" +#include "compass.db/codec/wire_fields.hpp" +#include "compass.db/codec/wire_traits_fwd.hpp" +#include "compass.db/types/agent_session_row.hpp" +#include +#include +#include + +namespace compass::db::types { + +/** + * @brief The members of agent_session_row, named as the wire names them and in the + * order the type declares them. + * + * This is the one statement of the row's shape. The carriers find it by + * argument-dependent lookup, so no caller passes a list, and a message whose + * member is this type encodes it as its own object without knowing the type. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &agent_session_row::environment}, + ::compass::db::codec::field{"subject", &agent_session_row::subject}, + ::compass::db::codec::field{"actor", &agent_session_row::actor}, + ::compass::db::codec::field{"view_name", &agent_session_row::view_name}, + ::compass::db::codec::field{"title", &agent_session_row::title}, + ::compass::db::codec::field{"updated_at", &agent_session_row::updated_at}, + }; +} + +} + +namespace compass::db::codec { + +/** + * @brief The generated codec: what the wire codec resolves to for this type. + * + * The functions are declared here and defined in this type's own translation + * unit, so a translation unit that only sends the type compiles a declaration + * rather than a second copy of the encoder. + */ +template <> +struct wire_traits { + /** + * @brief States that this is a generated codec. + * + * A test asserts this rather than the encoding, because the encoding is + * what the type's own case already round-trips: what it cannot see is + * whether the seam resolved to this specialisation or fell through to the + * primary template, and a marker that only this specialisation declares + * is that answer at compile time. + */ + static constexpr bool is_generated = true; + + static std::string write_json(const compass::db::types::agent_session_row& v); + + static compass::db::types::agent_session_row read_json(std::string_view text); +}; + +} + +#endif diff --git a/projects/compass.db/include/compass.db/types/agent_turn_row.hpp b/projects/compass.db/include/compass.db/types/agent_turn_row.hpp new file mode 100644 index 00000000..bdf3c42c --- /dev/null +++ b/projects/compass.db/include/compass.db/types/agent_turn_row.hpp @@ -0,0 +1,97 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_row.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_DB_TYPES_AGENT_TURN_ROW_HPP +#define COMPASS_DB_TYPES_AGENT_TURN_ROW_HPP + +#include +#include +#include +#include +#include + +namespace compass::db::types { + +/** + * @brief The values of agent.agent_turn.status. + */ +enum class agent_turn_status : std::uint8_t { streaming, done, failed, stopped, cut }; + +/** + * @brief Each value of agent_turn_status as agent.agent_turn stores it. + */ +[[nodiscard]] constexpr std::string_view to_string(agent_turn_status v) noexcept { + switch (v) { + case agent_turn_status::streaming: return "streaming"; + case agent_turn_status::done: return "done"; + case agent_turn_status::failed: return "failed"; + case agent_turn_status::stopped: return "stopped"; + case agent_turn_status::cut: return "cut"; + } + return "streaming"; +} + +/** + * @brief The agent_turn_status @p text names, or none for any other text. + */ +[[nodiscard]] constexpr std::optional agent_turn_status_of( + std::string_view text) noexcept { + if (text == "streaming") + return agent_turn_status::streaming; + if (text == "done") + return agent_turn_status::done; + if (text == "failed") + return agent_turn_status::failed; + if (text == "stopped") + return agent_turn_status::stopped; + if (text == "cut") + return agent_turn_status::cut; + return std::nullopt; +} + +/** + * @brief One exchange of a conversation with the compass agent. + * + * A row of agent.agent_turn. + */ +struct agent_turn_row { + std::int64_t session_id = 0; + std::int32_t ord = 0; + std::string question; + std::chrono::sys_time asked_at; + std::string retrieval; + std::string answer; + agent_turn_status status = agent_turn_status::streaming; + std::optional done; + std::optional failure; + std::string model; + std::optional actor; + std::chrono::sys_time updated_at; + + bool operator==(const agent_turn_row&) const = default; +}; + +} + +#endif diff --git a/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp b/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp new file mode 100644 index 00000000..a93b5b95 --- /dev/null +++ b/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp @@ -0,0 +1,118 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_DB_TYPES_AGENT_TURN_ROW_CODEC_HPP +#define COMPASS_DB_TYPES_AGENT_TURN_ROW_CODEC_HPP + +#include "compass.db/codec/text_form.hpp" +#include "compass.db/codec/wire_fields.hpp" +#include "compass.db/codec/wire_traits_fwd.hpp" +#include "compass.db/types/agent_turn_row.hpp" +#include +#include +#include +#include + +namespace compass::db::types { + +/** + * @brief The members of agent_turn_row, named as the wire names them and in the + * order the type declares them. + * + * This is the one statement of the row's shape. The carriers find it by + * argument-dependent lookup, so no caller passes a list, and a message whose + * member is this type encodes it as its own object without knowing the type. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"session_id", &agent_turn_row::session_id}, + ::compass::db::codec::field{"ord", &agent_turn_row::ord}, + ::compass::db::codec::field{"question", &agent_turn_row::question}, + ::compass::db::codec::field{"asked_at", &agent_turn_row::asked_at}, + ::compass::db::codec::field{"retrieval", &agent_turn_row::retrieval}, + ::compass::db::codec::field{"answer", &agent_turn_row::answer}, + ::compass::db::codec::field{"status", &agent_turn_row::status}, + ::compass::db::codec::field{"done", &agent_turn_row::done}, + ::compass::db::codec::field{"failure", &agent_turn_row::failure}, + ::compass::db::codec::field{"model", &agent_turn_row::model}, + ::compass::db::codec::field{"actor", &agent_turn_row::actor}, + ::compass::db::codec::field{"updated_at", &agent_turn_row::updated_at}, + }; +} + +} + +namespace compass::db::codec { + +/** + * @brief agent_turn_status travels as the name of its value. + */ +template <> +struct text_form { + static constexpr std::string_view wire_name = "a agent_turn_status"; + + static constexpr std::string_view names[] = { "streaming", "done", "failed", "stopped", "cut" }; + + static constexpr compass::db::types::agent_turn_status values[] = { compass::db::types::agent_turn_status::streaming, compass::db::types::agent_turn_status::done, compass::db::types::agent_turn_status::failed, compass::db::types::agent_turn_status::stopped, compass::db::types::agent_turn_status::cut }; + + static std::string to_text(compass::db::types::agent_turn_status v) { + return std::string(to_string(v)); + } + + static compass::db::types::agent_turn_status from_text(std::string_view text) { + if (const auto v = compass::db::types::agent_turn_status_of(text)) + return *v; + throw std::invalid_argument("Not " + std::string(wire_name) + ": '" + + std::string(text) + "' is not one of streaming, done, failed, stopped, cut"); + } +}; + +/** + * @brief The generated codec: what the wire codec resolves to for this type. + * + * The functions are declared here and defined in this type's own translation + * unit, so a translation unit that only sends the type compiles a declaration + * rather than a second copy of the encoder. + */ +template <> +struct wire_traits { + /** + * @brief States that this is a generated codec. + * + * A test asserts this rather than the encoding, because the encoding is + * what the type's own case already round-trips: what it cannot see is + * whether the seam resolved to this specialisation or fell through to the + * primary template, and a marker that only this specialisation declares + * is that answer at compile time. + */ + static constexpr bool is_generated = true; + + static std::string write_json(const compass::db::types::agent_turn_row& v); + + static compass::db::types::agent_turn_row read_json(std::string_view text); +}; + +} + +#endif diff --git a/projects/compass.db/modeling/compass.db.agent_session.org b/projects/compass.db/modeling/compass.db.agent_session.org new file mode 100644 index 00000000..7a7e446a --- /dev/null +++ b/projects/compass.db/modeling/compass.db.agent_session.org @@ -0,0 +1,130 @@ +:PROPERTIES: +:ID: BE684A24-5B70-4BF6-9779-415345C2C987 +:END: +#+title: compass.db.agent_session +#+description: Codegen entity model for agent.agent_session: one conversation of the compass agent, owned by a caller's environment, subject and view. +#+type: masd.codegen.entity +#+component: db +#+filetags: :model:entity:database: +#+brief: One conversation of the compass agent. +#+entity_singular: agent_session +#+entity_plural: agent_sessions +#+created: 2026-12-02 +#+updated: 2026-12-02 + +One row per conversation. A session belongs to the environment, subject and +view name of the caller that made it, and a restore requires all three. The +environment is text, not a reference to =corpus.environment=, so a session +outlives its environment, as a campaign does. The turns of the session are +=agent.agent_turn=. + +* Flags +:PROPERTIES: +:product: compass +:component: db +:schema: agent +:profile: conversation-record +:END: + +The profile =conversation-record= fixes =retained=: the transcript exists +nowhere else, so a model change that drops or retypes one of its columns +needs a migration in the same pull request. + +* Columns + +** id +:PROPERTIES: +:type: bigint +:primary_key: true +:key_kind: identity +:END: + +The session's identity. =GENERATED ALWAYS AS IDENTITY=: read back, never +written. + +** environment +:PROPERTIES: +:type: text +:END: + +The name of the environment the session belongs to. It is text, not a +reference to =corpus.environment=, so a session outlives its environment. + +** subject +:PROPERTIES: +:type: text +:END: + +The =Compass-Subject= of the caller that made the session. + +** actor +:PROPERTIES: +:type: text +:nullable: true +:END: + +The =Compass-Actor= of the caller, when the gateway named one: the agent +that acted for the subject. + +** view_name +:PROPERTIES: +:type: text +:END: + +The name of the caller's view. Ownership is the triple environment, subject +and view name, enforced by every query that reads, asks into or deletes the +session. + +** title +:PROPERTIES: +:type: text +:nullable: true +:END: + +The session's title: what the create route was given, else the first 80 +code points of its first question. NULL until the first question titles it. + +** created_at +:PROPERTIES: +:type: timestamptz +:default: now() +:written_by: database +:END: + +When the session was made. The database writes it. + +** updated_at +:PROPERTIES: +:type: timestamptz +:default: now() +:END: + +When the session last changed: a turn or its answer. Every write sets it. + +* SQL + +** Indexes + +The caller's sessions, most recently changed first. + +| name | columns | unique | where | using | opclass | +|-------+-------------------------------------------+--------+-------+-------+---------| +| owner | environment, subject, view_name, updated_at | false | | | | + +* C++ + +The generated row is =compass::db::types::agent_session_row= of +=compass.db/types/agent_session_row.hpp=. The profile leaves the COPY writer +off: the service writes the table with its own SQL. + +* Notes + +The =agent= schema is new in migration 7, apart from the =activity= schema +whose rows are test campaigns: a conversation is a different domain from +what people did to test the product. + +* See also + +- [[id:4906B02A-7BDE-485D-9F1C-B2F8DA49DCF7][compass.db.agent_turn]]: the exchanges of the session. +- [[id:493B7D68-516E-4430-B4CE-688C6FBE1271][compass.db]]: the component overview, which lists every model. +- [[id:7FD52505-1436-4925-A1DE-4A3EC88F0133][Investigation: How compass generates itself]]: the features, key kinds and profiles these models use. diff --git a/projects/compass.db/modeling/compass.db.agent_turn.org b/projects/compass.db/modeling/compass.db.agent_turn.org new file mode 100644 index 00000000..3bd46cb8 --- /dev/null +++ b/projects/compass.db/modeling/compass.db.agent_turn.org @@ -0,0 +1,202 @@ +:PROPERTIES: +:ID: 4906B02A-7BDE-485D-9F1C-B2F8DA49DCF7 +:END: +#+title: compass.db.agent_turn +#+description: Codegen entity model for agent.agent_turn: one exchange of a conversation with the compass agent, its question, the passages it was given and the answer it gave. +#+type: masd.codegen.entity +#+component: db +#+filetags: :model:entity:database: +#+brief: One exchange of a conversation with the compass agent. +#+entity_singular: agent_turn +#+entity_plural: agent_turns +#+created: 2026-12-02 +#+updated: 2026-12-02 + +One row per exchange, not per message: the question and the answer are +columns of one row. The row is the browser's turn and the model's history +entry. Passage text is never stored; =retrieval= holds the metadata-only +=agent_passages_event= the stream sent, so a restore rebuilds citations and +timings exactly as they were. + +* Flags +:PROPERTIES: +:product: compass +:component: db +:schema: agent +:profile: conversation-record +:END: + +The profile =conversation-record= fixes =retained=: the transcript exists +nowhere else, so a model change that drops or retypes one of its columns +needs a migration in the same pull request. + +* Columns + +** id +:PROPERTIES: +:type: bigint +:primary_key: true +:key_kind: identity +:END: + +The turn's identity. =GENERATED ALWAYS AS IDENTITY=: read back, never +written. + +** session_id +:PROPERTIES: +:type: bigint +:END: + +The session the exchange belongs to. + +** ord +:PROPERTIES: +:type: integer +:END: + +The exchange's place in its session, from 1. A session's questions are +numbered under the lock the ask takes on the session row. + +** question +:PROPERTIES: +:type: text +:END: + +What the caller asked, as given. + +** asked_at +:PROPERTIES: +:type: timestamptz +:END: + +When the question arrived at the service. + +** retrieval +:PROPERTIES: +:type: jsonb +:END: + +The =agent_passages_event= the stream sent: the searches, the passages' +metadata and the retrieval time. The passages' text stays out: a stored +transcript names documents, never their text. + +** answer +:PROPERTIES: +:type: text +:default: '' +:END: + +The answer as it has streamed so far. Every two seconds while it streams, +a snapshot replaces it, so a crash restores the last partial rather than an +empty cut. A terminal write replaces it with the whole answer. + +** status +:PROPERTIES: +:type: text +:values: streaming done failed stopped cut +:default: 'streaming' +:END: + +How the exchange ended: =streaming= while the answer is written, =done= when +the model ended it, =failed= when llama-server could not answer, =stopped= +when the client went away, and =cut= for a row neither the stream nor the +client settled, as when the service stopped mid-answer. Startup recovery +turns every leftover =streaming= row into =cut=. + +** done +:PROPERTIES: +:type: jsonb +:nullable: true +:END: + +The =agent_done_event= the stream sent, with the citations and timings; +NULL unless =status= is =done=. + +** failure +:PROPERTIES: +:type: jsonb +:nullable: true +:END: + +The =agent_failure_event= the stream sent, with the health code and the +message; NULL unless =status= is =failed=. + +** model +:PROPERTIES: +:type: text +:END: + +The model file the answer came from, as the settings named it when the +question arrived. + +** actor +:PROPERTIES: +:type: text +:nullable: true +:END: + +The =Compass-Actor= of the caller that asked, when the gateway named one. + +** created_at +:PROPERTIES: +:type: timestamptz +:default: now() +:written_by: database +:END: + +When the row was written. The database writes it. + +** updated_at +:PROPERTIES: +:type: timestamptz +:default: now() +:END: + +When the row last changed: a partial snapshot or the terminal write. + +* Foreign keys + +** session_id +:PROPERTIES: +:references: agent.agent_session +:on_delete: cascade +:END: + +Deleting a session deletes its turns. + +* SQL + +** Unique + +A session numbers its exchanges once. + +| columns | +|------------------| +| session_id, ord | + +** Indexes + +The rows a restart has to settle. + +| name | columns | unique | where | using | opclass | +|-----------+------------+--------+----------------------+-------+---------| +| streaming | session_id | false | status = 'streaming' | | | + +* C++ + +The generated row is =compass::db::types::agent_turn_row= of +=compass.db/types/agent_turn_row.hpp=, with =agent_turn_status= from its +=:values:=. The profile leaves the COPY writer off: the service writes the +table with its own SQL. + +* Notes + +The unique constraint is a table constraint, =agent_turn_session_id_ord_key=, +not a unique index, so a restore may rely on =ON CONFLICT= and the generated +catalog matches migration 7's. + +* See also + +- [[id:BE684A24-5B70-4BF6-9779-415345C2C987][compass.db.agent_session]]: the conversation the exchange belongs to. +- [[id:493B7D68-516E-4430-B4CE-688C6FBE1271][compass.db]]: the component overview, which lists every model. +- [[id:7FD52505-1436-4925-A1DE-4A3EC88F0133][Investigation: How compass generates itself]]: the features, key kinds and profiles these models use. diff --git a/projects/compass.db/modeling/compass.db.schema.org b/projects/compass.db/modeling/compass.db.schema.org index d7c01cc3..2f401959 100644 --- a/projects/compass.db/modeling/compass.db.schema.org +++ b/projects/compass.db/modeling/compass.db.schema.org @@ -7,7 +7,7 @@ #+component: db #+filetags: :model:schema:database: #+created: 2026-11-23 -#+updated: 2026-11-23 +#+updated: 2026-12-02 The whole of compass's database at the current version, as =projects/compass.db/sql/schema.sql= states it. Each table is the @@ -35,6 +35,7 @@ tables, before it applies the first migration. | corpus | The documents of every environment and the paths that hold them. | | test | The test scenarios among those documents and their steps. | | activity | The test campaigns, runs, results, notes and screenshots. | +| agent | The conversations with the compass agent and their turns. | * Functions diff --git a/projects/compass.db/modeling/component_overview.org b/projects/compass.db/modeling/component_overview.org index e7b3a8a9..4f76a33f 100644 --- a/projects/compass.db/modeling/component_overview.org +++ b/projects/compass.db/modeling/component_overview.org @@ -322,6 +322,13 @@ of =share/masd=: - =include/compass.db/io/_copy.hpp= and =src/io/_copy.cpp=, the COPY writer of each table a sync stages in bulk. +The =agent= schema is the conversations with the agent, modelled by +[[id:BE684A24-5B70-4BF6-9779-415345C2C987][compass.db.agent_session]] and +[[id:4906B02A-7BDE-485D-9F1C-B2F8DA49DCF7][compass.db.agent_turn]]. Their +profile =conversation-record= marks them retained: the transcript exists +nowhere else, so a change to either needs a migration. The environment is +text, as in =activity.campaign=, so a session outlives its environment. + The migrations of =src/ops/migrations.cpp= stay hand-written and frozen once released. The aggregates =corpus_document= and =test_scenario=, and every query, stay hand-written. diff --git a/projects/compass.db/sql/schema.sql b/projects/compass.db/sql/schema.sql index 2be9388e..380e78d0 100644 --- a/projects/compass.db/sql/schema.sql +++ b/projects/compass.db/sql/schema.sql @@ -240,6 +240,43 @@ CREATE TABLE activity.step_result ( PRIMARY KEY (run, step_ord) ); +CREATE SCHEMA agent; + +-- agent.agent_session is retained: its rows exist nowhere else, so a change +-- to it needs a migration. +CREATE TABLE agent.agent_session ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + environment text NOT NULL, + subject text NOT NULL, + actor text, + view_name text NOT NULL, + title text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX agent_session_owner ON agent.agent_session (environment, subject, view_name, updated_at); + +-- agent.agent_turn is retained: its rows exist nowhere else, so a change +-- to it needs a migration. +CREATE TABLE agent.agent_turn ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + session_id bigint NOT NULL REFERENCES agent.agent_session ON DELETE CASCADE, + ord integer NOT NULL, + question text NOT NULL, + asked_at timestamptz NOT NULL, + retrieval jsonb NOT NULL, + answer text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'streaming' CHECK (status IN ('streaming', 'done', 'failed', 'stopped', 'cut')), + done jsonb, + failure jsonb, + model text NOT NULL, + actor text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (session_id, ord) +); +CREATE INDEX agent_turn_streaming ON agent.agent_turn (session_id) WHERE status = 'streaming'; + CREATE FUNCTION corpus.sprint_members(environment bigint, sprint text) RETURNS SETOF bytea LANGUAGE sql STABLE AS $$ WITH page AS ( diff --git a/projects/compass.db/src/CMakeLists.txt b/projects/compass.db/src/CMakeLists.txt index 325840db..e1a6d5ca 100644 --- a/projects/compass.db/src/CMakeLists.txt +++ b/projects/compass.db/src/CMakeLists.txt @@ -43,6 +43,8 @@ add_library(${lib_target_name} query/search.cpp query/testing.cpp types/action_row_codec.cpp + types/agent_session_row_codec.cpp + types/agent_turn_row_codec.cpp types/attached_row_codec.cpp types/attachment_row_codec.cpp types/campaign_row_codec.cpp diff --git a/projects/compass.db/src/ops/migrations.cpp b/projects/compass.db/src/ops/migrations.cpp index 81c14411..baf0f056 100644 --- a/projects/compass.db/src/ops/migrations.cpp +++ b/projects/compass.db/src/ops/migrations.cpp @@ -324,6 +324,44 @@ CREATE TABLE corpus.position ( ); )sql"; +// The conversations with the agent and their turns, in a schema apart from +// the test campaigns: a transcript is kept for its own sake, not as activity +// that tested the product, and a session outlives its environment. +constexpr std::string_view agent_sessions = R"sql( +CREATE SCHEMA agent; + +CREATE TABLE agent.agent_session ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + environment text NOT NULL, + subject text NOT NULL, + actor text, + view_name text NOT NULL, + title text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX agent_session_owner ON agent.agent_session (environment, subject, view_name, updated_at); + +CREATE TABLE agent.agent_turn ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + session_id bigint NOT NULL REFERENCES agent.agent_session ON DELETE CASCADE, + ord integer NOT NULL, + question text NOT NULL, + asked_at timestamptz NOT NULL, + retrieval jsonb NOT NULL, + answer text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'streaming' CHECK (status IN ('streaming', 'done', 'failed', 'stopped', 'cut')), + done jsonb, + failure jsonb, + model text NOT NULL, + actor text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (session_id, ord) +); +CREATE INDEX agent_turn_streaming ON agent.agent_turn (session_id) WHERE status = 'streaming'; +)sql"; + constexpr std::array all{ migration{1, "the corpus, test and activity schemas", create_schemas}, migration{2, "the document state and sprint for search", search_columns}, @@ -331,6 +369,7 @@ constexpr std::array all{ migration{4, "the word count of each section for search", section_words}, migration{5, "the clearing of a step's outcome", clear_step_result}, migration{6, "the layout of the link graph", link_graph_layout}, + migration{7, "the agent's conversations and their turns", agent_sessions}, }; } diff --git a/projects/compass.db/src/types/agent_session_row_codec.cpp b/projects/compass.db/src/types/agent_session_row_codec.cpp new file mode 100644 index 00000000..325561ba --- /dev/null +++ b/projects/compass.db/src/types/agent_session_row_codec.cpp @@ -0,0 +1,39 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.db/types/agent_session_row_codec.hpp" + +#include "compass.db/codec/struct_codec.hpp" + +namespace compass::db::codec { + +std::string wire_traits::write_json(const compass::db::types::agent_session_row& v) { + return object::write_json(v); +} + +compass::db::types::agent_session_row wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +} diff --git a/projects/compass.db/src/types/agent_turn_row_codec.cpp b/projects/compass.db/src/types/agent_turn_row_codec.cpp new file mode 100644 index 00000000..67582536 --- /dev/null +++ b/projects/compass.db/src/types/agent_turn_row_codec.cpp @@ -0,0 +1,39 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.db/types/agent_turn_row_codec.hpp" + +#include "compass.db/codec/struct_codec.hpp" + +namespace compass::db::codec { + +std::string wire_traits::write_json(const compass::db::types::agent_turn_row& v) { + return object::write_json(v); +} + +compass::db::types::agent_turn_row wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +} diff --git a/projects/compass.db/tests/CMakeLists.txt b/projects/compass.db/tests/CMakeLists.txt index a3fda891..e234a86e 100644 --- a/projects/compass.db/tests/CMakeLists.txt +++ b/projects/compass.db/tests/CMakeLists.txt @@ -34,6 +34,8 @@ add_executable(${tests_target_name} query_search_tests.cpp query_testing_tests.cpp types_action_row_codec_tests.cpp + types_agent_session_row_codec_tests.cpp + types_agent_turn_row_codec_tests.cpp types_attached_row_codec_tests.cpp types_attachment_row_codec_tests.cpp types_campaign_row_codec_tests.cpp diff --git a/projects/compass.db/tests/types_agent_session_row_codec_tests.cpp b/projects/compass.db/tests/types_agent_session_row_codec_tests.cpp new file mode 100644 index 00000000..b38e0be8 --- /dev/null +++ b/projects/compass.db/tests/types_agent_session_row_codec_tests.cpp @@ -0,0 +1,84 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json_tests.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.db/types/agent_session_row_codec.hpp" + +#include +#include +#include +#include "compass.db/codec/json_schema.hpp" +#include "compass.db/codec/member_count.hpp" +#include "compass.db/codec/sample.hpp" +#include "compass.db/codec/schema_check.hpp" + +namespace { + +using roundtrip_type = compass::db::types::agent_session_row; +using roundtrip_traits = compass::db::codec::wire_traits; + +} + +static_assert(compass::db::codec::names_every_member(), + "agent_session_row has a member its wire shape does not name"); +static_assert(roundtrip_traits::is_generated); + +TEST_CASE("agent_session_row reads back the JSON it writes", "[codec][roundtrip]") { + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + CHECK(roundtrip_traits::read_json(roundtrip_traits::write_json(v)) == v); + } + const roundtrip_type empty{}; + CHECK(roundtrip_traits::read_json(roundtrip_traits::write_json(empty)) == empty); +} + +TEST_CASE("agent_session_row's JSON Schema allows the JSON it writes", + "[codec][schema]") { + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto text = roundtrip_traits::write_json( + compass::db::codec::sample(which)); + const auto violation = compass::db::codec::schema_violation(schema, text); + INFO(text); + CHECK(violation.value_or("") == ""); + } + const auto text = roundtrip_traits::write_json(roundtrip_type{}); + INFO(text); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_session_row's reader and JSON Schema refuse the same members", + "[codec][schema]") { + const auto schema = compass::db::codec::json_schema(); + const auto text = roundtrip_traits::write_json( + compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(roundtrip_traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(roundtrip_traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } +} diff --git a/projects/compass.db/tests/types_agent_turn_row_codec_tests.cpp b/projects/compass.db/tests/types_agent_turn_row_codec_tests.cpp new file mode 100644 index 00000000..5c3c758f --- /dev/null +++ b/projects/compass.db/tests/types_agent_turn_row_codec_tests.cpp @@ -0,0 +1,84 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_json_tests.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.db/types/agent_turn_row_codec.hpp" + +#include +#include +#include +#include "compass.db/codec/json_schema.hpp" +#include "compass.db/codec/member_count.hpp" +#include "compass.db/codec/sample.hpp" +#include "compass.db/codec/schema_check.hpp" + +namespace { + +using roundtrip_type = compass::db::types::agent_turn_row; +using roundtrip_traits = compass::db::codec::wire_traits; + +} + +static_assert(compass::db::codec::names_every_member(), + "agent_turn_row has a member its wire shape does not name"); +static_assert(roundtrip_traits::is_generated); + +TEST_CASE("agent_turn_row reads back the JSON it writes", "[codec][roundtrip]") { + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + CHECK(roundtrip_traits::read_json(roundtrip_traits::write_json(v)) == v); + } + const roundtrip_type empty{}; + CHECK(roundtrip_traits::read_json(roundtrip_traits::write_json(empty)) == empty); +} + +TEST_CASE("agent_turn_row's JSON Schema allows the JSON it writes", + "[codec][schema]") { + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto text = roundtrip_traits::write_json( + compass::db::codec::sample(which)); + const auto violation = compass::db::codec::schema_violation(schema, text); + INFO(text); + CHECK(violation.value_or("") == ""); + } + const auto text = roundtrip_traits::write_json(roundtrip_type{}); + INFO(text); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_turn_row's reader and JSON Schema refuse the same members", + "[codec][schema]") { + const auto schema = compass::db::codec::json_schema(); + const auto text = roundtrip_traits::write_json( + compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(roundtrip_traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(roundtrip_traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } +} diff --git a/projects/modeling/variability_conversation_record.org b/projects/modeling/variability_conversation_record.org new file mode 100644 index 00000000..ade1cf87 --- /dev/null +++ b/projects/modeling/variability_conversation_record.org @@ -0,0 +1,35 @@ +:PROPERTIES: +:ID: 2D2C172F-DFCB-4D95-92E7-2A6CF0C51E5F +:END: +#+title: Profile: Conversation record +#+description: A conversation with the compass agent, which exists nowhere else, so its tables are retained: a change to them needs a migration that says what becomes of their rows. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-12-02 +#+updated: 2026-12-02 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: conversation-record= in its =* Flags= drawer. + +* Purpose + +A chat session and its turns: what a person asked the agent and what it +answered, which nothing else holds. The profile marks the table =retained=, +so =schema.sql= says so above the table. Once released, the migration tests +hold the table to its rows and columns: a later migration that loses a row, +or drops or retypes a column, fails them unless a recorded decision allows +the loss. + +The domain is conversation, not test activity: the tables live in the +=agent= schema, apart from the campaigns and runs of =activity=. + +* Reference entity + +=compass.db.agent_session=, one conversation of the agent. + +* Assignments + +| Feature | Value | +|----------+-------| +| retained | true | From 5e8e3545dceea4b05887e6283b1d63b505adf2d4 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:16:33 +0000 Subject: [PATCH 02/24] [codegen] Let a streamed POST write, and hold it in the catalogue A route that streams answers the response itself and is no MCP tool, but the session ask is a command: it writes the exchange it answers. The model now admits :stream: with :writes: on a POST and no response; the router records the stream in the catalogue, admits a streamed writing POST, and still refuses a stream that is a tool call or writes as another method. Co-Authored-By: Claude Code --- .../include/compass.http/domain/route.hpp | 10 +++++ .../include/compass.http/net/router.hpp | 6 +++ projects/compass.http/src/app/service.cpp | 1 + projects/compass.http/src/net/router.cpp | 13 +++++- .../compass.http/src/routes/agent_routes.cpp | 1 + .../tests/openapi_document_tests.cpp | 42 +++++++++++++++++++ .../compass.model/src/ops/masd_entity.cpp | 9 ++-- .../tests/ops_load_masd_operation_tests.cpp | 35 ++++++++++++---- .../templates/masd.cpp.http-routes.impl.org | 11 +++-- share/masd/templates/masd.cpp.http-routes.org | 4 +- .../templates/masd.cpp.http-service.route.org | 17 +++++++- .../masd.cpp.http-service.router.org | 8 +++- .../masd.cpp.http-service.router_impl.org | 15 ++++++- .../masd_cpp_http_routes.cpp.mustache | 1 + .../masd_cpp_http_service_route.hpp.mustache | 10 +++++ .../masd_cpp_http_service_router.hpp.mustache | 6 +++ ..._cpp_http_service_router_impl.cpp.mustache | 13 +++++- 17 files changed, 177 insertions(+), 25 deletions(-) diff --git a/projects/compass.http/include/compass.http/domain/route.hpp b/projects/compass.http/include/compass.http/domain/route.hpp index 13893c1c..781fa866 100644 --- a/projects/compass.http/include/compass.http/domain/route.hpp +++ b/projects/compass.http/include/compass.http/domain/route.hpp @@ -146,6 +146,16 @@ struct route_catalogue final { * the hold that MCP's tools are held in. */ bool answers_no_tool = false; + /** + * @brief True when the route streams its answer instead of answering a + * JSON document, such as the agent's question. + * + * Only a route that answers no tool may state it. A stream that writes is + * a command the catalogue records, and only a POST may do so: a GET that + * wrote would be invisible to the catalogue and to the hold that keeps an + * agent's writes for its person. + */ + bool stream = false; /** * @brief On a route that writes: the call may replace or remove what an * earlier call wrote. MCP's destructiveHint. diff --git a/projects/compass.http/include/compass.http/net/router.hpp b/projects/compass.http/include/compass.http/net/router.hpp index 627be8d5..19da4788 100644 --- a/projects/compass.http/include/compass.http/net/router.hpp +++ b/projects/compass.http/include/compass.http/net/router.hpp @@ -130,6 +130,12 @@ class route_builder final { */ route_builder& no_tool(); + /** + * @brief States that the route streams its answer, so it answers no tool + * and may write only as a POST. + */ + route_builder& stream(); + /** * @brief States that the route's write may replace or remove what an * earlier call wrote. diff --git a/projects/compass.http/src/app/service.cpp b/projects/compass.http/src/app/service.cpp index cf990904..7545330e 100644 --- a/projects/compass.http/src/app/service.cpp +++ b/projects/compass.http/src/app/service.cpp @@ -742,6 +742,7 @@ std::string catalogue_json(const net::router& r) { item.set("idempotent", c.idempotent); item.set("transport", c.transport); item.set("answers_no_tool", c.answers_no_tool); + item.set("stream", c.stream); item.set("takes_no_body", c.takes_no_body); item.set("summary", c.summary); item.set("description", c.description); diff --git a/projects/compass.http/src/net/router.cpp b/projects/compass.http/src/net/router.cpp index d6df6ab5..824601c3 100644 --- a/projects/compass.http/src/net/router.cpp +++ b/projects/compass.http/src/net/router.cpp @@ -152,6 +152,11 @@ route_builder& route_builder::no_tool() { return *this; } +route_builder& route_builder::stream() { + catalogue_.stream = true; + return *this; +} + route_builder& route_builder::destructive() { catalogue_.destructive = true; return *this; @@ -390,7 +395,13 @@ std::vector router::uncatalogued() const { route.catalogue.tool); if (route.catalogue.answers_no_tool && route.tool_call) out.push_back(name + " states that it answers no tool, and also a tool call"); - if (route.catalogue.answers_no_tool && (changes || route.catalogue.writes)) + if (route.catalogue.stream && !route.catalogue.answers_no_tool) + out.push_back(name + " states that it streams, and answers a tool call"); + if (route.catalogue.stream && route.catalogue.answers_no_tool && + (changes || route.catalogue.writes) && route.method != domain::http_method::post) + out.push_back(name + " streams and writes, and only a POST stream may write"); + if (route.catalogue.answers_no_tool && !route.catalogue.stream && + (changes || route.catalogue.writes)) out.push_back(name + " states that it answers no tool, and it writes or its " "method changes something"); // A tool names one operation, so two routes may not share one. diff --git a/projects/compass.http/src/routes/agent_routes.cpp b/projects/compass.http/src/routes/agent_routes.cpp index 58065067..272d3c8e 100644 --- a/projects/compass.http/src/routes/agent_routes.cpp +++ b/projects/compass.http/src/routes/agent_routes.cpp @@ -52,6 +52,7 @@ void add_get_agent_answer(net::router& r, get_agent_answer_handler h) { .query_param("q", "string", "", true, "The question, at most 500 characters, counted as code points; an empty or longer one is refused as invalid.") .input() .no_tool() + .stream() .handler([h](const domain::http_request& req) { return net::ready(net::answer(req, domain::caller_need::view, [&](const domain::caller& c) { return h(c, bind_get_agent_answer(req)); })); diff --git a/projects/compass.http/tests/openapi_document_tests.cpp b/projects/compass.http/tests/openapi_document_tests.cpp index aef3c01e..39f9ea58 100644 --- a/projects/compass.http/tests/openapi_document_tests.cpp +++ b/projects/compass.http/tests/openapi_document_tests.cpp @@ -518,6 +518,48 @@ TEST_CASE("the gates refuse a route that answers no tool and writes or answers a "writes or its method changes something")); } +TEST_CASE("the gates admit a streamed POST that writes, and refuse a stream that is " + "a tool or writes otherwise", + "[serve][openapi]") { + const auto handler = [](const domain::http_request&) { + return net::ready(domain::http_response::json("{}")); + }; + net::router ok; + ok.add_route(ok.post("/ask") + .catalogue("ask_agent", "documents", "agent", true) + .json_body() + .no_tool() + .stream() + .caller(domain::caller_need::subject) + .handler(handler) + .build()); + CHECK(ok.uncatalogued().empty()); + const domain::http_request req; + CHECK(mcp::route_tools(ok).list(req).empty()); + + net::router tool_stream; + tool_stream.add_route(tool_stream.get("/stream") + .catalogue("get_stream", "documents", "agent", false) + .stream() + .tool_call([](const domain::caller&, std::string_view) { return "{}"; }) + .caller(domain::caller_need::view) + .handler(handler) + .build()); + net::router wrong_method; + wrong_method.add_route(wrong_method.put("/ask") + .catalogue("replace_agent", "documents", "agent", true) + .json_body() + .no_tool() + .stream() + .caller(domain::caller_need::subject) + .handler(handler) + .build()); + CHECK_THAT(joined(tool_stream.uncatalogued()), + ContainsSubstring("states that it streams, and answers a tool call")); + CHECK_THAT(joined(wrong_method.uncatalogued()), + ContainsSubstring("streams and writes, and only a POST stream may write")); +} + TEST_CASE("compass serves its OpenAPI document and Swagger UI with no network", "[serve][openapi]") { served s; diff --git a/projects/compass.model/src/ops/masd_entity.cpp b/projects/compass.model/src/ops/masd_entity.cpp index 92898fe3..9c95bbc7 100644 --- a/projects/compass.model/src/ops/masd_entity.cpp +++ b/projects/compass.model/src/ops/masd_entity.cpp @@ -460,9 +460,12 @@ void check_route(const types::masd_message& m) { ":area:, :entity: and :summary:"); if (m.http_method == "get" && r.writes) throw model_error(m.name + " is a GET that writes"); - if (r.stream && (r.writes || !m.response.empty())) - throw model_error(m.name + " streams, so it writes nothing and names " - "no :response:; its handler answers the stream itself"); + if (r.stream && !m.response.empty()) + throw model_error(m.name + " streams, so it names no :response:; " + "its handler answers the stream itself"); + if (r.stream && r.writes && m.http_method != "post") + throw model_error(m.name + " streams and writes, which only a POST " + "may do"); } } diff --git a/projects/compass.model/tests/ops_load_masd_operation_tests.cpp b/projects/compass.model/tests/ops_load_masd_operation_tests.cpp index af08ea2a..1dbc2f97 100644 --- a/projects/compass.model/tests/ops_load_masd_operation_tests.cpp +++ b/projects/compass.model/tests/ops_load_masd_operation_tests.cpp @@ -39,7 +39,8 @@ constexpr std::string_view component_path = */ std::string operation(std::string_view header, std::string_view request, std::string_view environment, std::string_view reply, - std::string_view plain = ":cpp_type: std::string\n") { + std::string_view plain = ":cpp_type: std::string\n", + bool names_response = true) { return std::string(R"org(#+title: compass.http.notes #+type: masd.codegen.operation #+component: http @@ -55,8 +56,8 @@ std::string operation(std::string_view header, std::string_view request, ** reply_request :PROPERTIES: -:response: reply_response -)org" + std::string(request) + R"org(:END: +)org" + (names_response ? ":response: reply_response\n" : "") + + std::string(request) + R"org(:END: *** environment :PROPERTIES: @@ -91,6 +92,10 @@ constexpr std::string_view routed_get = ":http_method: get\n:http_path: /v1/{environment}/reply\n" ":tool: read_reply\n:area: qa\n:entity: note\n" ":summary: Read a reply\n:caller: view\n"; +constexpr std::string_view routed_put = + ":http_method: put\n:http_path: /v1/{environment}/reply\n" + ":tool: replace_reply\n:area: qa\n:entity: note\n" + ":writes: true\n:summary: Replace a reply\n:caller: subject\n"; constexpr std::string_view path_field = ":cpp_type: std::string\n:http_in: path\n"; constexpr std::string_view body_field = @@ -154,6 +159,18 @@ TEST_CASE("a masd.codegen.operation model reads its messages and where a " CHECK(response.fields[0].http_in == types::http_in::none); } +TEST_CASE("a streamed POST that writes is a route the model allows", + "[ops][load][masd]") { + const auto c = with(operation(namespace_line, std::string(routed) + + ":stream: true\n", path_field, body_field, ":cpp_type: std::string\n", false)); + REQUIRE(c.load_error(operation_path).empty()); + const auto m = c.masd_operation(operation_path); + REQUIRE(m.messages.size() == 2); + CHECK(m.messages[0].route.stream); + CHECK(m.messages[0].route.writes); + CHECK(m.messages[0].response.empty()); +} + TEST_CASE("an operation model that says what the format does not have is " "refused, naming where", "[ops][load][masd]") { SECTION("a misspelt field property") { @@ -223,13 +240,13 @@ TEST_CASE("an operation model that says what the format does not have is " SECTION("a stream that names a response") { refused(operation(namespace_line, std::string(routed_get) + ":stream: true\n", path_field, path_field), - "reply_request streams, so it writes nothing and names no " - ":response:"); + "reply_request streams, so it names no :response:"); } - SECTION("a stream that writes") { - refused(operation(namespace_line, std::string(routed) + - ":stream: true\n", path_field, body_field), - "reply_request streams, so it writes nothing"); + SECTION("a stream that writes, and is not a POST") { + refused(operation(namespace_line, std::string(routed_put) + + ":stream: true\n", path_field, body_field, + ":cpp_type: std::string\n", false), + "reply_request streams and writes, which only a POST may do"); } SECTION("a flag that is not true or false") { refused(operation(namespace_line, std::string(routed) + diff --git a/share/masd/templates/masd.cpp.http-routes.impl.org b/share/masd/templates/masd.cpp.http-routes.impl.org index 07c36d05..d5b85485 100644 --- a/share/masd/templates/masd.cpp.http-routes.impl.org +++ b/share/masd/templates/masd.cpp.http-routes.impl.org @@ -9,7 +9,7 @@ #+level: cross #+filetags: :codegen:templates:literate:archetype:masd: #+created: 2026-11-23 -#+updated: 2026-11-30 +#+updated: 2026-12-02 This page is the archetype that writes the translation unit of an operation model's routes for the @@ -43,9 +43,11 @@ which =.body()= states. A query value of an enumeration is read by the enumeration's text form, so it is one of its values. A list-valued parameter is an OpenAPI array, given once per value. -A streamed route states =no_tool()= in place of a tool call: its answer is -not one JSON value a tool could return. Its handler's result still passes -through =net::answer=, which answers it as it is. +A streamed route states =no_tool()= and =stream()= in place of a tool call: +its answer is not one JSON value a tool could return, and the catalogue +knows the route streams. A streamed POST may write; the session ask does. +Its handler's result still passes through =net::answer=, which answers it as +it is. The route's tool call reads the MCP arguments as the whole request, every field, with the request's own reader, and calls the same handler as the @@ -130,6 +132,7 @@ void add_{{tool}}(net::router& r, {{tool}}_handler h) { {{/has_response}} {{#stream}} .no_tool() + .stream() {{/stream}} {{^stream}} .tool_call([h](const domain::caller& c, std::string_view arguments) { diff --git a/share/masd/templates/masd.cpp.http-routes.org b/share/masd/templates/masd.cpp.http-routes.org index b1bf79c7..3cc1bcec 100644 --- a/share/masd/templates/masd.cpp.http-routes.org +++ b/share/masd/templates/masd.cpp.http-routes.org @@ -10,7 +10,7 @@ #+facet_group: masd.cpp #+filetags: :codegen:physical-space:cpp:http:masd: #+created: 2026-11-23 -#+updated: 2026-11-30 +#+updated: 2026-12-02 This page is the node for the =masd.cpp.http-routes= facet of the MASD library. Its archetypes are @@ -40,7 +40,7 @@ gates check it as ORE Studio's check its own routes: | the request | =input()=, the tool's input schema | | =:response:= | =response()= | | the handler, as MCP reaches it | =tool_call=, which reads the request from the MCP arguments by the request's reader | -| =:stream: true= | =no_tool=, in place of =tool_call=; the handler answers the =domain::http_response= itself, whose body the server writes as it is produced | +| =:stream: true= | =no_tool= and =stream=, in place of =tool_call=; the handler answers the =domain::http_response= itself, whose body the server writes as it is produced | The binding follows the service's rules, stated once in the component's runtime (=net/binding.hpp=): a path field from its placeholder, a query diff --git a/share/masd/templates/masd.cpp.http-service.route.org b/share/masd/templates/masd.cpp.http-service.route.org index d14cdb90..60245b24 100644 --- a/share/masd/templates/masd.cpp.http-service.route.org +++ b/share/masd/templates/masd.cpp.http-service.route.org @@ -9,7 +9,7 @@ #+level: cross #+filetags: :codegen:templates:literate:archetype:masd: #+created: 2026-11-23 -#+updated: 2026-11-29 +#+updated: 2026-12-02 This page is an archetype of the [[id:58BCC011-F984-4DAA-B054-F3692C529F38][masd.cpp.http-service]] facet: one file of the HTTP route runtime, rendered into the component that switches @@ -36,7 +36,10 @@ destructive and idempotent are compass's own, MCP's =destructiveHint= and own: the route's tool as MCP's =tools/call= reaches it, which calls the same handler as the route. route_catalogue::answers_no_tool is compass's own: a read such as =GET /openapi.json= that serves the API's description and is no -MCP tool. +MCP tool. route_catalogue::stream is compass's own: a route whose handler +answers the response itself, streamed as it is produced. A stream answers no +tool; one that writes, as the agent's session ask does, is a POST the +catalogue records. * Context @@ -181,6 +184,16 @@ struct route_catalogue final { * the hold that MCP's tools are held in. */ bool answers_no_tool = false; + /** + * @brief True when the route streams its answer instead of answering a + * JSON document, such as the agent's question. + * + * Only a route that answers no tool may state it. A stream that writes is + * a command the catalogue records, and only a POST may do so: a GET that + * wrote would be invisible to the catalogue and to the hold that keeps an + * agent's writes for its person. + */ + bool stream = false; /** * @brief On a route that writes: the call may replace or remove what an * earlier call wrote. MCP's destructiveHint. diff --git a/share/masd/templates/masd.cpp.http-service.router.org b/share/masd/templates/masd.cpp.http-service.router.org index dc3e70fe..d08153c7 100644 --- a/share/masd/templates/masd.cpp.http-service.router.org +++ b/share/masd/templates/masd.cpp.http-service.router.org @@ -9,7 +9,7 @@ #+level: cross #+filetags: :codegen:templates:literate:archetype:masd: #+created: 2026-11-23 -#+updated: 2026-11-29 +#+updated: 2026-12-02 This page is an archetype of the [[id:58BCC011-F984-4DAA-B054-F3692C529F38][masd.cpp.http-service]] facet: one file of the HTTP route runtime, rendered into the component that switches @@ -166,6 +166,12 @@ public: */ route_builder& no_tool(); + /** + * @brief States that the route streams its answer, so it answers no tool + * and may write only as a POST. + */ + route_builder& stream(); + /** * @brief States that the route's write may replace or remove what an * earlier call wrote. diff --git a/share/masd/templates/masd.cpp.http-service.router_impl.org b/share/masd/templates/masd.cpp.http-service.router_impl.org index 953d0833..444166db 100644 --- a/share/masd/templates/masd.cpp.http-service.router_impl.org +++ b/share/masd/templates/masd.cpp.http-service.router_impl.org @@ -9,7 +9,7 @@ #+level: cross #+filetags: :codegen:templates:literate:archetype:masd: #+created: 2026-11-23 -#+updated: 2026-11-29 +#+updated: 2026-12-02 This page is an archetype of the [[id:58BCC011-F984-4DAA-B054-F3692C529F38][masd.cpp.http-service]] facet: one file of the HTTP route runtime, rendered into the component that switches @@ -179,6 +179,11 @@ route_builder& route_builder::no_tool() { return *this; } +route_builder& route_builder::stream() { + catalogue_.stream = true; + return *this; +} + route_builder& route_builder::destructive() { catalogue_.destructive = true; return *this; @@ -417,7 +422,13 @@ std::vector router::uncatalogued() const { route.catalogue.tool); if (route.catalogue.answers_no_tool && route.tool_call) out.push_back(name + " states that it answers no tool, and also a tool call"); - if (route.catalogue.answers_no_tool && (changes || route.catalogue.writes)) + if (route.catalogue.stream && !route.catalogue.answers_no_tool) + out.push_back(name + " states that it streams, and answers a tool call"); + if (route.catalogue.stream && route.catalogue.answers_no_tool && + (changes || route.catalogue.writes) && route.method != domain::http_method::post) + out.push_back(name + " streams and writes, and only a POST stream may write"); + if (route.catalogue.answers_no_tool && !route.catalogue.stream && + (changes || route.catalogue.writes)) out.push_back(name + " states that it answers no tool, and it writes or its " "method changes something"); // A tool names one operation, so two routes may not share one. diff --git a/share/masd/templates/masd_cpp_http_routes.cpp.mustache b/share/masd/templates/masd_cpp_http_routes.cpp.mustache index 2b74b89e..f2d14df7 100644 --- a/share/masd/templates/masd_cpp_http_routes.cpp.mustache +++ b/share/masd/templates/masd_cpp_http_routes.cpp.mustache @@ -66,6 +66,7 @@ void add_{{tool}}(net::router& r, {{tool}}_handler h) { {{/has_response}} {{#stream}} .no_tool() + .stream() {{/stream}} {{^stream}} .tool_call([h](const domain::caller& c, std::string_view arguments) { diff --git a/share/masd/templates/masd_cpp_http_service_route.hpp.mustache b/share/masd/templates/masd_cpp_http_service_route.hpp.mustache index d992f064..fbed761e 100644 --- a/share/masd/templates/masd_cpp_http_service_route.hpp.mustache +++ b/share/masd/templates/masd_cpp_http_service_route.hpp.mustache @@ -126,6 +126,16 @@ struct route_catalogue final { * the hold that MCP's tools are held in. */ bool answers_no_tool = false; + /** + * @brief True when the route streams its answer instead of answering a + * JSON document, such as the agent's question. + * + * Only a route that answers no tool may state it. A stream that writes is + * a command the catalogue records, and only a POST may do so: a GET that + * wrote would be invisible to the catalogue and to the hold that keeps an + * agent's writes for its person. + */ + bool stream = false; /** * @brief On a route that writes: the call may replace or remove what an * earlier call wrote. MCP's destructiveHint. diff --git a/share/masd/templates/masd_cpp_http_service_router.hpp.mustache b/share/masd/templates/masd_cpp_http_service_router.hpp.mustache index 8338c782..d723ce8b 100644 --- a/share/masd/templates/masd_cpp_http_service_router.hpp.mustache +++ b/share/masd/templates/masd_cpp_http_service_router.hpp.mustache @@ -110,6 +110,12 @@ public: */ route_builder& no_tool(); + /** + * @brief States that the route streams its answer, so it answers no tool + * and may write only as a POST. + */ + route_builder& stream(); + /** * @brief States that the route's write may replace or remove what an * earlier call wrote. diff --git a/share/masd/templates/masd_cpp_http_service_router_impl.cpp.mustache b/share/masd/templates/masd_cpp_http_service_router_impl.cpp.mustache index 56d37cd6..41edbfe2 100644 --- a/share/masd/templates/masd_cpp_http_service_router_impl.cpp.mustache +++ b/share/masd/templates/masd_cpp_http_service_router_impl.cpp.mustache @@ -132,6 +132,11 @@ route_builder& route_builder::no_tool() { return *this; } +route_builder& route_builder::stream() { + catalogue_.stream = true; + return *this; +} + route_builder& route_builder::destructive() { catalogue_.destructive = true; return *this; @@ -370,7 +375,13 @@ std::vector router::uncatalogued() const { route.catalogue.tool); if (route.catalogue.answers_no_tool && route.tool_call) out.push_back(name + " states that it answers no tool, and also a tool call"); - if (route.catalogue.answers_no_tool && (changes || route.catalogue.writes)) + if (route.catalogue.stream && !route.catalogue.answers_no_tool) + out.push_back(name + " states that it streams, and answers a tool call"); + if (route.catalogue.stream && route.catalogue.answers_no_tool && + (changes || route.catalogue.writes) && route.method != domain::http_method::post) + out.push_back(name + " streams and writes, and only a POST stream may write"); + if (route.catalogue.answers_no_tool && !route.catalogue.stream && + (changes || route.catalogue.writes)) out.push_back(name + " states that it answers no tool, and it writes or its " "method changes something"); // A tool names one operation, so two routes may not share one. From 89234a7473288f7a7ee8816cf21d69677e46db6c Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:26:35 +0000 Subject: [PATCH 03/24] [http] Serve the agent's sessions, and settle their answers off the io thread The session routes create, list, read and delete a conversation, every statement filtered by the caller's environment, subject and view. The ask is a streamed POST that writes: the question and the exact passages event are inserted on the handler's worker thread before the stream opens, and a terminal sink enqueues the answer to one writer thread, which settles it in short transactions. A killed stream records stopped with its partial text, a restart turns every leftover streaming row into cut, and a partial snapshot is taken every two seconds. The stream's passages frame and the stored event are one object. Co-Authored-By: Claude Code --- projects/compass.cli/src/app/serve.cpp | 7 + .../include/compass.http/agent/llama.hpp | 17 +- .../include/compass.http/agent/turn.hpp | 61 +++ .../compass.http/agent/turn_writer.hpp | 97 ++++ .../include/compass.http/app/service.hpp | 31 +- .../messages/agent_sessions_protocol.hpp | 441 +++++++++++++++ .../include/compass.http/ops/agent.hpp | 18 + .../include/compass.http/query/sessions.hpp | 121 +++++ .../routes/agent_sessions_routes.hpp | 97 ++++ .../modeling/compass.http.agent_sessions.org | 391 ++++++++++++++ projects/compass.http/src/CMakeLists.txt | 4 + projects/compass.http/src/agent/llama.cpp | 68 ++- .../compass.http/src/agent/turn_writer.cpp | 117 ++++ projects/compass.http/src/app/service.cpp | 130 ++++- .../src/messages/agent_sessions_protocol.cpp | 128 +++++ projects/compass.http/src/ops/agent.cpp | 10 + projects/compass.http/src/query/sessions.cpp | 346 ++++++++++++ .../src/routes/agent_sessions_routes.cpp | 194 +++++++ projects/compass.http/tests/CMakeLists.txt | 3 + .../compass.http/tests/agent_llama_tests.cpp | 150 +++++- .../compass.http/tests/app_service_tests.cpp | 19 +- ...messages_agent_sessions_protocol_tests.cpp | 506 ++++++++++++++++++ .../tests/query_sessions_tests.cpp | 348 ++++++++++++ .../compass.http/tests/query_writes_tests.cpp | 7 +- .../compass.http/tests/turn_writer_tests.cpp | 169 ++++++ 25 files changed, 3418 insertions(+), 62 deletions(-) create mode 100644 projects/compass.http/include/compass.http/agent/turn.hpp create mode 100644 projects/compass.http/include/compass.http/agent/turn_writer.hpp create mode 100644 projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp create mode 100644 projects/compass.http/include/compass.http/query/sessions.hpp create mode 100644 projects/compass.http/include/compass.http/routes/agent_sessions_routes.hpp create mode 100644 projects/compass.http/modeling/compass.http.agent_sessions.org create mode 100644 projects/compass.http/src/agent/turn_writer.cpp create mode 100644 projects/compass.http/src/messages/agent_sessions_protocol.cpp create mode 100644 projects/compass.http/src/query/sessions.cpp create mode 100644 projects/compass.http/src/routes/agent_sessions_routes.cpp create mode 100644 projects/compass.http/tests/messages_agent_sessions_protocol_tests.cpp create mode 100644 projects/compass.http/tests/query_sessions_tests.cpp create mode 100644 projects/compass.http/tests/turn_writer_tests.cpp diff --git a/projects/compass.cli/src/app/serve.cpp b/projects/compass.cli/src/app/serve.cpp index 247b574a..549fb682 100644 --- a/projects/compass.cli/src/app/serve.cpp +++ b/projects/compass.cli/src/app/serve.cpp @@ -41,6 +41,7 @@ #include "compass.platform/process/executable.hpp" #include "compass.platform/process/run_program.hpp" #include "compass.http/app/service.hpp" +#include "compass.http/query/sessions.hpp" #include "compass.http/web/bundle.hpp" namespace compass::cli::app { @@ -119,6 +120,12 @@ int run_serve(const types::invocation& i, std::ostream& out, s->service.version = COMPASS_VERSION; http::app::connection_pool pool(s->database); + const auto recovered = pool.write([](db::io::connection& c) { + return http::query::recover_agent_turns(c); + }); + if (recovered > 0) + err << "compass: serve: settled " << recovered + << " agent turn(s) left streaming\n"; http::app::service service(s->service, pool, environment_sync_of(i.checkout, *local, i.threads)); http::net::router router; diff --git a/projects/compass.http/include/compass.http/agent/llama.hpp b/projects/compass.http/include/compass.http/agent/llama.hpp index 3f01641f..e0079fe7 100644 --- a/projects/compass.http/include/compass.http/agent/llama.hpp +++ b/projects/compass.http/include/compass.http/agent/llama.hpp @@ -30,6 +30,7 @@ #include #include #include +#include "compass.http/agent/turn.hpp" #include "compass.http/domain/awaitable_body_source.hpp" #include "compass.http/messages/agent_protocol.hpp" #include "compass.http/ops/agent.hpp" @@ -78,8 +79,14 @@ struct answer_options { bool names_server = true; /// How long the stream stays silent before a comment keeps it open. std::chrono::milliseconds heartbeat = std::chrono::seconds(15); + /// How often a growing answer is snapshotted while it streams. + std::chrono::milliseconds partial_every = std::chrono::seconds(2); /// Held for as long as the stream lives. stream_slot slot; + /// The turn this stream settles; 0 on the stateless ask. + std::int64_t turn = 0; + /// Where the stream records the turn; null on the stateless ask. + std::shared_ptr sink; }; /** @@ -93,11 +100,15 @@ struct answer_options { class answer_stream final : public domain::awaitable_body_source { public: /** + * @param passages the metadata event sent as the stream's first frame + * and, on a session ask, stored with the turn: one object, so a restore + * cannot drift from the stream. * @param asked when the question arrived, which the times count from. */ answer_stream(types::agent_settings server, ops::agent_retrieval found, - std::string question, std::uint32_t retrieval_ms, - std::chrono::steady_clock::time_point asked, answer_options options = {}); + messages::agent_passages_event passages, std::string question, + std::chrono::steady_clock::time_point asked, + answer_options options = {}); ~answer_stream() override; boost::asio::awaitable read(std::span into) override; @@ -114,8 +125,8 @@ class answer_stream final : public domain::awaitable_body_source { types::agent_settings server_; ops::agent_retrieval found_; + messages::agent_passages_event passages_; std::string question_; - std::uint32_t retrieval_ms_; std::chrono::steady_clock::time_point asked_; answer_options options_; bool started_ = false; diff --git a/projects/compass.http/include/compass.http/agent/turn.hpp b/projects/compass.http/include/compass.http/agent/turn.hpp new file mode 100644 index 00000000..abc8a431 --- /dev/null +++ b/projects/compass.http/include/compass.http/agent/turn.hpp @@ -0,0 +1,61 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_HTTP_AGENT_TURN_HPP +#define COMPASS_HTTP_AGENT_TURN_HPP + +#include +#include +#include +#include "compass.http/messages/agent_protocol.hpp" + +namespace compass::http::agent { + +/** + * @brief How a streamed answer ended: the model finished it, the model's + * server failed, or the client left before either. + */ +enum class turn_end { done, failed, stopped }; + +/** + * @brief The terminal record of one exchange: its turn, the answer as it + * ended, how it ended, and the event the stream sent with it. + */ +struct turn_record { + std::int64_t turn = 0; + std::string answer; + turn_end end = turn_end::stopped; + std::optional done; + std::optional failure; +}; + +/** + * @brief The stream's persistence seam. Neither call may block the io + * thread: an implementation enqueues, and another thread writes. + */ +class turn_sink { +public: + virtual ~turn_sink() = default; + virtual void record(turn_record r) noexcept = 0; + virtual void record_partial(std::int64_t turn, std::string answer) noexcept = 0; +}; + +} + +#endif diff --git a/projects/compass.http/include/compass.http/agent/turn_writer.hpp b/projects/compass.http/include/compass.http/agent/turn_writer.hpp new file mode 100644 index 00000000..1a567931 --- /dev/null +++ b/projects/compass.http/include/compass.http/agent/turn_writer.hpp @@ -0,0 +1,97 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_HTTP_AGENT_TURN_WRITER_HPP +#define COMPASS_HTTP_AGENT_TURN_WRITER_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "compass.http/agent/turn.hpp" + +namespace compass::http::app { +class connection_pool; +} + +namespace compass::http::agent { + +/** + * @brief One write waiting for the writer: a partial snapshot, or the + * terminal record of a turn. + */ +struct queued_turn { + enum class kind { partial, terminal } what = kind::terminal; + turn_record record; + std::int64_t turn = 0; + std::string answer; +}; + +/** + * @brief The one thread that settles turns in the database. + * + * The stream hands it records from the connection's io thread, where a + * database write would stall every connection the service holds; the writer + * drains them through the pool in short transactions of its own. Its queue + * is bounded: a burst beyond it drops records, counted and logged, rather + * than grow without bound. On destruction it drains what it holds and joins, + * so a clean shutdown settles every answer the server closed. Logs name + * turns, never question or answer text. + */ +class turn_writer final : public turn_sink { +public: + explicit turn_writer(app::connection_pool& pool, + std::function log = {}); + ~turn_writer() override; + turn_writer(const turn_writer&) = delete; + turn_writer& operator=(const turn_writer&) = delete; + + void record(turn_record r) noexcept override; + void record_partial(std::int64_t turn, std::string answer) noexcept override; + + /// Waits until nothing is queued or being written; a test seam. + void flush(); + + /// How many records the bounded queue refused. + [[nodiscard]] std::uint64_t dropped() const noexcept; + +private: + static constexpr std::size_t max_queued = 64; + + void run(std::stop_token stop); + void push(queued_turn q) noexcept; + + app::connection_pool& pool_; + std::function log_; + std::mutex mutex_; + std::condition_variable_any ready_; + std::deque queue_; + bool writing_ = false; + std::jthread worker_; + std::atomic dropped_{0}; +}; + +} + +#endif diff --git a/projects/compass.http/include/compass.http/app/service.hpp b/projects/compass.http/include/compass.http/app/service.hpp index b5bd104b..5567838e 100644 --- a/projects/compass.http/include/compass.http/app/service.hpp +++ b/projects/compass.http/include/compass.http/app/service.hpp @@ -29,6 +29,7 @@ #include #include "compass.db/io/connection.hpp" #include "compass.db/types/search.hpp" +#include "compass.http/agent/turn_writer.hpp" #include "compass.http/domain/caller.hpp" #include "compass.http/domain/http_request.hpp" #include "compass.http/domain/http_response.hpp" @@ -160,14 +161,18 @@ class service final { void add_read_routes(net::router& r); /** - * @brief Adds the compass agent's two routes to @p r: GET + * @brief Adds the compass agent's three routes to @p r: GET * /v1/{environment}/agent, which searches inside the caller's view, * hands the passages to llama-server and streams its answer as - * server-sent events, and GET /v1/agent, the model and whether its server - * answers. Neither changes anything, and the stream is no MCP tool. Only - * a caller who runs the service is told llama-server's address, what it - * said and the command that starts it; four streams are open at most, - * and one more is refused as busy. + * server-sent events; POST + * /v1/{environment}/agent/sessions/{session}/ask, the same answer in a + * session, whose question is written before the stream opens and whose + * answer the stream settles through the writer; and GET /v1/agent, the + * model and whether its server answers. Only a caller who runs the + * service is told llama-server's address, what it said and the command + * that starts it; four streams are open at most, and one more is refused + * as busy. The session ask writes, so the gateway's rule for a write + * covers it; neither stream is an MCP tool. */ void add_agent_routes(net::router& r); @@ -188,10 +193,10 @@ class service final { void add_openapi_routes(net::router& r) const; /** - * @brief Adds the six campaign write routes and - * POST /v1/{environment}/sync to @p r. A refused write answers - * invalid, not_found or conflict and writes nothing. The sync syncs - * only the environment of the service's checkout, and answers any + * @brief Adds the six campaign write routes, POST /v1/{environment}/sync + * and the session create and delete routes to @p r. A refused write + * answers invalid, not_found or conflict and writes nothing. The sync + * syncs only the environment of the service's checkout, and answers any * other, or every one when the service has no checkout, conflict: * another environment's files are in its own worktree, where * compass sync syncs it. The files the sync could not read are named @@ -233,6 +238,12 @@ class service final { std::map> views_; connection_pool& pool_; std::optional sync_; + /** + * The one thread that settles the turns of the sessions. Declared last so + * it is destroyed first: it drains its queue and joins before the pool + * and the service's other state go, and it outlives every stream. + */ + std::shared_ptr writer_; }; /** diff --git a/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp b/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp new file mode 100644 index 00000000..58828eb7 --- /dev/null +++ b/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp @@ -0,0 +1,441 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_protocol.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_HTTP_MESSAGES_AGENT_SESSIONS_PROTOCOL_HPP +#define COMPASS_HTTP_MESSAGES_AGENT_SESSIONS_PROTOCOL_HPP + +#include +#include +#include +#include +#include +#include +#include +#include "compass.http/messages/agent_protocol.hpp" +#include "compass.db/codec/text_form.hpp" +#include "compass.db/codec/wire_fields.hpp" +#include "compass.db/codec/wire_traits_fwd.hpp" + +namespace compass::http::messages { + +#ifndef COMPASS_HTTP_MESSAGES_AGENT_TURN_STATUS_ENUM +/** + * @brief The values :values: lists for agent_turn_status. + */ +enum class agent_turn_status { streaming, done, failed, stopped, cut }; + +/** + * @brief Each value of agent_turn_status as the wire names it. + */ +[[nodiscard]] constexpr std::string_view to_string(agent_turn_status v) { + switch (v) { + case agent_turn_status::streaming: return "streaming"; + case agent_turn_status::done: return "done"; + case agent_turn_status::failed: return "failed"; + case agent_turn_status::stopped: return "stopped"; + case agent_turn_status::cut: return "cut"; + } + throw std::invalid_argument("Not a agent_turn_status: the value is not one of streaming, done, failed, stopped, cut"); +} + +/** + * @brief The agent_turn_status @p text names, or none for any other text. + */ +[[nodiscard]] constexpr std::optional agent_turn_status_of( + std::string_view text) noexcept { + if (text == "streaming") + return agent_turn_status::streaming; + if (text == "done") + return agent_turn_status::done; + if (text == "failed") + return agent_turn_status::failed; + if (text == "stopped") + return agent_turn_status::stopped; + if (text == "cut") + return agent_turn_status::cut; + return std::nullopt; +} +#endif + +struct create_agent_session_request { + std::string environment; + std::optional title; + + friend bool operator==(const create_agent_session_request&, const create_agent_session_request&) = default; +}; + +/** + * @brief The members of create_agent_session_request, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &create_agent_session_request::environment}, + ::compass::db::codec::field{"title", &create_agent_session_request::title}, + }; +} + +/** + * @brief The members of create_agent_session_request its route reads from the JSON body. The + * route sets the others from the request line. + */ +[[nodiscard]] constexpr auto body_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"title", &create_agent_session_request::title}, + }; +} + +struct create_agent_session_response { + std::int64_t session = 0; + std::string created_at; + + friend bool operator==(const create_agent_session_response&, const create_agent_session_response&) = default; +}; + +/** + * @brief The members of create_agent_session_response, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"session", &create_agent_session_response::session, true}, + ::compass::db::codec::field{"created_at", &create_agent_session_response::created_at}, + }; +} + +struct list_agent_sessions_request { + std::string environment; + std::uint32_t limit = 50; + std::uint32_t offset = 0; + + friend bool operator==(const list_agent_sessions_request&, const list_agent_sessions_request&) = default; +}; + +/** + * @brief The members of list_agent_sessions_request, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &list_agent_sessions_request::environment}, + ::compass::db::codec::field{"limit", &list_agent_sessions_request::limit, true}, + ::compass::db::codec::field{"offset", &list_agent_sessions_request::offset, true}, + }; +} + +struct agent_session_summary { + std::int64_t session = 0; + std::string title; + std::string created_at; + std::string updated_at; + std::uint32_t turns = 0; + + friend bool operator==(const agent_session_summary&, const agent_session_summary&) = default; +}; + +/** + * @brief The members of agent_session_summary, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"session", &agent_session_summary::session, true}, + ::compass::db::codec::field{"title", &agent_session_summary::title}, + ::compass::db::codec::field{"created_at", &agent_session_summary::created_at}, + ::compass::db::codec::field{"updated_at", &agent_session_summary::updated_at}, + ::compass::db::codec::field{"turns", &agent_session_summary::turns, true}, + }; +} + +struct list_agent_sessions_response { + std::vector sessions; + + friend bool operator==(const list_agent_sessions_response&, const list_agent_sessions_response&) = default; +}; + +/** + * @brief The members of list_agent_sessions_response, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"sessions", &list_agent_sessions_response::sessions, true}, + }; +} + +struct get_agent_session_request { + std::string environment; + std::int64_t session = 0; + + friend bool operator==(const get_agent_session_request&, const get_agent_session_request&) = default; +}; + +/** + * @brief The members of get_agent_session_request, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &get_agent_session_request::environment}, + ::compass::db::codec::field{"session", &get_agent_session_request::session}, + }; +} + +struct agent_turn { + std::int64_t id = 0; + std::int32_t ord = 0; + std::string question; + std::string asked_at; + agent_passages_event retrieval; + std::string answer; + agent_turn_status status{}; + std::optional done; + std::optional failure; + + friend bool operator==(const agent_turn&, const agent_turn&) = default; +}; + +/** + * @brief The members of agent_turn, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"id", &agent_turn::id, true}, + ::compass::db::codec::field{"ord", &agent_turn::ord, true}, + ::compass::db::codec::field{"question", &agent_turn::question}, + ::compass::db::codec::field{"asked_at", &agent_turn::asked_at}, + ::compass::db::codec::field{"retrieval", &agent_turn::retrieval}, + ::compass::db::codec::field{"answer", &agent_turn::answer}, + ::compass::db::codec::field{"status", &agent_turn::status}, + ::compass::db::codec::field{"done", &agent_turn::done}, + ::compass::db::codec::field{"failure", &agent_turn::failure}, + }; +} + +struct get_agent_session_response { + std::int64_t session = 0; + std::string environment; + std::string title; + std::string created_at; + std::string updated_at; + std::vector turns; + + friend bool operator==(const get_agent_session_response&, const get_agent_session_response&) = default; +}; + +/** + * @brief The members of get_agent_session_response, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"session", &get_agent_session_response::session, true}, + ::compass::db::codec::field{"environment", &get_agent_session_response::environment}, + ::compass::db::codec::field{"title", &get_agent_session_response::title}, + ::compass::db::codec::field{"created_at", &get_agent_session_response::created_at}, + ::compass::db::codec::field{"updated_at", &get_agent_session_response::updated_at}, + ::compass::db::codec::field{"turns", &get_agent_session_response::turns, true}, + }; +} + +struct delete_agent_session_request { + std::string environment; + std::int64_t session = 0; + + friend bool operator==(const delete_agent_session_request&, const delete_agent_session_request&) = default; +}; + +/** + * @brief The members of delete_agent_session_request, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &delete_agent_session_request::environment}, + ::compass::db::codec::field{"session", &delete_agent_session_request::session}, + }; +} + +struct agent_session_ask_request { + std::string environment; + std::int64_t session = 0; + std::string q; + + friend bool operator==(const agent_session_ask_request&, const agent_session_ask_request&) = default; +}; + +/** + * @brief The members of agent_session_ask_request, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"environment", &agent_session_ask_request::environment}, + ::compass::db::codec::field{"session", &agent_session_ask_request::session}, + ::compass::db::codec::field{"q", &agent_session_ask_request::q}, + }; +} + +/** + * @brief The members of agent_session_ask_request its route reads from the JSON body. The + * route sets the others from the request line. + */ +[[nodiscard]] constexpr auto body_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"q", &agent_session_ask_request::q}, + }; +} + +} + +namespace compass::db::codec { + +#ifndef COMPASS_HTTP_MESSAGES_AGENT_TURN_STATUS_ENUM +#define COMPASS_HTTP_MESSAGES_AGENT_TURN_STATUS_ENUM +/** + * @brief agent_turn_status travels as the name of its value. + */ +template <> +struct text_form { + static constexpr std::string_view wire_name = "a agent_turn_status"; + + static constexpr std::string_view names[] = { "streaming", "done", "failed", "stopped", "cut" }; + + static constexpr compass::http::messages::agent_turn_status values[] = { compass::http::messages::agent_turn_status::streaming, compass::http::messages::agent_turn_status::done, compass::http::messages::agent_turn_status::failed, compass::http::messages::agent_turn_status::stopped, compass::http::messages::agent_turn_status::cut }; + + static std::string to_text(compass::http::messages::agent_turn_status v) { + return std::string(to_string(v)); + } + + static compass::http::messages::agent_turn_status from_text(std::string_view text) { + if (const auto v = compass::http::messages::agent_turn_status_of(text)) + return *v; + throw std::invalid_argument("Not " + std::string(wire_name) + ": '" + + std::string(text) + "' is not one of streaming, done, failed, stopped, cut"); + } +}; +#endif + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::create_agent_session_request& v); + + static compass::http::messages::create_agent_session_request read_json(std::string_view text); + + static compass::http::messages::create_agent_session_request read_body_json(std::string_view text); + + static std::string body_json_schema(); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::create_agent_session_response& v); + + static compass::http::messages::create_agent_session_response read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::list_agent_sessions_request& v); + + static compass::http::messages::list_agent_sessions_request read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::agent_session_summary& v); + + static compass::http::messages::agent_session_summary read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::list_agent_sessions_response& v); + + static compass::http::messages::list_agent_sessions_response read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::get_agent_session_request& v); + + static compass::http::messages::get_agent_session_request read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::agent_turn& v); + + static compass::http::messages::agent_turn read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::get_agent_session_response& v); + + static compass::http::messages::get_agent_session_response read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::delete_agent_session_request& v); + + static compass::http::messages::delete_agent_session_request read_json(std::string_view text); +}; + +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::agent_session_ask_request& v); + + static compass::http::messages::agent_session_ask_request read_json(std::string_view text); + + static compass::http::messages::agent_session_ask_request read_body_json(std::string_view text); + + static std::string body_json_schema(); +}; + +} + +#endif diff --git a/projects/compass.http/include/compass.http/ops/agent.hpp b/projects/compass.http/include/compass.http/ops/agent.hpp index 2550685a..9883b5e4 100644 --- a/projects/compass.http/include/compass.http/ops/agent.hpp +++ b/projects/compass.http/include/compass.http/ops/agent.hpp @@ -92,6 +92,24 @@ agent_section(std::span sections, [[nodiscard]] agent_retrieval agent_retrieve(std::string_view question, const agent_search& search, const agent_sections& sections); +/** + * @brief The metadata-only =passages= event the stream sends and the session + * stores, so a restore cannot drift from the live answer. + */ +[[nodiscard]] messages::agent_passages_event agent_passages_event_of( + const agent_retrieval& found, std::uint32_t retrieval_ms); + +/** + * @brief One exchange of a session, as the model's history gives it: the + * question as it was asked and the answer as it settled. + */ +struct agent_exchange { + std::string question; + std::string answer; + + friend bool operator==(const agent_exchange&, const agent_exchange&) = default; +}; + /** * @brief The chat the model answers: the system prompt, which tells the * model what knowledge and work history are, or, when there are no diff --git a/projects/compass.http/include/compass.http/query/sessions.hpp b/projects/compass.http/include/compass.http/query/sessions.hpp new file mode 100644 index 00000000..7ac88fab --- /dev/null +++ b/projects/compass.http/include/compass.http/query/sessions.hpp @@ -0,0 +1,121 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_HTTP_QUERY_SESSIONS_HPP +#define COMPASS_HTTP_QUERY_SESSIONS_HPP + +#include +#include +#include +#include +#include +#include "compass.db/io/connection.hpp" +#include "compass.http/agent/turn.hpp" +#include "compass.http/domain/caller.hpp" +#include "compass.http/messages/agent_sessions_protocol.hpp" +#include "compass.http/ops/agent.hpp" + +/** + * @file sessions.hpp + * @brief The conversations with the compass agent: their create, list, read + * and delete, and the turns an ask writes. Every statement filters the + * session by the triple the caller names, =environment=, =subject= and + * =view_name=; a row of another triple is not found, as an absent row is. + * All of a call's SQL runs in one short transaction, never while + * llama-server answers. + */ +namespace compass::http::query { + +/** + * @brief A session as the ask reads it: its title, its done exchanges, + * oldest first, and the last question asked in it, for a follow-up's + * retrieval. The retrieval itself runs in the caller's view, in the same + * snapshot. + */ +struct agent_session_state { + std::string environment; + std::string title; + std::vector history; + std::string last_question; +}; + +/// The turn an ask opened: its row and its place in the session. +struct agent_begin_turn { + std::int64_t turn = 0; + std::int32_t ord = 0; +}; + +[[nodiscard]] messages::create_agent_session_response create_agent_session( + db::io::connection& c, const domain::caller& who, + const messages::create_agent_session_request& r); + +[[nodiscard]] messages::list_agent_sessions_response list_agent_sessions( + db::io::connection& c, const domain::caller& who, + const messages::list_agent_sessions_request& r); + +[[nodiscard]] std::optional get_agent_session( + db::io::connection& c, const domain::caller& who, + const messages::get_agent_session_request& r); + +/// Deletes the caller's session; another caller's answers not found, as a +/// create under its id did. +void delete_agent_session(db::io::connection& c, const domain::caller& who, + const messages::delete_agent_session_request& r); + +/** + * @brief The session and what an ask needs from it, or nothing when the + * triple does not own it. @p max_turns bounds the done exchanges read. + * @throws db::io::error when a stored event is not the JSON it should be. + */ +[[nodiscard]] std::optional load_agent_session( + db::io::connection& c, const domain::caller& who, std::string_view environment, + std::int64_t session, std::size_t max_turns); + +/** + * @brief Locks the session and inserts its next exchange as =streaming=, + * with the retrieval event the stream will send, the model and the actor. + * The session is titled from its first question when it has no title. + * @throws query::rejected_write not_found when the triple does not own it. + */ +[[nodiscard]] agent_begin_turn begin_agent_turn( + db::io::connection& c, const domain::caller& who, std::string_view environment, + std::int64_t session, std::string_view question, std::string_view retrieval_json, + std::string_view model); + +/// Replaces the answer of a streaming turn with the snapshot taken so far. +void save_agent_partial(db::io::connection& c, std::int64_t turn, + std::string_view answer); + +/** + * @brief Settles a streaming turn with its answer and end. A turn already + * settled, or deleted with its session, is left as it is, so a late record + * changes nothing. + */ +void finish_agent_turn(db::io::connection& c, const agent::turn_record& r); + +/** + * @brief Marks every turn left =streaming= as =cut=: the answer of a + * process that stopped without settling it. Meant for startup, before the + * service answers. @returns how many rows it settled. + */ +[[nodiscard]] std::uint32_t recover_agent_turns(db::io::connection& c); + +} + +#endif diff --git a/projects/compass.http/include/compass.http/routes/agent_sessions_routes.hpp b/projects/compass.http/include/compass.http/routes/agent_sessions_routes.hpp new file mode 100644 index 00000000..ac33afbe --- /dev/null +++ b/projects/compass.http/include/compass.http/routes/agent_sessions_routes.hpp @@ -0,0 +1,97 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_http_routes.hpp.mustache + * To modify, update the template and regenerate. + */ +#ifndef COMPASS_HTTP_ROUTES_AGENT_SESSIONS_ROUTES_HPP +#define COMPASS_HTTP_ROUTES_AGENT_SESSIONS_ROUTES_HPP + +#include +#include "compass.http/domain/caller.hpp" +#include "compass.http/messages/agent_sessions_protocol.hpp" +#include "compass.http/net/router.hpp" + +namespace compass::http::routes { + +/** + * @brief What answers create_agent_session: Create a conversation with the compass agent. + */ +using create_agent_session_handler = std::function; + +/** + * @brief Adds POST /v1/{environment}/agent/sessions, the tool create_agent_session, to @p r, answered by + * @p h. + */ +void add_create_agent_session(net::router& r, create_agent_session_handler h); + +/** + * @brief What answers list_agent_sessions: List the caller's conversations with the compass agent. + */ +using list_agent_sessions_handler = std::function; + +/** + * @brief Adds GET /v1/{environment}/agent/sessions, the tool list_agent_sessions, to @p r, answered by + * @p h. + */ +void add_list_agent_sessions(net::router& r, list_agent_sessions_handler h); + +/** + * @brief What answers get_agent_session: Read a conversation with the compass agent. + */ +using get_agent_session_handler = std::function; + +/** + * @brief Adds GET /v1/{environment}/agent/sessions/{session}, the tool get_agent_session, to @p r, answered by + * @p h. + */ +void add_get_agent_session(net::router& r, get_agent_session_handler h); + +/** + * @brief What answers delete_agent_session: Delete a conversation with the compass agent. + */ +using delete_agent_session_handler = std::function; + +/** + * @brief Adds DELETE /v1/{environment}/agent/sessions/{session}, the tool delete_agent_session, to @p r, answered by + * @p h. + */ +void add_delete_agent_session(net::router& r, delete_agent_session_handler h); + +/** + * @brief What answers ask_agent_session: Ask the compass agent in a conversation. + */ +using ask_agent_session_handler = std::function; + +/** + * @brief Adds POST /v1/{environment}/agent/sessions/{session}/ask, the tool ask_agent_session, to @p r, answered by + * @p h. + */ +void add_ask_agent_session(net::router& r, ask_agent_session_handler h); + +} + +#endif diff --git a/projects/compass.http/modeling/compass.http.agent_sessions.org b/projects/compass.http/modeling/compass.http.agent_sessions.org new file mode 100644 index 00000000..46d2e4f5 --- /dev/null +++ b/projects/compass.http/modeling/compass.http.agent_sessions.org @@ -0,0 +1,391 @@ +:PROPERTIES: +:ID: 3AD52FCF-9965-4AE9-834D-630242B403B6 +:END: +#+title: compass.http.agent_sessions +#+description: Codegen operation model for the compass agent's server-owned conversations: their create, list, read and delete routes, and the streamed question that writes an exchange. +#+type: masd.codegen.operation +#+component: http +#+namespace: compass::http::messages +#+entity_singular: agent_sessions +#+brief: The conversations with the compass agent. +#+filetags: :model:operation:http: +#+created: 2026-12-02 +#+updated: 2026-12-02 + +A conversation belongs to the caller's environment, subject and view: a +create, a list, a read, a delete and an ask name all three in their SQL, and +a mismatch answers as an absent row does. The ask is a streamed =POST= that +writes: it inserts the exchange before the stream opens, and the stream's +terminal sink settles it after the answer. The stateless +=GET /v1/{environment}/agent= stays for a question nothing records. + +* Includes + +#+begin_src cpp :name includes +#include +#include +#include +#include +#include "compass.http/messages/agent_protocol.hpp" +#+end_src + +* Messages + +** create_agent_session_request +:PROPERTIES: +:tool: create_agent_session +:area: documents +:entity: agent_session +:writes: true +:summary: Create a conversation with the compass agent +:response: create_agent_session_response +:http_method: post +:http_path: /v1/{environment}/agent/sessions +:caller: subject +:END: + +Makes a conversation in the caller's environment, subject and view. Its +title is the given one, trimmed and at most 200 code points, else it is +untitled until the first question names it. + +*** environment +:PROPERTIES: +:cpp_type: std::string +:http_in: path +:END: + +The environment the conversation belongs to. + +*** title +:PROPERTIES: +:cpp_type: std::optional +:http_in: body +:required: false +:END: + +The conversation's title; absent or blank leaves it until the first +question. + +** create_agent_session_response + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:END: + +The conversation's id. + +*** created_at +:PROPERTIES: +:cpp_type: std::string +:END: + +When the conversation was made, as UTC. + +** list_agent_sessions_request +:PROPERTIES: +:tool: list_agent_sessions +:area: documents +:entity: agent_session +:writes: false +:summary: List the caller's conversations with the compass agent +:response: list_agent_sessions_response +:http_method: get +:http_path: /v1/{environment}/agent/sessions +:caller: subject +:END: + +The caller's conversations in an environment and view, most recently +changed first. + +*** environment +:PROPERTIES: +:cpp_type: std::string +:http_in: path +:END: + +*** limit +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 50 +:http_in: query +:END: + +At most 100. + +*** offset +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:http_in: query +:END: + +** agent_session_summary + +One conversation in the list. + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:END: + +*** title +:PROPERTIES: +:cpp_type: std::string +:END: + +The given title, else the first question's. + +*** created_at +:PROPERTIES: +:cpp_type: std::string +:END: + +*** updated_at +:PROPERTIES: +:cpp_type: std::string +:END: + +When the conversation last changed. + +*** turns +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +How many exchanges it holds. + +** list_agent_sessions_response + +*** sessions +:PROPERTIES: +:cpp_type: std::vector +:END: + +** get_agent_session_request +:PROPERTIES: +:tool: get_agent_session +:area: documents +:entity: agent_session +:writes: false +:summary: Read a conversation with the compass agent +:response: get_agent_session_response +:http_method: get +:http_path: /v1/{environment}/agent/sessions/{session} +:caller: subject +:END: + +A conversation and its turns, oldest first, as they were stored: the +retrieval event, the answer, and the done or failure event the stream sent. +A conversation of another subject or view answers as absent. + +*** environment +:PROPERTIES: +:cpp_type: std::string +:http_in: path +:END: + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:http_in: path +:END: + +** agent_turn + +One exchange of a conversation. + +*** id +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:END: + +The turn's id. + +*** ord +:PROPERTIES: +:cpp_type: std::int32_t +:default: 0 +:END: + +Its place in the conversation, from 1. + +*** question +:PROPERTIES: +:cpp_type: std::string +:END: + +*** asked_at +:PROPERTIES: +:cpp_type: std::string +:END: + +When the question arrived, as UTC. + +*** retrieval +:PROPERTIES: +:cpp_type: agent_passages_event +:END: + +The =passages= event the stream sent. + +*** answer +:PROPERTIES: +:cpp_type: std::string +:END: + +The answer as stored: the whole one, or the last partial snapshot. + +*** status +:PROPERTIES: +:cpp_type: agent_turn_status +:values: streaming done failed stopped cut +:END: + +=streaming= while the answer is written, then =done=, =failed=, +=stopped= when the client left, or =cut= when neither settled it. + +*** done +:PROPERTIES: +:cpp_type: std::optional +:END: + +The =done= event; absent unless the turn is done. + +*** failure +:PROPERTIES: +:cpp_type: std::optional +:END: + +The =failure= event; absent unless the turn failed. + +** get_agent_session_response + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:END: + +*** environment +:PROPERTIES: +:cpp_type: std::string +:END: + +*** title +:PROPERTIES: +:cpp_type: std::string +:END: + +*** created_at +:PROPERTIES: +:cpp_type: std::string +:END: + +*** updated_at +:PROPERTIES: +:cpp_type: std::string +:END: + +*** turns +:PROPERTIES: +:cpp_type: std::vector +:END: + +The exchanges, oldest first. + +** delete_agent_session_request +:PROPERTIES: +:tool: delete_agent_session +:area: documents +:entity: agent_session +:writes: true +:destructive: true +:idempotent: true +:summary: Delete a conversation with the compass agent +:http_method: delete +:http_path: /v1/{environment}/agent/sessions/{session} +:caller: subject +:END: + +Deletes a conversation and its turns. A conversation of another subject or +view is not deleted, and answers as absent. + +*** environment +:PROPERTIES: +:cpp_type: std::string +:http_in: path +:END: + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:http_in: path +:END: + +** agent_session_ask_request +:PROPERTIES: +:tool: ask_agent_session +:area: documents +:entity: agent_session +:writes: true +:stream: true +:summary: Ask the compass agent in a conversation +:http_method: post +:http_path: /v1/{environment}/agent/sessions/{session}/ask +:caller: subject +:END: + +Asks a question in a conversation and answers it as the stateless route +does, as server-sent events. The question is written as a =streaming= turn +before the stream opens; the answer is written by the stream's terminal +sink, off the connection's thread. A conversation of another subject or +view answers as absent, and no stream opens. + +*** environment +:PROPERTIES: +:cpp_type: std::string +:http_in: path +:END: + +*** session +:PROPERTIES: +:cpp_type: std::int64_t +:default: 0 +:http_in: path +:END: + +*** q +:PROPERTIES: +:cpp_type: std::string +:http_in: body +:END: + +The question, at most 500 characters, counted as code points; an empty or +longer one is refused as =invalid=. + +* Physical space + +| Address | Enabled | +|------------------------+---------| +| =masd.cpp.http-routes= | true | + +* Notes + +- =agent_session_ask_request= is the one streamed route that writes: the + router admits a stream that writes only on a =POST=, and the stream is no + MCP tool. The create, list, read and delete routes are ordinary tools. +- =get_agent_session_response= rebuilds the browser's turn exactly: the + stored =retrieval=, =done= and =failure= are the events the live stream + sent, because the handler serializes one event object for both. + +* See also + +- [[id:127BE790-567D-48EC-B0FC-9376C002EB88][compass.http.agent]]: the stateless ask and the event messages. +- [[id:277ECB9A-5B6A-4235-9207-D5EC3AB816C0][compass.http]], which lists the properties these models use. diff --git a/projects/compass.http/src/CMakeLists.txt b/projects/compass.http/src/CMakeLists.txt index 123f29c9..6491b9ce 100644 --- a/projects/compass.http/src/CMakeLists.txt +++ b/projects/compass.http/src/CMakeLists.txt @@ -41,6 +41,7 @@ endforeach() add_library(${lib_target_name} ${embedded_files} agent/llama.cpp + agent/turn_writer.cpp app/http_server.cpp app/service.cpp domain/catalogue_rules.cpp @@ -51,6 +52,7 @@ add_library(${lib_target_name} mcp/route_tools.cpp mcp/session_registry.cpp messages/agent_protocol.cpp + messages/agent_sessions_protocol.cpp messages/campaign_writes_protocol.cpp messages/document_queries_protocol.cpp messages/errors_protocol.cpp @@ -64,8 +66,10 @@ add_library(${lib_target_name} ops/views.cpp query/convert.cpp query/reads.cpp + query/sessions.cpp query/writes.cpp routes/agent_routes.cpp + routes/agent_sessions_routes.cpp routes/campaign_writes_routes.cpp routes/document_queries_routes.cpp routes/testing_queries_routes.cpp diff --git a/projects/compass.http/src/agent/llama.cpp b/projects/compass.http/src/agent/llama.cpp index 33c106f8..45f94072 100644 --- a/projects/compass.http/src/agent/llama.cpp +++ b/projects/compass.http/src/agent/llama.cpp @@ -20,6 +20,7 @@ #include "compass.http/agent/llama.hpp" #include +#include #include #include #include @@ -201,20 +202,26 @@ messages::agent_status_response shared_status::get() { struct answer_stream::exchange { exchange(const asio::any_io_executor& on, types::agent_settings s, std::string chat, std::size_t passages_given, std::chrono::steady_clock::time_point asked_at, - bool names) + bool names, std::int64_t turn_number, std::shared_ptr record_to, + std::chrono::milliseconds snapshot_every) : events(on, 64) , stream(on) , server(std::move(s)) , body(std::move(chat)) , passages(passages_given) , asked(asked_at) - , names_server(names) {} + , names_server(names) + , turn(turn_number) + , sink(std::move(record_to)) + , last_partial(asked_at) + , partial_every(snapshot_every) {} asio::awaitable run(); asio::awaitable ask(); void take_lines(); void finish(); void fail(agent_health code, std::string message); + void settle(turn_end end); // Here, not in the stream that emits it: the exchange outlives that stream. asio::cancellation_signal leaving; @@ -227,6 +234,11 @@ struct answer_stream::exchange { std::size_t passages; std::chrono::steady_clock::time_point asked; bool names_server; + std::int64_t turn; + std::shared_ptr sink; + std::chrono::steady_clock::time_point last_partial; + std::chrono::milliseconds partial_every; + std::atomic recorded{false}; bool told_done = false; bool ended = false; std::string out; @@ -235,31 +247,29 @@ struct answer_stream::exchange { }; answer_stream::answer_stream(types::agent_settings server, ops::agent_retrieval found, - std::string question, std::uint32_t retrieval_ms, + messages::agent_passages_event passages, std::string question, std::chrono::steady_clock::time_point asked, answer_options options) : server_(std::move(server)) , found_(std::move(found)) + , passages_(std::move(passages)) , question_(std::move(question)) - , retrieval_ms_(retrieval_ms) , asked_(asked) , options_(std::move(options)) {} answer_stream::~answer_stream() { - if (exchange_) - exchange_->leaving.emit(asio::cancellation_type::terminal); + if (!exchange_) + return; + exchange_->settle(turn_end::stopped); + exchange_->leaving.emit(asio::cancellation_type::terminal); } void answer_stream::start(const asio::any_io_executor& on) { - messages::agent_passages_event e; - e.queries = found_.queries; - e.retrieval_ms = retrieval_ms_; - for (const auto& p : found_.passages) - e.passages.push_back(p.given); out_ += ops::agent_event( - "passages", db::codec::wire_traits::write_json(e)); + "passages", db::codec::wire_traits::write_json(passages_)); exchange_ = std::make_shared( on, server_, ops::agent_chat_body(ops::agent_prompt_for(question_, found_.passages)), - found_.passages.size(), asked_, options_.names_server); + found_.passages.size(), asked_, options_.names_server, options_.turn, options_.sink, + options_.partial_every); asio::co_spawn( on, [x = exchange_] { return x->run(); }, asio::bind_cancellation_slot(exchange_->leaving.slot(), asio::detached)); @@ -417,11 +427,32 @@ void answer_stream::exchange::take_lines() { } } text.erase(0, start); - if (!ended && text.size() > line_limit) + if (ended) + return; + if (sink && !answer.empty()) { + const auto now = std::chrono::steady_clock::now(); + if (now - last_partial >= partial_every) { + last_partial = now; + sink->record_partial(turn, answer); + } + } + if (text.size() > line_limit) fail(agent_health::failing, "llama-server at " + address(server) + " sent a line longer than compass reads."); } +void answer_stream::exchange::settle(turn_end end) { + if (!sink || recorded.exchange(true)) + return; + turn_record r; + r.turn = turn; + r.answer = answer; + r.end = end; + if (end == turn_end::done) + r.done = done; + sink->record(std::move(r)); +} + void answer_stream::exchange::finish() { const auto citations = ops::agent_cite(answer, passages); done.cited = citations.cited; @@ -430,6 +461,7 @@ void answer_stream::exchange::finish() { std::chrono::duration_cast(std::chrono::steady_clock::now() - asked) .count()); + settle(turn_end::done); out += ops::agent_event( "done", db::codec::wire_traits::write_json(done)); ended = true; @@ -439,6 +471,14 @@ void answer_stream::exchange::fail(agent_health code, std::string message) { messages::agent_failure_event e; e.code = code; e.message = names_server ? std::move(message) : failure_without_server(code); + if (sink && !recorded.exchange(true)) { + turn_record r; + r.turn = turn; + r.answer = answer; + r.end = turn_end::failed; + r.failure = e; + sink->record(std::move(r)); + } out += ops::agent_event( "failure", db::codec::wire_traits::write_json(e)); ended = true; diff --git a/projects/compass.http/src/agent/turn_writer.cpp b/projects/compass.http/src/agent/turn_writer.cpp new file mode 100644 index 00000000..ce8f9977 --- /dev/null +++ b/projects/compass.http/src/agent/turn_writer.cpp @@ -0,0 +1,117 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.http/agent/turn_writer.hpp" + +#include +#include +#include "compass.http/app/service.hpp" +#include "compass.http/query/sessions.hpp" + +namespace compass::http::agent { + +turn_writer::turn_writer(app::connection_pool& pool, + std::function log) + : pool_(pool) + , log_(std::move(log)) + , worker_([this](std::stop_token stop) { run(stop); }) {} + +turn_writer::~turn_writer() { + worker_.request_stop(); + ready_.notify_all(); + if (worker_.joinable()) + worker_.join(); +} + +void turn_writer::push(queued_turn q) noexcept { + { + const std::lock_guard lock(mutex_); + if (queue_.size() < max_queued) { + queue_.push_back(std::move(q)); + ready_.notify_one(); + return; + } + dropped_.fetch_add(1, std::memory_order_relaxed); + } + if (log_) + log_("the agent's turn queue is full; a record was dropped"); +} + +void turn_writer::record(turn_record r) noexcept { + queued_turn q; + q.what = queued_turn::kind::terminal; + q.record = std::move(r); + push(std::move(q)); +} + +void turn_writer::record_partial(std::int64_t turn, std::string answer) noexcept { + queued_turn q; + q.what = queued_turn::kind::partial; + q.turn = turn; + q.answer = std::move(answer); + push(std::move(q)); +} + +void turn_writer::flush() { + std::unique_lock lock(mutex_); + ready_.wait(lock, [this] { return queue_.empty() && !writing_; }); +} + +std::uint64_t turn_writer::dropped() const noexcept { + return dropped_.load(std::memory_order_relaxed); +} + +void turn_writer::run(std::stop_token stop) { + for (;;) { + queued_turn q; + { + std::unique_lock lock(mutex_); + ready_.wait(lock, [this, &stop] { + return !queue_.empty() || stop.stop_requested(); + }); + if (queue_.empty() && stop.stop_requested()) + return; + q = std::move(queue_.front()); + queue_.pop_front(); + writing_ = true; + } + try { + if (q.what == queued_turn::kind::terminal) + pool_.write([&q](db::io::connection& c) { + query::finish_agent_turn(c, q.record); + }); + else + pool_.write([&q](db::io::connection& c) { + query::save_agent_partial(c, q.turn, q.answer); + }); + } catch (const std::exception& e) { + if (log_) + log_("agent turn " + std::to_string(q.record.turn == 0 ? q.turn : q.record.turn) + + " was not settled: " + e.what()); + } + { + const std::lock_guard lock(mutex_); + writing_ = false; + if (queue_.empty()) + ready_.notify_all(); + } + } +} + +} diff --git a/projects/compass.http/src/app/service.cpp b/projects/compass.http/src/app/service.cpp index 7545330e..49e7d4e9 100644 --- a/projects/compass.http/src/app/service.cpp +++ b/projects/compass.http/src/app/service.cpp @@ -30,6 +30,7 @@ #include #include #include "compass.db/codec/json_document.hpp" +#include "compass.db/codec/wire_traits_fwd.hpp" #include "compass.db/query/graph.hpp" #include "compass.db/query/scope.hpp" #include "compass.db/query/search.hpp" @@ -44,8 +45,10 @@ #include "compass.http/ops/views.hpp" #include "compass.http/query/convert.hpp" #include "compass.http/query/reads.hpp" +#include "compass.http/query/sessions.hpp" #include "compass.http/query/writes.hpp" #include "compass.http/routes/agent_routes.hpp" +#include "compass.http/routes/agent_sessions_routes.hpp" #include "compass.http/routes/campaign_writes_routes.hpp" #include "compass.http/routes/document_queries_routes.hpp" #include "compass.http/routes/testing_queries_routes.hpp" @@ -225,7 +228,8 @@ service::service(types::settings s, connection_pool& pool, std::optional sync) : settings_(std::move(s)) , pool_(pool) - , sync_(std::move(sync)) { + , sync_(std::move(sync)) + , writer_(std::make_shared(pool_)) { auto views = ops::compile_views(settings_.views); if (!views) throw std::runtime_error(views.error()); @@ -277,13 +281,61 @@ void service::add_agent_routes(net::router& r) { namespace m = messages; using db::io::connection; const auto open = std::make_shared>(0); - routes::add_get_agent_answer(r, [this, open](const domain::caller& c, - const m::agent_request& q) { - if (q.q.find_first_not_of(" \t\r\n") == std::string::npos) + const auto require_question = [](const std::string& text) { + if (text.find_first_not_of(" \t\r\n") == std::string::npos) throw refusal::invalid("The question is empty."); - if (code_points(q.q) > max_question) + if (code_points(text) > max_question) throw refusal::invalid("The question is longer than " + std::to_string(max_question) + " characters."); + }; + const auto retrieve = [](connection& conn, const std::string& environment, + const db::types::view_filter& view, std::string_view question) { + return ops::agent_retrieve( + question, + [&](const std::string& query) { + db::types::search_request s; + s.environment = environment; + s.q = query; + s.limit = 10; + return db::query::search(conn, view, s).hits; + }, + [&](const db::types::search_hit& hit) { + return db::query::sections(conn, view, environment, hit.path); + }); + }; + + routes::add_get_agent_answer(r, [this, open, require_question, retrieve]( + const domain::caller& c, const m::agent_request& q) { + require_question(q.q); + agent::answer_options options; + options.names_server = runs_the_service(c); + options.slot = take_stream_slot(open); + const auto asked = std::chrono::steady_clock::now(); + const auto& view = view_of(c); + auto found = refusing([&] { + return pool_.read([&](connection& conn) { + require_environment(conn, q.environment); + return retrieve(conn, q.environment, view, q.q); + }); + }); + const auto retrieval_ms = static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now() - asked) + .count()); + auto passages = ops::agent_passages_event_of(found, retrieval_ms); + domain::http_response out; + out.content_type = "text/event-stream"; + out.headers["Cache-Control"] = "no-cache"; + out.headers["X-Accel-Buffering"] = "no"; + out.body_awaitable = std::make_shared( + settings_.agent, std::move(found), std::move(passages), q.q, asked, + std::move(options)); + return out; + }); + routes::add_ask_agent_session(r, [this, open, require_question, retrieve]( + const domain::caller& c, + const m::agent_session_ask_request& q) { + require_question(q.q); agent::answer_options options; options.names_server = runs_the_service(c); options.slot = take_stream_slot(open); @@ -292,30 +344,35 @@ void service::add_agent_routes(net::router& r) { auto found = refusing([&] { return pool_.read([&](connection& conn) { require_environment(conn, q.environment); - return ops::agent_retrieve( - q.q, - [&](const std::string& query) { - db::types::search_request s; - s.environment = q.environment; - s.q = query; - s.limit = 10; - return db::query::search(conn, view, s).hits; - }, - [&](const db::types::search_hit& hit) { - return db::query::sections(conn, view, q.environment, hit.path); - }); + if (!query::load_agent_session(conn, c, q.environment, q.session, 0)) + throw refusal::not_found("The caller has no conversation " + + std::to_string(q.session) + " in the environment " + + q.environment + "."); + return retrieve(conn, q.environment, view, q.q); }); }); const auto retrieval_ms = static_cast( std::chrono::duration_cast( std::chrono::steady_clock::now() - asked) .count()); + auto passages = ops::agent_passages_event_of(found, retrieval_ms); + const auto retrieval_json = + db::codec::wire_traits::write_json(passages); + const auto begun = refusing([&] { + return pool_.write([&](connection& conn) { + return query::begin_agent_turn(conn, c, q.environment, q.session, q.q, + retrieval_json, settings_.agent.model); + }); + }); + options.turn = begun.turn; + options.sink = writer_; domain::http_response out; out.content_type = "text/event-stream"; out.headers["Cache-Control"] = "no-cache"; out.headers["X-Accel-Buffering"] = "no"; out.body_awaitable = std::make_shared( - settings_.agent, std::move(found), q.q, retrieval_ms, asked, std::move(options)); + settings_.agent, std::move(found), std::move(passages), q.q, asked, + std::move(options)); return out; }); const auto status = std::make_shared(settings_.agent); @@ -531,6 +588,27 @@ void service::add_read_routes(net::router& r) { }); }); + routes::add_list_agent_sessions(r, [this](const domain::caller& c, + const m::list_agent_sessions_request& q) { + within_ceiling(q.limit); + return refusing([&] { + return pool_.read( + [&](connection& conn) { return query::list_agent_sessions(conn, c, q); }); + }); + }); + routes::add_get_agent_session(r, [this](const domain::caller& c, + const m::get_agent_session_request& q) { + return refusing([&] { + auto out = pool_.read( + [&](connection& conn) { return query::get_agent_session(conn, c, q); }); + if (!out) + throw refusal::not_found("The caller has no conversation " + + std::to_string(q.session) + " in the environment " + + q.environment + "."); + return std::move(*out); + }); + }); + auto catalogue = r.get("/v1/catalogue") .summary("List the service's operations") .description("Every route's declaration and input schema, in the " @@ -633,6 +711,22 @@ void service::add_openapi_routes(net::router& r) const { void service::add_write_routes(net::router& r) { namespace m = messages; + routes::add_create_agent_session(r, [this](const domain::caller& c, + const m::create_agent_session_request& q) { + return refusing([&] { + return pool_.write([&](db::io::connection& conn) { + return query::create_agent_session(conn, c, q); + }); + }); + }); + routes::add_delete_agent_session(r, [this](const domain::caller& c, + const m::delete_agent_session_request& q) { + refusing([&] { + pool_.write([&](db::io::connection& conn) { + query::delete_agent_session(conn, c, q); + }); + }); + }); routes::add_start_run(r, [this](const domain::caller& c, const m::start_run_request& q) { return refusing([&] { return pool_.write([&](db::io::connection& conn) { diff --git a/projects/compass.http/src/messages/agent_sessions_protocol.cpp b/projects/compass.http/src/messages/agent_sessions_protocol.cpp new file mode 100644 index 00000000..0e027059 --- /dev/null +++ b/projects/compass.http/src/messages/agent_sessions_protocol.cpp @@ -0,0 +1,128 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_protocol.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.http/messages/agent_sessions_protocol.hpp" + +#include "compass.db/codec/json_schema.hpp" +#include "compass.db/codec/struct_codec.hpp" + +namespace compass::db::codec { + +std::string wire_traits::write_json(const compass::http::messages::create_agent_session_request& v) { + return object::write_json(v); +} + +compass::http::messages::create_agent_session_request wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +compass::http::messages::create_agent_session_request wire_traits::read_body_json(std::string_view text) { + return object::read_json(text, body_fields(std::type_identity{})); +} + +std::string wire_traits::body_json_schema() { + return json_schema(body_fields(std::type_identity{})); +} + +std::string wire_traits::write_json(const compass::http::messages::create_agent_session_response& v) { + return object::write_json(v); +} + +compass::http::messages::create_agent_session_response wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::list_agent_sessions_request& v) { + return object::write_json(v); +} + +compass::http::messages::list_agent_sessions_request wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::agent_session_summary& v) { + return object::write_json(v); +} + +compass::http::messages::agent_session_summary wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::list_agent_sessions_response& v) { + return object::write_json(v); +} + +compass::http::messages::list_agent_sessions_response wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::get_agent_session_request& v) { + return object::write_json(v); +} + +compass::http::messages::get_agent_session_request wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::agent_turn& v) { + return object::write_json(v); +} + +compass::http::messages::agent_turn wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::get_agent_session_response& v) { + return object::write_json(v); +} + +compass::http::messages::get_agent_session_response wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::delete_agent_session_request& v) { + return object::write_json(v); +} + +compass::http::messages::delete_agent_session_request wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +std::string wire_traits::write_json(const compass::http::messages::agent_session_ask_request& v) { + return object::write_json(v); +} + +compass::http::messages::agent_session_ask_request wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + +compass::http::messages::agent_session_ask_request wire_traits::read_body_json(std::string_view text) { + return object::read_json(text, body_fields(std::type_identity{})); +} + +std::string wire_traits::body_json_schema() { + return json_schema(body_fields(std::type_identity{})); +} + +} diff --git a/projects/compass.http/src/ops/agent.cpp b/projects/compass.http/src/ops/agent.cpp index 3b53f199..d346d8ac 100644 --- a/projects/compass.http/src/ops/agent.cpp +++ b/projects/compass.http/src/ops/agent.cpp @@ -248,6 +248,16 @@ agent_retrieval agent_retrieve(std::string_view question, const agent_search& se return out; } +messages::agent_passages_event agent_passages_event_of(const agent_retrieval& found, + std::uint32_t retrieval_ms) { + messages::agent_passages_event out; + out.queries = found.queries; + out.retrieval_ms = retrieval_ms; + for (const auto& p : found.passages) + out.passages.push_back(p.given); + return out; +} + agent_prompt agent_prompt_for(std::string_view question, std::span passages) { if (passages.empty()) diff --git a/projects/compass.http/src/query/sessions.cpp b/projects/compass.http/src/query/sessions.cpp new file mode 100644 index 00000000..8faec7fc --- /dev/null +++ b/projects/compass.http/src/query/sessions.cpp @@ -0,0 +1,346 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.http/query/sessions.hpp" + +#include +#include +#include +#include +#include +#include "compass.db/codec/wire_traits_fwd.hpp" +#include "compass.db/query/scope.hpp" +#include "compass.http/query/writes.hpp" + +namespace compass::http::query { + +namespace { + +namespace io = db::io; +using reason = rejected_write::reason; + +constexpr std::string_view utc_time = "'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'"; + +std::string utc(std::string_view column) { + return "coalesce(to_char(" + std::string(column) + " AT TIME ZONE 'UTC', " + + std::string(utc_time) + "), '')"; +} + +bool blank(std::string_view s) { + return s.find_first_not_of(" \t\r\n") == std::string_view::npos; +} + +void require_subject(const domain::caller& who) { + if (blank(who.subject)) + throw rejected_write(reason::no_subject, + "The request names no subject in Compass-Subject."); +} + +[[noreturn]] void reject(reason why, const std::string& what) { + throw rejected_write(why, what); +} + +std::string number(std::int64_t v) { + return std::to_string(v); +} + +std::int64_t to_id(std::string_view text) { + std::int64_t v = 0; + std::from_chars(text.data(), text.data() + text.size(), v); + return v; +} + +std::string_view trimmed(std::string_view s) { + const auto first = s.find_first_not_of(" \t\r\n"); + if (first == std::string_view::npos) + return {}; + const auto last = s.find_last_not_of(" \t\r\n"); + return s.substr(first, last - first + 1); +} + +/** + * @brief @p text cut to @p limit code points, on a UTF-8 character's + * boundary. Every byte that starts no continuation byte starts a character. + */ +std::string clip_code_points(std::string_view text, std::size_t limit) { + std::size_t at = 0; + for (std::size_t points = 0; at < text.size() && points < limit; ++points) { + ++at; + while (at < text.size() && (static_cast(text[at]) & 0xC0) == 0x80) + ++at; + } + return std::string(text.substr(0, at)); +} + +std::optional title_given(const std::optional& given) { + if (!given) + return std::nullopt; + const auto text = trimmed(*given); + if (text.empty()) + return std::nullopt; + return clip_code_points(text, 200); +} + +std::optional title_asked(std::string_view question) { + const auto text = trimmed(question); + if (text.empty()) + return std::nullopt; + return clip_code_points(text, 80); +} + +template +Event read_event(std::string_view text, std::string_view what, std::int64_t turn) { + try { + return db::codec::wire_traits::read_json(text); + } catch (const std::exception& e) { + throw io::error("agent.agent_turn " + std::to_string(turn) + " holds a " + + std::string(what) + " that is not the event compass wrote: " + e.what(), + ""); + } +} + +std::string status_of(agent::turn_end end) { + switch (end) { + case agent::turn_end::done: return "done"; + case agent::turn_end::failed: return "failed"; + case agent::turn_end::stopped: return "stopped"; + } + return "stopped"; +} + +} + +messages::create_agent_session_response create_agent_session( + io::connection& c, const domain::caller& who, + const messages::create_agent_session_request& r) { + require_subject(who); + static_cast(db::query::find_environment(c, r.environment)); + const auto title = title_given(r.title); + const auto rows = c.exec( + "INSERT INTO agent.agent_session (environment, subject, actor, view_name, title)\n" + "VALUES ($1, $2, $3, $4, $5)\nRETURNING id, " + utc("created_at"), + {r.environment, who.subject, who.actor, who.view, title}); + messages::create_agent_session_response out; + out.session = to_id(rows.value(0, 0)); + out.created_at = std::string(rows.value(0, 1)); + return out; +} + +messages::list_agent_sessions_response list_agent_sessions( + io::connection& c, const domain::caller& who, + const messages::list_agent_sessions_request& r) { + require_subject(who); + const auto rows = c.exec( + "SELECT s.id, coalesce(s.title, ''), " + utc("s.created_at") + ", " + + utc("s.updated_at") + ", count(t.id)\n" + "FROM agent.agent_session s\n" + "LEFT JOIN agent.agent_turn t ON t.session_id = s.id\n" + "WHERE s.environment = $1 AND s.subject = $2 AND s.view_name = $3\n" + "GROUP BY s.id\n" + "ORDER BY s.updated_at DESC, s.id DESC\n" + "LIMIT $4::bigint OFFSET $5::bigint", + {r.environment, who.subject, who.view, std::to_string(r.limit), + std::to_string(r.offset)}); + messages::list_agent_sessions_response out; + for (std::size_t row = 0; row < rows.rows(); ++row) { + messages::agent_session_summary s; + s.session = to_id(rows.value(row, 0)); + s.title = std::string(rows.value(row, 1)); + s.created_at = std::string(rows.value(row, 2)); + s.updated_at = std::string(rows.value(row, 3)); + std::uint32_t turns = 0; + const auto count = rows.value(row, 4); + std::from_chars(count.data(), count.data() + count.size(), turns); + s.turns = turns; + out.sessions.push_back(std::move(s)); + } + return out; +} + +std::optional get_agent_session( + io::connection& c, const domain::caller& who, + const messages::get_agent_session_request& r) { + require_subject(who); + io::transaction tx(c, io::transaction::snapshot); + const auto session = c.exec( + "SELECT s.id, s.environment, coalesce(s.title, ''), " + utc("s.created_at") + ", " + + utc("s.updated_at") + "\n" + "FROM agent.agent_session s\n" + "WHERE s.id = $1::bigint AND s.environment = $2 AND s.subject = $3\n" + " AND s.view_name = $4", + {number(r.session), r.environment, who.subject, who.view}); + if (session.rows() == 0) + return std::nullopt; + messages::get_agent_session_response out; + out.session = to_id(session.value(0, 0)); + out.environment = std::string(session.value(0, 1)); + out.title = std::string(session.value(0, 2)); + out.created_at = std::string(session.value(0, 3)); + out.updated_at = std::string(session.value(0, 4)); + const auto turns = c.exec( + "SELECT id, ord, question, " + utc("asked_at") + + ", retrieval::text, answer, status, done::text, failure::text\n" + "FROM agent.agent_turn\n" + "WHERE session_id = $1::bigint\n" + "ORDER BY ord", + {number(out.session)}); + for (std::size_t row = 0; row < turns.rows(); ++row) { + messages::agent_turn t; + t.id = to_id(turns.value(row, 0)); + std::from_chars(turns.value(row, 1).data(), + turns.value(row, 1).data() + turns.value(row, 1).size(), t.ord); + t.question = std::string(turns.value(row, 2)); + t.asked_at = std::string(turns.value(row, 3)); + t.retrieval = read_event( + turns.value(row, 4), "retrieval", t.id); + t.answer = std::string(turns.value(row, 5)); + t.status = messages::agent_turn_status_of(turns.value(row, 6)) + .value_or(messages::agent_turn_status::streaming); + if (!turns.is_null(row, 7)) + t.done = read_event( + turns.value(row, 7), "done event", t.id); + if (!turns.is_null(row, 8)) + t.failure = read_event( + turns.value(row, 8), "failure event", t.id); + out.turns.push_back(std::move(t)); + } + return out; +} + +void delete_agent_session(io::connection& c, const domain::caller& who, + const messages::delete_agent_session_request& r) { + require_subject(who); + io::transaction tx(c); + const auto deleted = c.exec( + "DELETE FROM agent.agent_session\n" + "WHERE id = $1::bigint AND environment = $2 AND subject = $3 AND view_name = $4", + {number(r.session), r.environment, who.subject, who.view}); + if (deleted.affected() == 0) { + const auto elsewhere = + c.exec("SELECT 1 FROM agent.agent_session WHERE id = $1::bigint", + {number(r.session)}); + if (elsewhere.rows() > 0) + reject(reason::not_found, "the caller owns no session " + number(r.session) + + " in the environment " + r.environment); + } + tx.commit(); +} + +std::optional load_agent_session( + io::connection& c, const domain::caller& who, std::string_view environment, + std::int64_t session, std::size_t max_turns) { + require_subject(who); + io::transaction tx(c, io::transaction::snapshot); + const auto row = c.exec( + "SELECT environment, coalesce(title, '')\n" + "FROM agent.agent_session\n" + "WHERE id = $1::bigint AND environment = $2 AND subject = $3 AND view_name = $4", + {number(session), std::string(environment), who.subject, who.view}); + if (row.rows() == 0) + return std::nullopt; + agent_session_state out; + out.environment = std::string(row.value(0, 0)); + out.title = std::string(row.value(0, 1)); + const auto history = c.exec( + "SELECT question, answer FROM agent.agent_turn\n" + "WHERE session_id = $1::bigint AND status = 'done'\n" + "ORDER BY ord DESC LIMIT $2::bigint", + {number(session), std::to_string(max_turns)}); + for (std::size_t r = history.rows(); r > 0; --r) + out.history.push_back({std::string(history.value(r - 1, 0)), + std::string(history.value(r - 1, 1))}); + const auto last = c.exec( + "SELECT question FROM agent.agent_turn\n" + "WHERE session_id = $1::bigint\n" + "ORDER BY ord DESC LIMIT 1", + {number(session)}); + if (last.rows() > 0) + out.last_question = std::string(last.value(0, 0)); + return out; +} + +agent_begin_turn begin_agent_turn(io::connection& c, const domain::caller& who, + std::string_view environment, std::int64_t session, + std::string_view question, + std::string_view retrieval_json, + std::string_view model) { + require_subject(who); + io::transaction tx(c); + const auto owned = c.exec( + "SELECT id FROM agent.agent_session\n" + "WHERE id = $1::bigint AND environment = $2 AND subject = $3 AND view_name = $4\n" + "FOR UPDATE", + {number(session), std::string(environment), who.subject, who.view}); + if (owned.rows() == 0) + reject(reason::not_found, "the caller owns no session " + number(session) + + " in the environment " + std::string(environment)); + const auto next = c.exec( + "SELECT coalesce(max(ord), 0) + 1 FROM agent.agent_turn WHERE session_id = $1::bigint", + {number(session)}); + agent_begin_turn out; + out.ord = static_cast(to_id(next.value(0, 0))); + c.exec("UPDATE agent.agent_session\n" + "SET title = coalesce(title, $2), updated_at = now()\n" + "WHERE id = $1::bigint", + {number(session), title_asked(question)}); + const auto inserted = c.exec( + "INSERT INTO agent.agent_turn\n" + " (session_id, ord, question, asked_at, retrieval, model, actor)\n" + "VALUES ($1::bigint, $2::integer, $3, now(), $4::jsonb, $5, $6)\n" + "RETURNING id", + {number(session), std::to_string(out.ord), std::string(question), + std::string(retrieval_json), std::string(model), who.actor}); + out.turn = to_id(inserted.value(0, 0)); + tx.commit(); + return out; +} + +void save_agent_partial(io::connection& c, std::int64_t turn, std::string_view answer) { + io::transaction tx(c); + c.exec("UPDATE agent.agent_turn\n" + "SET answer = $2, updated_at = now()\n" + "WHERE id = $1::bigint AND status = 'streaming'", + {number(turn), std::string(answer)}); + tx.commit(); +} + +void finish_agent_turn(io::connection& c, const agent::turn_record& r) { + std::optional done; + std::optional failure; + if (r.end == agent::turn_end::done && r.done) + done = db::codec::wire_traits::write_json(*r.done); + if (r.end == agent::turn_end::failed && r.failure) + failure = db::codec::wire_traits::write_json(*r.failure); + io::transaction tx(c); + c.exec("UPDATE agent.agent_turn\n" + "SET answer = $2, status = $3, done = $4::jsonb, failure = $5::jsonb,\n" + " updated_at = now()\n" + "WHERE id = $1::bigint AND status = 'streaming'", + {number(r.turn), r.answer, status_of(r.end), done, failure}); + tx.commit(); +} + +std::uint32_t recover_agent_turns(io::connection& c) { + const auto settled = c.exec( + "UPDATE agent.agent_turn SET status = 'cut', updated_at = now()\n" + "WHERE status = 'streaming'"); + return static_cast(settled.affected()); +} + +} diff --git a/projects/compass.http/src/routes/agent_sessions_routes.cpp b/projects/compass.http/src/routes/agent_sessions_routes.cpp new file mode 100644 index 00000000..08c853e7 --- /dev/null +++ b/projects/compass.http/src/routes/agent_sessions_routes.cpp @@ -0,0 +1,194 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_http_routes.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.http/routes/agent_sessions_routes.hpp" + +#include +#include "compass.http/net/answer.hpp" +#include "compass.http/net/binding.hpp" + +namespace compass::http::routes { + +namespace { + +compass::http::messages::create_agent_session_request bind_create_agent_session(const domain::http_request& req) { + net::binding b(req); + compass::http::messages::create_agent_session_request r; + b.body(r); + b.path("environment", r.environment); + b.finish(); + return r; +} + +} + +void add_create_agent_session(net::router& r, create_agent_session_handler h) { + r.add_route(r.post("/v1/{environment}/agent/sessions") + .summary("Create a conversation with the compass agent") + .description("Makes a conversation in the caller's environment, subject and view. Its title is the given one, trimmed and at most 200 code points, else it is untitled until the first question names it.") + .catalogue("create_agent_session", "documents", "agent_session", true) + .caller(domain::caller_need::subject) + .body() + .input() + .response() + .tool_call([h](const domain::caller& c, std::string_view arguments) { + return net::call_tool(c, arguments, h); + }) + .handler([h](const domain::http_request& req) { + return net::ready(net::answer(req, domain::caller_need::subject, + [&](const domain::caller& c) { return h(c, bind_create_agent_session(req)); })); + }) + .build()); +} + +namespace { + +compass::http::messages::list_agent_sessions_request bind_list_agent_sessions(const domain::http_request& req) { + net::binding b(req); + compass::http::messages::list_agent_sessions_request r; + b.path("environment", r.environment); + b.query("limit", r.limit, false); + b.query("offset", r.offset, false); + b.finish(); + return r; +} + +} + +void add_list_agent_sessions(net::router& r, list_agent_sessions_handler h) { + r.add_route(r.get("/v1/{environment}/agent/sessions") + .summary("List the caller's conversations with the compass agent") + .description("The caller's conversations in an environment and view, most recently changed first.") + .catalogue("list_agent_sessions", "documents", "agent_session", false) + .caller(domain::caller_need::subject) + .query_param("limit", "integer", "", false, "At most 100.") + .query_param("offset", "integer", "", false, "") + .input() + .response() + .tool_call([h](const domain::caller& c, std::string_view arguments) { + return net::call_tool(c, arguments, h); + }) + .handler([h](const domain::http_request& req) { + return net::ready(net::answer(req, domain::caller_need::subject, + [&](const domain::caller& c) { return h(c, bind_list_agent_sessions(req)); })); + }) + .build()); +} + +namespace { + +compass::http::messages::get_agent_session_request bind_get_agent_session(const domain::http_request& req) { + net::binding b(req); + compass::http::messages::get_agent_session_request r; + b.path("environment", r.environment); + b.path("session", r.session); + b.finish(); + return r; +} + +} + +void add_get_agent_session(net::router& r, get_agent_session_handler h) { + r.add_route(r.get("/v1/{environment}/agent/sessions/{session}") + .summary("Read a conversation with the compass agent") + .description("A conversation and its turns, oldest first, as they were stored: the retrieval event, the answer, and the done or failure event the stream sent. A conversation of another subject or view answers as absent.") + .catalogue("get_agent_session", "documents", "agent_session", false) + .caller(domain::caller_need::subject) + .input() + .response() + .tool_call([h](const domain::caller& c, std::string_view arguments) { + return net::call_tool(c, arguments, h); + }) + .handler([h](const domain::http_request& req) { + return net::ready(net::answer(req, domain::caller_need::subject, + [&](const domain::caller& c) { return h(c, bind_get_agent_session(req)); })); + }) + .build()); +} + +namespace { + +compass::http::messages::delete_agent_session_request bind_delete_agent_session(const domain::http_request& req) { + net::binding b(req); + compass::http::messages::delete_agent_session_request r; + b.path("environment", r.environment); + b.path("session", r.session); + b.finish(); + return r; +} + +} + +void add_delete_agent_session(net::router& r, delete_agent_session_handler h) { + r.add_route(r.delete_("/v1/{environment}/agent/sessions/{session}") + .summary("Delete a conversation with the compass agent") + .description("Deletes a conversation and its turns. A conversation of another subject or view is not deleted, and answers as absent.") + .catalogue("delete_agent_session", "documents", "agent_session", true) + .destructive() + .idempotent() + .caller(domain::caller_need::subject) + .no_body() + .input() + .tool_call([h](const domain::caller& c, std::string_view arguments) { + return net::call_tool(c, arguments, h); + }) + .handler([h](const domain::http_request& req) { + return net::ready(net::answer(req, domain::caller_need::subject, + [&](const domain::caller& c) { return h(c, bind_delete_agent_session(req)); })); + }) + .build()); +} + +namespace { + +compass::http::messages::agent_session_ask_request bind_ask_agent_session(const domain::http_request& req) { + net::binding b(req); + compass::http::messages::agent_session_ask_request r; + b.body(r); + b.path("environment", r.environment); + b.path("session", r.session); + b.finish(); + return r; +} + +} + +void add_ask_agent_session(net::router& r, ask_agent_session_handler h) { + r.add_route(r.post("/v1/{environment}/agent/sessions/{session}/ask") + .summary("Ask the compass agent in a conversation") + .description("Asks a question in a conversation and answers it as the stateless route does, as server-sent events. The question is written as a streaming turn before the stream opens; the answer is written by the stream's terminal sink, off the connection's thread. A conversation of another subject or view answers as absent, and no stream opens.") + .catalogue("ask_agent_session", "documents", "agent_session", true) + .caller(domain::caller_need::subject) + .body() + .input() + .no_tool() + .stream() + .handler([h](const domain::http_request& req) { + return net::ready(net::answer(req, domain::caller_need::subject, + [&](const domain::caller& c) { return h(c, bind_ask_agent_session(req)); })); + }) + .build()); +} + +} diff --git a/projects/compass.http/tests/CMakeLists.txt b/projects/compass.http/tests/CMakeLists.txt index 9249189c..22dd26f9 100644 --- a/projects/compass.http/tests/CMakeLists.txt +++ b/projects/compass.http/tests/CMakeLists.txt @@ -26,6 +26,7 @@ add_executable(${tests_target_name} mcp_conformance_tests.cpp mcp_endpoint_tests.cpp messages_agent_protocol_tests.cpp + messages_agent_sessions_protocol_tests.cpp messages_campaign_writes_protocol_tests.cpp messages_codec_tests.cpp messages_document_queries_protocol_tests.cpp @@ -34,7 +35,9 @@ add_executable(${tests_target_name} openapi_document_tests.cpp ops_agent_tests.cpp query_reads_tests.cpp + query_sessions_tests.cpp query_writes_tests.cpp + turn_writer_tests.cpp web_bundle_tests.cpp) target_link_libraries(${tests_target_name} diff --git a/projects/compass.http/tests/agent_llama_tests.cpp b/projects/compass.http/tests/agent_llama_tests.cpp index 1aa98e60..508542f9 100644 --- a/projects/compass.http/tests/agent_llama_tests.cpp +++ b/projects/compass.http/tests/agent_llama_tests.cpp @@ -75,20 +75,41 @@ ops::agent_retrieval one_passage() { return r; } +messages::agent_passages_event event_of(const ops::agent_retrieval& found, + std::uint32_t retrieval_ms) { + return ops::agent_passages_event_of(found, retrieval_ms); +} + std::uint16_t closed_port() { asio::io_context io; tcp::acceptor a(io, tcp::endpoint(asio::ip::make_address("127.0.0.1"), 0)); return a.local_endpoint().port(); } +/// A sink that keeps what the stream records, for a test to inspect. +struct recording_sink final : agent::turn_sink { + void record(agent::turn_record r) noexcept override { + const std::lock_guard lock(mutex); + terminals.push_back(std::move(r)); + } + void record_partial(std::int64_t turn, std::string answer) noexcept override { + const std::lock_guard lock(mutex); + partials.emplace_back(turn, std::move(answer)); + } + std::mutex mutex; + std::vector terminals; + std::vector> partials; +}; + } TEST_CASE("the agent streams the passages, the model's answer a piece at a time, then " "the citations, dropping a number no passage had", "[agent][llama]") { llama_stub stub(llama_stub::mode::ready, {"The log records", " the weather [1]", " and [7]."}); - agent::answer_stream s(stub.settings(), one_passage(), "What does the keeper's log record?", - 3, std::chrono::steady_clock::now()); + agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 3), + "What does the keeper's log record?", + std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 5); CHECK(events[0].name == "passages"); @@ -120,7 +141,7 @@ TEST_CASE("with no passages the agent still asks the model, which is told no doc "[agent][llama]") { llama_stub stub(llama_stub::mode::ready, {"No compass document matched your question", " [1]."}); - agent::answer_stream s(stub.settings(), {}, "how do i build qwen", 1, + agent::answer_stream s(stub.settings(), {}, event_of({}, 1), "how do i build qwen", std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 4); @@ -138,7 +159,8 @@ TEST_CASE("with no passages the agent still asks the model, which is told no doc TEST_CASE("the agent says llama-server is not running, and how to start it", "[agent][llama]") { types::agent_settings nobody; nobody.port = closed_port(); - agent::answer_stream s(nobody, one_passage(), "q", 0, std::chrono::steady_clock::now()); + agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now()); const auto events = drain(s, 4096); REQUIRE(events.size() == 2); CHECK(events[1].name == "failure"); @@ -153,7 +175,7 @@ TEST_CASE("the agent says llama-server is not running, and how to start it", "[a TEST_CASE("the agent tells a model still loading from one that answers", "[agent][llama]") { llama_stub loading(llama_stub::mode::loading); - agent::answer_stream s(loading.settings(), one_passage(), "q", 0, + agent::answer_stream s(loading.settings(), one_passage(), event_of(one_passage(), 0), "q", std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 2); @@ -174,7 +196,7 @@ TEST_CASE("a comment keeps the stream open while the model is silent, and the an llama_stub stub(llama_stub::mode::slow, {"The log", " records", " the weather [1]."}); agent::answer_options o; o.heartbeat = 40ms; - agent::answer_stream s(stub.settings(), one_passage(), "q", 0, + agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 0), "q", std::chrono::steady_clock::now(), o); const auto events = drain(s); std::string answer; @@ -198,8 +220,9 @@ TEST_CASE("a stream dropped while the model answers ends the model's work", "[agent][llama]") { llama_stub stub(llama_stub::mode::slow, std::vector(12, "word ")); asio::io_context io; - auto s = std::make_unique(stub.settings(), one_passage(), "q", 0, - std::chrono::steady_clock::now()); + auto s = std::make_unique( + stub.settings(), one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now()); std::size_t taken = 0; asio::co_spawn( io, @@ -221,7 +244,7 @@ TEST_CASE("a stream dropped while the model answers ends the model's work", TEST_CASE("the agent reads no more of llama-server's error or line than its limit", "[agent][llama]") { llama_stub huge(llama_stub::mode::huge_error); - agent::answer_stream refused(huge.settings(), one_passage(), "q", 0, + agent::answer_stream refused(huge.settings(), one_passage(), event_of(one_passage(), 0), "q", std::chrono::steady_clock::now()); const auto error = drain(refused, 4096); REQUIRE(error.size() == 2); @@ -229,8 +252,8 @@ TEST_CASE("the agent reads no more of llama-server's error or line than its limi "reads")); llama_stub endless(llama_stub::mode::endless_line); - agent::answer_stream unending(endless.settings(), one_passage(), "q", 0, - std::chrono::steady_clock::now()); + agent::answer_stream unending(endless.settings(), one_passage(), event_of(one_passage(), 0), + "q", std::chrono::steady_clock::now()); const auto line = drain(unending, 4096); REQUIRE(line.size() == 2); CHECK_THAT(line[1].data, ContainsSubstring(R"("code":"failing")")); @@ -243,7 +266,8 @@ TEST_CASE("a failure names llama-server's address and command only when asked to nobody.port = closed_port(); agent::answer_options o; o.names_server = false; - agent::answer_stream s(nobody, one_passage(), "q", 0, std::chrono::steady_clock::now(), o); + agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now(), o); const auto events = drain(s, 4096); REQUIRE(events.size() == 2); CHECK(events[1].data == @@ -521,3 +545,105 @@ TEST_CASE("clients that close just as the stream's next piece arrives leave the bhttp::read_some(socket, buffer, parser); CHECK(parser.get().body().starts_with("...")); } + +TEST_CASE("a session stream records one done turn with the answer and the event it sent", + "[agent][llama][sink]") { + llama_stub stub(llama_stub::mode::ready, {"The log records", " the weather [1]."}); + auto sink = std::make_shared(); + agent::answer_options o; + o.turn = 7; + o.sink = sink; + agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 3), "q", + std::chrono::steady_clock::now(), o); + static_cast(drain(s)); + + REQUIRE(sink->terminals.size() == 1); + const auto& r = sink->terminals.front(); + CHECK(r.turn == 7); + CHECK(r.end == agent::turn_end::done); + CHECK(r.answer == "The log records the weather [1]."); + REQUIRE(r.done); + CHECK(r.done->cited == std::vector{1}); + CHECK(r.done->total_ms > 0); + CHECK_FALSE(r.failure); +} + +TEST_CASE("a session stream records its failure, and any partial answer with it", + "[agent][llama][sink]") { + types::agent_settings nobody; + nobody.port = closed_port(); + auto sink = std::make_shared(); + agent::answer_options o; + o.turn = 9; + o.sink = sink; + agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now(), o); + static_cast(drain(s, 4096)); + + REQUIRE(sink->terminals.size() == 1); + const auto& r = sink->terminals.front(); + CHECK(r.turn == 9); + CHECK(r.end == agent::turn_end::failed); + REQUIRE(r.failure); + CHECK(r.failure->code == messages::agent_health::not_running); + CHECK(r.answer.empty()); +} + +TEST_CASE("a stream destroyed while answering records stopped with the partial text", + "[agent][llama][sink]") { + llama_stub stub(llama_stub::mode::slow, std::vector(24, "word ")); + auto sink = std::make_shared(); + agent::answer_options o; + o.turn = 11; + o.sink = sink; + o.partial_every = 10ms; + asio::io_context io; + auto s = std::make_unique( + stub.settings(), one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now(), o); + std::size_t taken = 0; + asio::co_spawn( + io, + [&]() -> asio::awaitable { + std::vector buffer(4096); + taken = co_await s->read(std::span(buffer)); + }, + asio::detached); + io.run_for(400ms); + CHECK(taken > 0); + s.reset(); + io.run(); + + const auto waited = std::chrono::steady_clock::now(); + while (sink->terminals.empty() && std::chrono::steady_clock::now() - waited < 5s) + std::this_thread::sleep_for(10ms); + REQUIRE(sink->terminals.size() == 1); + const auto& r = sink->terminals.front(); + CHECK(r.turn == 11); + CHECK(r.end == agent::turn_end::stopped); + CHECK_FALSE(r.answer.empty()); + CHECK_FALSE(r.done); + CHECK_FALSE(r.failure); +} + +TEST_CASE("a growing answer is snapshotted while it streams", "[agent][llama][sink]") { + llama_stub stub(llama_stub::mode::slow, std::vector(24, "word ")); + auto sink = std::make_shared(); + agent::answer_options o; + o.turn = 12; + o.sink = sink; + o.partial_every = 10ms; + agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 0), "q", + std::chrono::steady_clock::now(), o); + static_cast(drain(s, 4096)); + + REQUIRE_FALSE(sink->partials.empty()); + REQUIRE(sink->terminals.size() == 1); + const auto& done = sink->terminals.front(); + CHECK(done.end == agent::turn_end::done); + for (const auto& [turn, answer] : sink->partials) { + CHECK(turn == 12); + CHECK_FALSE(answer.empty()); + CHECK(done.answer.starts_with(answer)); + } +} diff --git a/projects/compass.http/tests/app_service_tests.cpp b/projects/compass.http/tests/app_service_tests.cpp index e354de11..9a43185b 100644 --- a/projects/compass.http/tests/app_service_tests.cpp +++ b/projects/compass.http/tests/app_service_tests.cpp @@ -70,9 +70,24 @@ TEST_CASE("the router's start-up gates accept every read route", "[serve][app]") "get_version", "get_sprint_state", "get_sprint_charts", "list_scenarios_to_test", "get_work_item", "list_backlog", "get_run", "list_notes", - "get_attachment", "get_scenario", "get_catalogue"}) + "get_attachment", "get_scenario", "get_catalogue", + "list_agent_sessions", "get_agent_session"}) CHECK_THAT(catalogue, ContainsSubstring(std::string("\"tool\":\"") + tool + "\"")); - CHECK(r.routes().size() == 19); + CHECK(r.routes().size() == 21); +} + +TEST_CASE("a streamed session ask is catalogued as a stream and no tool", "[serve][app]") { + net::router r; + app::service s(settings(), unreachable_pool()); + s.add_agent_routes(r); + CHECK(r.uncatalogued().empty()); + const auto catalogue = app::catalogue_json(r); + CHECK_THAT(catalogue, ContainsSubstring("\"tool\":\"ask_agent_session\"")); + CHECK_THAT(catalogue, ContainsSubstring("\"stream\":true")); + CHECK_THAT(catalogue, ContainsSubstring("\"answers_no_tool\":true")); + CHECK_THAT(catalogue, ContainsSubstring("\"method\":\"POST\"")); + CHECK_THAT(catalogue, ContainsSubstring("\"path\":\"/v1/{environment}/agent/sessions/" + "{session}/ask\"")); } TEST_CASE("a request is admitted only with a view the service serves and " diff --git a/projects/compass.http/tests/messages_agent_sessions_protocol_tests.cpp b/projects/compass.http/tests/messages_agent_sessions_protocol_tests.cpp new file mode 100644 index 00000000..08fc024f --- /dev/null +++ b/projects/compass.http/tests/messages_agent_sessions_protocol_tests.cpp @@ -0,0 +1,506 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +/** + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_cpp_protocol_tests.cpp.mustache + * To modify, update the template and regenerate. + */ +#include "compass.http/messages/agent_sessions_protocol.hpp" + +#include +#include +#include +#include +#include +#include +#include "compass.db/codec/json_schema.hpp" +#include "compass.db/codec/member_count.hpp" +#include "compass.db/codec/sample.hpp" +#include "compass.db/codec/schema_check.hpp" + +static_assert(compass::db::codec::names_every_member(), + "create_agent_session_request has a member its wire shape does not name"); + +TEST_CASE("create_agent_session_request reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::create_agent_session_request empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("create_agent_session_request's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +TEST_CASE("create_agent_session_request's route reads its body fields from a body its body " + "schema allows, and no other member", "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = traits::body_json_schema(); + const auto v = compass::db::codec::sample(0); + const auto full = traits::write_json(v); + const std::vector body_names{ "title", }; + const auto body = compass::db::codec::only_members(full, body_names); + INFO(body); + CHECK(compass::db::codec::schema_violation(schema, body).value_or("") == ""); + const auto read = traits::read_body_json(body); + CHECK(read.title == v.title); + auto with_environment = body_names; + with_environment.push_back("environment"); + CHECK_THROWS_AS(traits::read_body_json(compass::db::codec::only_members(full, with_environment)), + std::invalid_argument); +} + +static_assert(compass::db::codec::names_every_member(), + "create_agent_session_response has a member its wire shape does not name"); + +TEST_CASE("create_agent_session_response reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::create_agent_session_response empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("create_agent_session_response's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "list_agent_sessions_request has a member its wire shape does not name"); + +TEST_CASE("list_agent_sessions_request reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::list_agent_sessions_request empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("list_agent_sessions_request's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "agent_session_summary has a member its wire shape does not name"); + +TEST_CASE("agent_session_summary reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::agent_session_summary empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_session_summary's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "list_agent_sessions_response has a member its wire shape does not name"); + +TEST_CASE("list_agent_sessions_response reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::list_agent_sessions_response empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("list_agent_sessions_response's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "get_agent_session_request has a member its wire shape does not name"); + +TEST_CASE("get_agent_session_request reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::get_agent_session_request empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("get_agent_session_request's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "agent_turn has a member its wire shape does not name"); + +TEST_CASE("agent_turn reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::agent_turn empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_turn's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "get_agent_session_response has a member its wire shape does not name"); + +TEST_CASE("get_agent_session_response reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::get_agent_session_response empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("get_agent_session_response's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "delete_agent_session_request has a member its wire shape does not name"); + +TEST_CASE("delete_agent_session_request reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::delete_agent_session_request empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("delete_agent_session_request's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +static_assert(compass::db::codec::names_every_member(), + "agent_session_ask_request has a member its wire shape does not name"); + +TEST_CASE("agent_session_ask_request reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::agent_session_ask_request empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_session_ask_request's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + +TEST_CASE("agent_session_ask_request's route reads its body fields from a body its body " + "schema allows, and no other member", "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = traits::body_json_schema(); + const auto v = compass::db::codec::sample(0); + const auto full = traits::write_json(v); + const std::vector body_names{ "q", }; + const auto body = compass::db::codec::only_members(full, body_names); + INFO(body); + CHECK(compass::db::codec::schema_violation(schema, body).value_or("") == ""); + const auto read = traits::read_body_json(body); + CHECK(read.q == v.q); + auto with_environment = body_names; + with_environment.push_back("environment"); + CHECK_THROWS_AS(traits::read_body_json(compass::db::codec::only_members(full, with_environment)), + std::invalid_argument); + auto with_session = body_names; + with_session.push_back("session"); + CHECK_THROWS_AS(traits::read_body_json(compass::db::codec::only_members(full, with_session)), + std::invalid_argument); +} diff --git a/projects/compass.http/tests/query_sessions_tests.cpp b/projects/compass.http/tests/query_sessions_tests.cpp new file mode 100644 index 00000000..4bca1bbd --- /dev/null +++ b/projects/compass.http/tests/query_sessions_tests.cpp @@ -0,0 +1,348 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.http/query/sessions.hpp" + +#include +#include +#include +#include +#include +#include "compass.db/codec/wire_traits_fwd.hpp" +#include "compass.db/io/corpus.hpp" +#include "compass.db/io/schema.hpp" +#include "compass.db/query/scope.hpp" +#include "compass.db/query/search.hpp" +#include "compass.http/query/writes.hpp" +#include "compass.testing/database/scoped_cluster.hpp" + +namespace { + +using namespace compass::http; +using Catch::Matchers::ContainsSubstring; +namespace db = compass::db; + +const domain::caller ana{"team", "ana", "mcp:test"}; +const domain::caller bob{"team", "bob", std::nullopt}; +const domain::caller reader{"public", "ana", std::nullopt}; + +std::string fresh() { + std::string why; + auto* cluster = compass::testing::database::shared_cluster("compass.http.tests", why); + if (cluster == nullptr) + SKIP(why); + auto conninfo = cluster->create_database(); + db::io::connection c(conninfo); + db::io::init(c, "english"); + for (const auto* name : {"main", "other"}) { + db::types::environment e; + e.name = name; + e.root = "/work/" + std::string(name); + db::io::write_environment(c, e, {}, {}); + } + return conninfo; +} + +messages::agent_passages_event passages(std::uint32_t retrieval_ms = 5) { + messages::agent_passages_event e; + e.queries = {"lighthouse keeper"}; + messages::agent_passage p; + p.number = 1; + p.org_id = "HELLO"; + p.title = "Hello"; + p.type = "knowledge"; + p.path = "doc/hello.org"; + p.heading_path = {"The log"}; + p.anchor = "the-log"; + p.kind = messages::hit_kind::knowledge; + e.passages.push_back(std::move(p)); + e.retrieval_ms = retrieval_ms; + return e; +} + +template +std::string json_of(const T& value) { + return db::codec::wire_traits::write_json(value); +} + +std::int64_t new_session(db::io::connection& c, const domain::caller& who, + std::optional title = std::nullopt, + const std::string& environment = "main") { + messages::create_agent_session_request r; + r.environment = environment; + r.title = std::move(title); + return query::create_agent_session(c, who, r).session; +} + +query::agent_begin_turn ask(db::io::connection& c, const domain::caller& who, + std::int64_t session, const std::string& question, + const std::string& environment = "main") { + return query::begin_agent_turn(c, who, environment, session, question, + json_of(passages()), "qwen.gguf"); +} + +agent::turn_record done_record(std::int64_t turn, std::string answer) { + agent::turn_record r; + r.turn = turn; + r.answer = std::move(answer); + r.end = agent::turn_end::done; + messages::agent_done_event d; + d.cited = {1}; + d.total_ms = 42; + d.finish_reason = "stop"; + r.done = d; + return r; +} + +} + +TEST_CASE("a session is created, listed, read and deleted within its triple", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + + const auto first = new_session(c, ana); + const auto titled = new_session(c, ana, " Given title "); + static_cast(query::begin_agent_turn(c, ana, "main", first, "How do I build?", + json_of(passages()), "qwen.gguf")); + query::finish_agent_turn(c, done_record(1, "With cmake [1].")); + + messages::list_agent_sessions_request list; + list.environment = "main"; + list.limit = 10; + const auto listed = query::list_agent_sessions(c, ana, list); + REQUIRE(listed.sessions.size() == 2); + CHECK(listed.sessions[0].session == first); + CHECK(listed.sessions[0].title == "How do I build?"); + CHECK(listed.sessions[0].turns == 1); + CHECK(listed.sessions[1].session == titled); + CHECK(listed.sessions[1].title == "Given title"); + CHECK(listed.sessions[1].turns == 0); + + messages::get_agent_session_request get; + get.environment = "main"; + get.session = first; + const auto read = query::get_agent_session(c, ana, get); + REQUIRE(read); + CHECK(read->session == first); + CHECK(read->environment == "main"); + CHECK(read->title == "How do I build?"); + REQUIRE(read->turns.size() == 1); + CHECK(read->turns[0].ord == 1); + CHECK(read->turns[0].question == "How do I build?"); + CHECK(read->turns[0].answer == "With cmake [1]."); + CHECK(read->turns[0].status == messages::agent_turn_status::done); + CHECK(read->turns[0].retrieval == passages()); + REQUIRE(read->turns[0].done); + CHECK(read->turns[0].done->cited == std::vector{1}); + CHECK_FALSE(read->turns[0].failure); + + messages::delete_agent_session_request del; + del.environment = "main"; + del.session = first; + query::delete_agent_session(c, ana, del); + CHECK_FALSE(query::get_agent_session(c, ana, get)); + CHECK(c.exec("SELECT count(*) FROM agent.agent_turn").value(0, 0) == "0"); + query::delete_agent_session(c, ana, del); +} + +TEST_CASE("a session of another subject, view or environment is absent", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + + messages::get_agent_session_request get; + get.environment = "main"; + get.session = session; + CHECK_FALSE(query::get_agent_session(c, bob, get)); + CHECK_FALSE(query::get_agent_session(c, reader, get)); + get.environment = "other"; + CHECK_FALSE(query::get_agent_session(c, ana, get)); + + messages::list_agent_sessions_request list; + list.environment = "main"; + CHECK(query::list_agent_sessions(c, bob, list).sessions.empty()); + CHECK(query::list_agent_sessions(c, reader, list).sessions.empty()); + + CHECK_THROWS_AS(ask(c, bob, session, "why?"), query::rejected_write); + messages::delete_agent_session_request del; + del.environment = "main"; + del.session = session; + CHECK_THROWS_AS(query::delete_agent_session(c, bob, del), query::rejected_write); + CHECK_THROWS_AS(query::delete_agent_session(c, reader, del), query::rejected_write); + get.environment = "main"; + CHECK(query::get_agent_session(c, ana, get).has_value()); + + messages::create_agent_session_request unknown; + unknown.environment = "nowhere"; + CHECK_THROWS_AS(query::create_agent_session(c, ana, unknown), db::query::unknown_environment); + CHECK_THROWS_AS(query::create_agent_session(c, domain::caller{"team", " ", {}}, unknown), + query::rejected_write); +} + +TEST_CASE("an ask takes the next ord under the session's lock and stores its event", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + + const auto first = ask(c, ana, session, "First?"); + const auto second = ask(c, ana, session, "Second?"); + CHECK(first.ord == 1); + CHECK(second.ord == 2); + CHECK(first.turn != second.turn); + + const auto stored = c.exec( + "SELECT question, status, retrieval::text, model, actor, ord\n" + "FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(first.turn)}); + REQUIRE(stored.rows() == 1); + CHECK(stored.value(0, 0) == "First?"); + CHECK(stored.value(0, 1) == "streaming"); + CHECK(db::codec::wire_traits::read_json( + stored.value(0, 2)) == passages()); + CHECK(stored.value(0, 3) == "qwen.gguf"); + CHECK(stored.value(0, 4) == "mcp:test"); + CHECK(stored.value(0, 5) == "1"); + + const auto titled = query::load_agent_session(c, ana, "main", session, 8); + REQUIRE(titled); + CHECK(titled->title == "First?"); + CHECK(titled->last_question == "Second?"); + CHECK(titled->history.empty()); +} + +TEST_CASE("a partial answer is visible while streaming, and the terminal record wins", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + const auto began = ask(c, ana, session, "Q?"); + + query::save_agent_partial(c, began.turn, "Half"); + messages::get_agent_session_request get; + get.environment = "main"; + get.session = session; + auto read = query::get_agent_session(c, ana, get); + REQUIRE(read); + REQUIRE(read->turns.size() == 1); + CHECK(read->turns[0].status == messages::agent_turn_status::streaming); + CHECK(read->turns[0].answer == "Half"); + + query::finish_agent_turn(c, done_record(began.turn, "Whole [1].")); + query::save_agent_partial(c, began.turn, "late"); + query::finish_agent_turn(c, done_record(began.turn, "later")); + read = query::get_agent_session(c, ana, get); + REQUIRE(read); + CHECK(read->turns[0].status == messages::agent_turn_status::done); + CHECK(read->turns[0].answer == "Whole [1]."); + CHECK(read->turns[0].done->total_ms == 42); +} + +TEST_CASE("a turn settles as failed or stopped, and a server's failure is stored", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + const auto failing = ask(c, ana, session, "Q?"); + agent::turn_record failure; + failure.turn = failing.turn; + failure.answer = ""; + failure.end = agent::turn_end::failed; + messages::agent_failure_event e; + e.code = messages::agent_health::not_running; + e.message = "not running"; + failure.failure = e; + query::finish_agent_turn(c, failure); + + const auto stopped = ask(c, ana, session, "Q2?"); + agent::turn_record cut; + cut.turn = stopped.turn; + cut.answer = "Partial"; + cut.end = agent::turn_end::stopped; + query::finish_agent_turn(c, cut); + + messages::get_agent_session_request get; + get.environment = "main"; + get.session = session; + const auto read = query::get_agent_session(c, ana, get); + REQUIRE(read); + REQUIRE(read->turns.size() == 2); + CHECK(read->turns[0].status == messages::agent_turn_status::failed); + REQUIRE(read->turns[0].failure); + CHECK(read->turns[0].failure->code == messages::agent_health::not_running); + CHECK_FALSE(read->turns[0].done); + CHECK(read->turns[1].status == messages::agent_turn_status::stopped); + CHECK(read->turns[1].answer == "Partial"); + CHECK_FALSE(read->turns[1].done); + CHECK_FALSE(read->turns[1].failure); +} + +TEST_CASE("startup recovery cuts every turn left streaming", "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + ask(c, ana, session, "One?"); + ask(c, ana, session, "Two?"); + CHECK(query::recover_agent_turns(c) == 2); + CHECK(query::recover_agent_turns(c) == 0); + CHECK(c.exec("SELECT count(*) FROM agent.agent_turn WHERE status = 'cut'").value(0, 0) == + "2"); +} + +TEST_CASE("history holds only done exchanges, oldest first, and the last question", + "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + const auto one = ask(c, ana, session, "One?"); + query::finish_agent_turn(c, done_record(one.turn, "Answer one [1].")); + const auto two = ask(c, ana, session, "Two?"); + agent::turn_record stopped; + stopped.turn = two.turn; + stopped.answer = "half"; + stopped.end = agent::turn_end::stopped; + query::finish_agent_turn(c, stopped); + const auto three = ask(c, ana, session, "Three?"); + query::finish_agent_turn(c, done_record(three.turn, "Answer three [2].")); + + const auto state = query::load_agent_session(c, ana, "main", session, 8); + REQUIRE(state); + REQUIRE(state->history.size() == 2); + CHECK(state->history[0].question == "One?"); + CHECK(state->history[0].answer == "Answer one [1]."); + CHECK(state->history[1].question == "Three?"); + CHECK(state->history[1].answer == "Answer three [2]."); + CHECK(state->last_question == "Three?"); +} + +TEST_CASE("a stored event that is not the one compass wrote is an error", "[http][sessions]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto session = new_session(c, ana); + const auto began = ask(c, ana, session, "Q?"); + c.exec("UPDATE agent.agent_turn SET retrieval = '{\"wrong\":true}'::jsonb " + "WHERE id = $1::bigint", + {std::to_string(began.turn)}); + messages::get_agent_session_request get; + get.environment = "main"; + get.session = session; + CHECK_THROWS_AS(query::get_agent_session(c, ana, get), db::io::error); +} \ No newline at end of file diff --git a/projects/compass.http/tests/query_writes_tests.cpp b/projects/compass.http/tests/query_writes_tests.cpp index 8c445969..5fe09e2c 100644 --- a/projects/compass.http/tests/query_writes_tests.cpp +++ b/projects/compass.http/tests/query_writes_tests.cpp @@ -712,9 +712,10 @@ TEST_CASE("the router's start-up gates accept every write route", "[serve][write const auto catalogue = app::catalogue_json(w.router); for (const auto* tool : {"start_run", "record_step_result", "clear_step_result", "finish_run", "attach_screenshot", "add_note", "address_note", - "sync_environment"}) + "sync_environment", "create_agent_session", + "delete_agent_session"}) CHECK_THAT(catalogue, ContainsSubstring(std::string("\"tool\":\"") + tool + "\"")); - CHECK(w.router.routes().size() == 27); + CHECK(w.router.routes().size() == 31); } TEST_CASE("a sync of the served environment syncs it, so the next read sees it, and " @@ -790,7 +791,7 @@ TEST_CASE("sync_environment is the nineteenth MCP tool, and a call of it syncs a json_document::parse(post(R"({"jsonrpc":"2.0","id":2,"method":"tools/list"})", session).body); REQUIRE(listed); const auto tools = listed->root().member("result").member("tools").elements(); - CHECK(tools.size() == 27); + CHECK(tools.size() == 31); const auto sync = std::ranges::find_if(tools, [](const auto& t) { return t.member("name").text_or() == "sync_environment"; }); diff --git a/projects/compass.http/tests/turn_writer_tests.cpp b/projects/compass.http/tests/turn_writer_tests.cpp new file mode 100644 index 00000000..42a4764f --- /dev/null +++ b/projects/compass.http/tests/turn_writer_tests.cpp @@ -0,0 +1,169 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.http/agent/turn_writer.hpp" + +#include +#include +#include +#include +#include +#include "compass.db/codec/wire_traits_fwd.hpp" +#include "compass.db/io/corpus.hpp" +#include "compass.db/io/schema.hpp" +#include "compass.http/app/service.hpp" +#include "compass.http/query/sessions.hpp" +#include "compass.testing/database/scoped_cluster.hpp" + +namespace { + +using namespace compass::http; +using Catch::Matchers::ContainsSubstring; +namespace db = compass::db; + +const domain::caller ana{"team", "ana", std::nullopt}; + +std::string fresh() { + std::string why; + auto* cluster = compass::testing::database::shared_cluster("compass.http.tests", why); + if (cluster == nullptr) + SKIP(why); + auto conninfo = cluster->create_database(); + db::io::connection c(conninfo); + db::io::init(c, "english"); + db::types::environment e; + e.name = "main"; + e.root = "/work/main"; + db::io::write_environment(c, e, {}, {}); + return conninfo; +} + +messages::agent_passages_event passages() { + messages::agent_passages_event e; + e.queries = {"lighthouse"}; + e.retrieval_ms = 3; + return e; +} + +std::int64_t new_turn(db::io::connection& c, const std::string& question) { + messages::create_agent_session_request create; + create.environment = "main"; + const auto session = query::create_agent_session(c, ana, create).session; + return query::begin_agent_turn(c, ana, "main", session, question, + db::codec::wire_traits::write_json( + passages()), + "qwen.gguf") + .turn; +} + +agent::turn_record done_record(std::int64_t turn, std::string answer) { + agent::turn_record r; + r.turn = turn; + r.answer = std::move(answer); + r.end = agent::turn_end::done; + messages::agent_done_event d; + d.cited = {1}; + d.finish_reason = "stop"; + r.done = d; + return r; +} + +} + +TEST_CASE("the writer settles a turn through the pool and waits when asked to flush", + "[http][writer]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto turn = new_turn(c, "Q?"); + + app::connection_pool pool(conninfo); + agent::turn_writer writer(pool); + writer.record(done_record(turn, "Answer [1].")); + writer.flush(); + CHECK(writer.dropped() == 0); + + CHECK(c.exec("SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}) + .value(0, 0) == "done"); +} + +TEST_CASE("a partial settles while streaming, and the terminal record replaces it", + "[http][writer]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto turn = new_turn(c, "Q?"); + + app::connection_pool pool(conninfo); + agent::turn_writer writer(pool); + writer.record_partial(turn, "Half"); + writer.flush(); + const auto streaming = c.exec( + "SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}); + CHECK(streaming.value(0, 0) == "streaming"); + CHECK(streaming.value(0, 1) == "Half"); + + writer.record(done_record(turn, "Whole [1].")); + writer.flush(); + const auto done = c.exec( + "SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}); + CHECK(done.value(0, 0) == "done"); + CHECK(done.value(0, 1) == "Whole [1]."); +} + +TEST_CASE("the writer drains what it holds when it stops", "[http][writer]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto turn = new_turn(c, "Q?"); + { + app::connection_pool pool(conninfo); + agent::turn_writer writer(pool); + writer.record(done_record(turn, "Answer.")); + } + CHECK(c.exec("SELECT status FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}) + .value(0, 0) == "done"); +} + +TEST_CASE("a failed write leaves the turn streaming and logs no content", + "[http][writer]") { + const auto conninfo = fresh(); + db::io::connection c(conninfo); + const auto turn = new_turn(c, "Question no log should repeat?"); + + std::vector logged; + { + app::connection_pool unreachable("host=/nonexistent dbname=none"); + agent::turn_writer writer(unreachable, [&](std::string_view line) { + logged.emplace_back(line); + }); + writer.record(done_record(turn, "Answer no log should repeat [1].")); + writer.flush(); + } + CHECK(c.exec("SELECT status FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}) + .value(0, 0) == "streaming"); + REQUIRE_FALSE(logged.empty()); + for (const auto& line : logged) { + CHECK_THAT(line, ContainsSubstring("was not settled")); + CHECK_THAT(line, !ContainsSubstring("Question no log")); + CHECK_THAT(line, !ContainsSubstring("Answer no log")); + } +} \ No newline at end of file From 1f74047db16e3fa6679e9e1ee6db6ef518bb907b Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:28:07 +0000 Subject: [PATCH 04/24] [http] Feed the agent its settled history, and budget it against the context A session ask now loads the last eight done exchanges in the same snapshot as the session, neutralises their citations to [cited earlier], and keeps the newest whole exchanges inside the context-reserve byte budget, so the message list grows append-only for llama-server's prompt cache. A follow-up with no keywords searches with the previous question's, and with no current passages but a history the model is told to answer from the conversation. agent_settings.context_tokens is 65536 and start_command prints it. Co-Authored-By: Claude Code --- .../include/compass.http/agent/llama.hpp | 4 + .../include/compass.http/ops/agent.hpp | 66 ++++++++++-- .../include/compass.http/types/settings.hpp | 5 + projects/compass.http/src/agent/llama.cpp | 8 +- projects/compass.http/src/app/service.cpp | 28 +++-- projects/compass.http/src/ops/agent.cpp | 78 +++++++++++++- .../compass.http/tests/agent_llama_tests.cpp | 46 +++++--- .../compass.http/tests/ops_agent_tests.cpp | 101 ++++++++++++++++++ 8 files changed, 298 insertions(+), 38 deletions(-) diff --git a/projects/compass.http/include/compass.http/agent/llama.hpp b/projects/compass.http/include/compass.http/agent/llama.hpp index e0079fe7..5d122740 100644 --- a/projects/compass.http/include/compass.http/agent/llama.hpp +++ b/projects/compass.http/include/compass.http/agent/llama.hpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include "compass.http/agent/turn.hpp" @@ -103,10 +104,12 @@ class answer_stream final : public domain::awaitable_body_source { * @param passages the metadata event sent as the stream's first frame * and, on a session ask, stored with the turn: one object, so a restore * cannot drift from the stream. + * @param history the session's settled exchanges, oldest first. * @param asked when the question arrived, which the times count from. */ answer_stream(types::agent_settings server, ops::agent_retrieval found, messages::agent_passages_event passages, std::string question, + std::vector history, std::chrono::steady_clock::time_point asked, answer_options options = {}); ~answer_stream() override; @@ -127,6 +130,7 @@ class answer_stream final : public domain::awaitable_body_source { ops::agent_retrieval found_; messages::agent_passages_event passages_; std::string question_; + std::vector history_; std::chrono::steady_clock::time_point asked_; answer_options options_; bool started_ = false; diff --git a/projects/compass.http/include/compass.http/ops/agent.hpp b/projects/compass.http/include/compass.http/ops/agent.hpp index 9883b5e4..82c590df 100644 --- a/projects/compass.http/include/compass.http/ops/agent.hpp +++ b/projects/compass.http/include/compass.http/ops/agent.hpp @@ -20,6 +20,7 @@ #ifndef COMPASS_HTTP_OPS_AGENT_HPP #define COMPASS_HTTP_OPS_AGENT_HPP +#include #include #include #include @@ -88,9 +89,15 @@ agent_section(std::span sections, * of one keyword left out, then of two; the clauses' hits interleaved best * first; one passage per section, at most five. A question costs at most * twelve searches however long it is, shared evenly between its clauses. + * + * A follow-up such as "and why?" has no keywords of its own; its search + * then uses @p previous_question, the last question asked in the session, + * so it continues the topic rather than searching nothing. A question that + * has keywords searches with them alone. */ [[nodiscard]] agent_retrieval agent_retrieve(std::string_view question, const agent_search& search, - const agent_sections& sections); + const agent_sections& sections, + std::string_view previous_question = {}); /** * @brief The metadata-only =passages= event the stream sends and the session @@ -110,21 +117,66 @@ struct agent_exchange { friend bool operator==(const agent_exchange&, const agent_exchange&) = default; }; +/// One message of the chat the model answers. +struct agent_message { + std::string role; + std::string content; + + friend bool operator==(const agent_message&, const agent_message&) = default; +}; + +/** + * @brief @p answer with every citation group replaced by "[cited earlier]": + * a stored answer's numbers name the passages of its own exchange, which the + * current one does not give, so they must not count as citations of it. + * "[cited earlier]" itself is no citation the model can make. + */ +[[nodiscard]] std::string neutralise_citations(std::string_view answer); + +/** + * @brief The newest exchanges, oldest first, that fit the model's history: + * at most @p max_turns, and at most @p max_chars bytes of question and + * neutralised answer. An exchange that does not fit drops it and every + * older one; an answerless exchange is left out, since it gives the model + * nothing. The window keeps whole exchanges, never half of one. + */ +[[nodiscard]] std::vector agent_history_window( + std::span turns, std::size_t max_turns = 8, + std::size_t max_chars = 24000); + +/** + * @brief The bytes of history a context of @p context_tokens leaves after + * @p prompt_bytes of system and current user message, @p max_answer_tokens + * of answer and @p slack of headroom, at four bytes a token; at most the + * 24,000-byte ceiling. + */ +[[nodiscard]] std::size_t agent_history_budget(std::uint32_t context_tokens, + std::size_t prompt_bytes, + std::uint32_t max_answer_tokens = 400, + std::size_t slack = 1024); + /** * @brief The chat the model answers: the system prompt, which tells the * model what knowledge and work history are, or, when there are no - * passages, to tell the user no document matched; and the user's message, - * the numbered passages, each labelled, then the question. When every - * passage is work history, the message asks the answer to begin by saying - * so. + * passages, to tell the user no document matched; the session's prior + * exchanges, oldest first; and the user's message, the numbered passages, + * each labelled, then the question. When every passage is work history, the + * message asks the answer to begin by saying so. + * + * The messages are append-only across a session, so llama-server's prompt + * cache may reuse the shared prefix. A stored question is bare, without its + * passages, so reuse stops at the previous exchange rather than including + * the current one. */ struct agent_prompt { std::string system; + std::vector history; std::string user; }; -[[nodiscard]] agent_prompt agent_prompt_for(std::string_view question, - std::span passages); +[[nodiscard]] agent_prompt agent_prompt_for( + std::string_view question, std::span passages, + std::span history = {}); /** * @brief The body of llama-server's /v1/chat/completions request for diff --git a/projects/compass.http/include/compass.http/types/settings.hpp b/projects/compass.http/include/compass.http/types/settings.hpp index ed127c30..d849bd0f 100644 --- a/projects/compass.http/include/compass.http/types/settings.hpp +++ b/projects/compass.http/include/compass.http/types/settings.hpp @@ -45,6 +45,11 @@ struct agent_settings { std::string host = "127.0.0.1"; std::uint16_t port = 8081; std::string model = "~/.local/share/compass/models/Qwen2.5-7B-Instruct-Q4_K_M.gguf"; + /** + * The model's context window in tokens, as llama-server is started with + * it. The history budget keeps the prompt well inside it. + */ + std::uint32_t context_tokens = 65536; }; /** diff --git a/projects/compass.http/src/agent/llama.cpp b/projects/compass.http/src/agent/llama.cpp index 45f94072..a81ce3d6 100644 --- a/projects/compass.http/src/agent/llama.cpp +++ b/projects/compass.http/src/agent/llama.cpp @@ -152,7 +152,8 @@ asio::awaitable check(types::agent_settings s) std::string start_command(const types::agent_settings& s) { return "llama-server --model " + s.model + " --host " + s.host + " --port " + - std::to_string(s.port) + " --ctx-size 8192 --jinja --no-ui"; + std::to_string(s.port) + " --ctx-size " + std::to_string(s.context_tokens) + + " --jinja --no-ui"; } messages::agent_status_response status(const types::agent_settings& s) { @@ -248,11 +249,13 @@ struct answer_stream::exchange { answer_stream::answer_stream(types::agent_settings server, ops::agent_retrieval found, messages::agent_passages_event passages, std::string question, + std::vector history, std::chrono::steady_clock::time_point asked, answer_options options) : server_(std::move(server)) , found_(std::move(found)) , passages_(std::move(passages)) , question_(std::move(question)) + , history_(std::move(history)) , asked_(asked) , options_(std::move(options)) {} @@ -267,7 +270,8 @@ void answer_stream::start(const asio::any_io_executor& on) { out_ += ops::agent_event( "passages", db::codec::wire_traits::write_json(passages_)); exchange_ = std::make_shared( - on, server_, ops::agent_chat_body(ops::agent_prompt_for(question_, found_.passages)), + on, server_, + ops::agent_chat_body(ops::agent_prompt_for(question_, found_.passages, history_)), found_.passages.size(), asked_, options_.names_server, options_.turn, options_.sink, options_.partial_every); asio::co_spawn( diff --git a/projects/compass.http/src/app/service.cpp b/projects/compass.http/src/app/service.cpp index 49e7d4e9..259770bd 100644 --- a/projects/compass.http/src/app/service.cpp +++ b/projects/compass.http/src/app/service.cpp @@ -281,6 +281,7 @@ void service::add_agent_routes(net::router& r) { namespace m = messages; using db::io::connection; const auto open = std::make_shared>(0); + constexpr std::size_t history_turns = 8; const auto require_question = [](const std::string& text) { if (text.find_first_not_of(" \t\r\n") == std::string::npos) throw refusal::invalid("The question is empty."); @@ -289,7 +290,8 @@ void service::add_agent_routes(net::router& r) { std::to_string(max_question) + " characters."); }; const auto retrieve = [](connection& conn, const std::string& environment, - const db::types::view_filter& view, std::string_view question) { + const db::types::view_filter& view, std::string_view question, + std::string_view previous) { return ops::agent_retrieve( question, [&](const std::string& query) { @@ -301,7 +303,8 @@ void service::add_agent_routes(net::router& r) { }, [&](const db::types::search_hit& hit) { return db::query::sections(conn, view, environment, hit.path); - }); + }, + previous); }; routes::add_get_agent_answer(r, [this, open, require_question, retrieve]( @@ -315,7 +318,7 @@ void service::add_agent_routes(net::router& r) { auto found = refusing([&] { return pool_.read([&](connection& conn) { require_environment(conn, q.environment); - return retrieve(conn, q.environment, view, q.q); + return retrieve(conn, q.environment, view, q.q, {}); }); }); const auto retrieval_ms = static_cast( @@ -328,8 +331,8 @@ void service::add_agent_routes(net::router& r) { out.headers["Cache-Control"] = "no-cache"; out.headers["X-Accel-Buffering"] = "no"; out.body_awaitable = std::make_shared( - settings_.agent, std::move(found), std::move(passages), q.q, asked, - std::move(options)); + settings_.agent, std::move(found), std::move(passages), q.q, std::vector{}, + asked, std::move(options)); return out; }); routes::add_ask_agent_session(r, [this, open, require_question, retrieve]( @@ -341,14 +344,19 @@ void service::add_agent_routes(net::router& r) { options.slot = take_stream_slot(open); const auto asked = std::chrono::steady_clock::now(); const auto& view = view_of(c); + std::vector history; auto found = refusing([&] { return pool_.read([&](connection& conn) { require_environment(conn, q.environment); - if (!query::load_agent_session(conn, c, q.environment, q.session, 0)) + auto state = query::load_agent_session(conn, c, q.environment, q.session, + history_turns); + if (!state) throw refusal::not_found("The caller has no conversation " + std::to_string(q.session) + " in the environment " + q.environment + "."); - return retrieve(conn, q.environment, view, q.q); + auto found = retrieve(conn, q.environment, view, q.q, state->last_question); + history = std::move(state->history); + return found; }); }); const auto retrieval_ms = static_cast( @@ -364,6 +372,10 @@ void service::add_agent_routes(net::router& r) { retrieval_json, settings_.agent.model); }); }); + const auto current = ops::agent_prompt_for(q.q, found.passages); + const auto budget = ops::agent_history_budget( + settings_.agent.context_tokens, current.system.size() + current.user.size()); + auto window = ops::agent_history_window(history, history_turns, budget); options.turn = begun.turn; options.sink = writer_; domain::http_response out; @@ -371,7 +383,7 @@ void service::add_agent_routes(net::router& r) { out.headers["Cache-Control"] = "no-cache"; out.headers["X-Accel-Buffering"] = "no"; out.body_awaitable = std::make_shared( - settings_.agent, std::move(found), std::move(passages), q.q, asked, + settings_.agent, std::move(found), std::move(passages), q.q, std::move(window), asked, std::move(options)); return out; }); diff --git a/projects/compass.http/src/ops/agent.cpp b/projects/compass.http/src/ops/agent.cpp index d346d8ac..e48a2e02 100644 --- a/projects/compass.http/src/ops/agent.cpp +++ b/projects/compass.http/src/ops/agent.cpp @@ -70,6 +70,13 @@ constexpr std::string_view no_match_rules = "sentences, that no compass document matched their question, and suggest asking with " "other words. Do not answer the question from your own knowledge and cite nothing."; +constexpr std::string_view no_match_history_rules = + "You answer questions about the compass repository's documents. compass searched its " + "documents for the user's question and no document matched. If the conversation above " + "already answers the question, answer it from the conversation and cite nothing; " + "otherwise tell the user, in one or two sentences, that no compass document matched " + "and suggest asking with other words. Do not answer from your own knowledge."; + std::string lower(std::string_view text) { std::string out(text); std::ranges::transform(out, out.begin(), [](unsigned char c) { return std::tolower(c); }); @@ -202,10 +209,15 @@ std::optional agent_section(std::span } agent_retrieval agent_retrieve(std::string_view question, const agent_search& search, - const agent_sections& sections) { + const agent_sections& sections, + std::string_view previous_question) { agent_retrieval out; std::vector> ranked; - const auto clauses = agent_clauses(question); + auto searched = std::string(question); + if (agent_keywords(searched).empty() && + !agent_keywords(previous_question).empty()) + searched = std::string(previous_question); + const auto clauses = agent_clauses(searched); for (const auto& clause : clauses) ranked.push_back( search_relaxed(clause, search, max_queries / clauses.size(), out.queries)); @@ -258,10 +270,60 @@ messages::agent_passages_event agent_passages_event_of(const agent_retrieval& fo return out; } +std::string neutralise_citations(std::string_view answer) { + static const std::regex group(R"(\[(\d+(?:\s*,\s*\d+)*)\])"); + return std::regex_replace(std::string(answer), group, "[cited earlier]"); +} + +std::vector agent_history_window(std::span turns, + std::size_t max_turns, + std::size_t max_chars) { + std::vector out; + std::size_t bytes = 0; + for (auto it = turns.rbegin(); it != turns.rend() && out.size() < max_turns; ++it) { + const auto answer = neutralise_citations(it->answer); + if (answer.empty()) + continue; + const auto size = it->question.size() + answer.size(); + if (out.empty() ? size > max_chars : bytes + size > max_chars) + break; + out.push_back({it->question, answer}); + bytes += size; + } + std::ranges::reverse(out); + return out; +} + +std::size_t agent_history_budget(std::uint32_t context_tokens, std::size_t prompt_bytes, + std::uint32_t max_answer_tokens, std::size_t slack) { + constexpr std::size_t bytes_per_token = 4; + constexpr std::size_t ceiling = 24000; + if (context_tokens <= max_answer_tokens) + return 0; + const auto room = + static_cast(context_tokens - max_answer_tokens) * bytes_per_token; + if (room <= prompt_bytes + slack) + return 0; + return std::min(ceiling, room - prompt_bytes - slack); +} + agent_prompt agent_prompt_for(std::string_view question, - std::span passages) { + std::span passages, + std::span history) { + agent_prompt out; if (passages.empty()) - return {std::string(no_match_rules), "Question: " + std::string(question)}; + out.system = history.empty() ? std::string(no_match_rules) + : std::string(no_match_history_rules); + else + out.system = knowledge_rules; + for (const auto& e : history) { + out.history.push_back({"user", e.question}); + out.history.push_back({"assistant", neutralise_citations(e.answer)}); + } + if (passages.empty()) { + out.user = "Question: " + std::string(question); + return out; + } std::string user = "Passages:\n\n"; for (const auto& p : passages) user += "[" + std::to_string(p.given.number) + "] " + label(p.given) + "\n" + p.text + @@ -273,7 +335,8 @@ agent_prompt agent_prompt_for(std::string_view question, user += "Every passage is work history, so begin your answer with \"From the work " "history:\".\n\n"; user += "Question: " + std::string(question); - return {std::string(knowledge_rules), std::move(user)}; + out.user = std::move(user); + return out; } std::string agent_chat_body(const agent_prompt& prompt) { @@ -283,6 +346,11 @@ std::string agent_chat_body(const agent_prompt& prompt) { auto system = messages.push_object(); system.set("role", "system"); system.set("content", prompt.system); + for (const auto& m : prompt.history) { + auto message = messages.push_object(); + message.set("role", m.role); + message.set("content", m.content); + } auto user = messages.push_object(); user.set("role", "user"); user.set("content", prompt.user); diff --git a/projects/compass.http/tests/agent_llama_tests.cpp b/projects/compass.http/tests/agent_llama_tests.cpp index 508542f9..cc270e6b 100644 --- a/projects/compass.http/tests/agent_llama_tests.cpp +++ b/projects/compass.http/tests/agent_llama_tests.cpp @@ -107,8 +107,9 @@ TEST_CASE("the agent streams the passages, the model's answer a piece at a time, "the citations, dropping a number no passage had", "[agent][llama]") { llama_stub stub(llama_stub::mode::ready, {"The log records", " the weather [1]", " and [7]."}); - agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 3), - "What does the keeper's log record?", + const auto found = one_passage(); + agent::answer_stream s(stub.settings(), found, event_of(found, 3), + "What does the keeper's log record?", {}, std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 5); @@ -141,7 +142,7 @@ TEST_CASE("with no passages the agent still asks the model, which is told no doc "[agent][llama]") { llama_stub stub(llama_stub::mode::ready, {"No compass document matched your question", " [1]."}); - agent::answer_stream s(stub.settings(), {}, event_of({}, 1), "how do i build qwen", + agent::answer_stream s(stub.settings(), {}, event_of({}, 1), "how do i build qwen", {}, std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 4); @@ -159,7 +160,7 @@ TEST_CASE("with no passages the agent still asks the model, which is told no doc TEST_CASE("the agent says llama-server is not running, and how to start it", "[agent][llama]") { types::agent_settings nobody; nobody.port = closed_port(); - agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", + agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", {}, std::chrono::steady_clock::now()); const auto events = drain(s, 4096); REQUIRE(events.size() == 2); @@ -171,12 +172,13 @@ TEST_CASE("the agent says llama-server is not running, and how to start it", "[a CHECK(status.health == messages::agent_health::not_running); CHECK(status.model == "Qwen2.5-7B-Instruct-Q4_K_M.gguf"); CHECK_THAT(status.start, ContainsSubstring("--port " + std::to_string(nobody.port))); + CHECK_THAT(status.start, ContainsSubstring("--ctx-size 65536")); } TEST_CASE("the agent tells a model still loading from one that answers", "[agent][llama]") { llama_stub loading(llama_stub::mode::loading); agent::answer_stream s(loading.settings(), one_passage(), event_of(one_passage(), 0), "q", - std::chrono::steady_clock::now()); + {}, std::chrono::steady_clock::now()); const auto events = drain(s); REQUIRE(events.size() == 2); CHECK_THAT(events[1].data, ContainsSubstring(R"("code":"loading")")); @@ -196,7 +198,7 @@ TEST_CASE("a comment keeps the stream open while the model is silent, and the an llama_stub stub(llama_stub::mode::slow, {"The log", " records", " the weather [1]."}); agent::answer_options o; o.heartbeat = 40ms; - agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 0), "q", + agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 0), "q", {}, std::chrono::steady_clock::now(), o); const auto events = drain(s); std::string answer; @@ -222,7 +224,7 @@ TEST_CASE("a stream dropped while the model answers ends the model's work", asio::io_context io; auto s = std::make_unique( stub.settings(), one_passage(), event_of(one_passage(), 0), "q", - std::chrono::steady_clock::now()); + std::vector{}, std::chrono::steady_clock::now()); std::size_t taken = 0; asio::co_spawn( io, @@ -245,7 +247,7 @@ TEST_CASE("the agent reads no more of llama-server's error or line than its limi "[agent][llama]") { llama_stub huge(llama_stub::mode::huge_error); agent::answer_stream refused(huge.settings(), one_passage(), event_of(one_passage(), 0), "q", - std::chrono::steady_clock::now()); + {}, std::chrono::steady_clock::now()); const auto error = drain(refused, 4096); REQUIRE(error.size() == 2); CHECK_THAT(error[1].data, ContainsSubstring("answered 500: an error longer than compass " @@ -253,7 +255,7 @@ TEST_CASE("the agent reads no more of llama-server's error or line than its limi llama_stub endless(llama_stub::mode::endless_line); agent::answer_stream unending(endless.settings(), one_passage(), event_of(one_passage(), 0), - "q", std::chrono::steady_clock::now()); + "q", {}, std::chrono::steady_clock::now()); const auto line = drain(unending, 4096); REQUIRE(line.size() == 2); CHECK_THAT(line[1].data, ContainsSubstring(R"("code":"failing")")); @@ -266,7 +268,7 @@ TEST_CASE("a failure names llama-server's address and command only when asked to nobody.port = closed_port(); agent::answer_options o; o.names_server = false; - agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", + agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", {}, std::chrono::steady_clock::now(), o); const auto events = drain(s, 4096); REQUIRE(events.size() == 2); @@ -553,7 +555,9 @@ TEST_CASE("a session stream records one done turn with the answer and the event agent::answer_options o; o.turn = 7; o.sink = sink; - agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 3), "q", + const auto found = one_passage(); + agent::answer_stream s(stub.settings(), found, event_of(found, 3), "q", + std::vector{{"prior question", "prior [1]"}}, std::chrono::steady_clock::now(), o); static_cast(drain(s)); @@ -566,6 +570,13 @@ TEST_CASE("a session stream records one done turn with the answer and the event CHECK(r.done->cited == std::vector{1}); CHECK(r.done->total_ms > 0); CHECK_FALSE(r.failure); + + const auto asked = json_document::parse(stub.last_body()); + REQUIRE(asked); + const auto messages = asked->root().member("messages"); + REQUIRE(messages.size() == 4); + CHECK(messages.element(1).member("content").text_or() == "prior question"); + CHECK(messages.element(2).member("content").text_or() == "prior [cited earlier]"); } TEST_CASE("a session stream records its failure, and any partial answer with it", @@ -576,8 +587,9 @@ TEST_CASE("a session stream records its failure, and any partial answer with it" agent::answer_options o; o.turn = 9; o.sink = sink; - agent::answer_stream s(nobody, one_passage(), event_of(one_passage(), 0), "q", - std::chrono::steady_clock::now(), o); + const auto found = one_passage(); + agent::answer_stream s(nobody, found, event_of(found, 0), "q", + std::vector{}, std::chrono::steady_clock::now(), o); static_cast(drain(s, 4096)); REQUIRE(sink->terminals.size() == 1); @@ -597,9 +609,10 @@ TEST_CASE("a stream destroyed while answering records stopped with the partial t o.turn = 11; o.sink = sink; o.partial_every = 10ms; + const auto found = one_passage(); asio::io_context io; auto s = std::make_unique( - stub.settings(), one_passage(), event_of(one_passage(), 0), "q", + stub.settings(), found, event_of(found, 0), "q", std::vector{}, std::chrono::steady_clock::now(), o); std::size_t taken = 0; asio::co_spawn( @@ -633,8 +646,9 @@ TEST_CASE("a growing answer is snapshotted while it streams", "[agent][llama][si o.turn = 12; o.sink = sink; o.partial_every = 10ms; - agent::answer_stream s(stub.settings(), one_passage(), event_of(one_passage(), 0), "q", - std::chrono::steady_clock::now(), o); + const auto found = one_passage(); + agent::answer_stream s(stub.settings(), found, event_of(found, 0), "q", + std::vector{}, std::chrono::steady_clock::now(), o); static_cast(drain(s, 4096)); REQUIRE_FALSE(sink->partials.empty()); diff --git a/projects/compass.http/tests/ops_agent_tests.cpp b/projects/compass.http/tests/ops_agent_tests.cpp index 71128998..f7094bcb 100644 --- a/projects/compass.http/tests/ops_agent_tests.cpp +++ b/projects/compass.http/tests/ops_agent_tests.cpp @@ -247,3 +247,104 @@ TEST_CASE("an event is its name and one line of data", "[agent][ops]") { CHECK(ops::agent_event("token", R"({"text":"a"})") == "event: token\ndata: {\"text\":\"a\"}\n\n"); } + +TEST_CASE("a prior answer's citations are neutralised before the model sees them", + "[agent][ops]") { + CHECK(ops::neutralise_citations("The log records the weather [1], the ships [1, 3].") == + "The log records the weather [cited earlier], the ships [cited earlier]."); + CHECK(ops::neutralise_citations("[12] and [cited earlier]") == + "[cited earlier] and [cited earlier]"); + CHECK(ops::neutralise_citations("plain [not a number]") == "plain [not a number]"); +} + +TEST_CASE("the history keeps the newest exchanges that fit both caps, whole", + "[agent][ops]") { + std::vector turns; + for (int i = 1; i <= 10; ++i) + turns.push_back({"question " + std::to_string(i), "answer " + std::to_string(i) + " [1]"}); + + const auto newest_eight = ops::agent_history_window(turns); + REQUIRE(newest_eight.size() == 8); + CHECK(newest_eight.front().question == "question 3"); + CHECK(newest_eight.back().question == "question 10"); + CHECK(newest_eight.back().answer == "answer 10 [cited earlier]"); + + const std::vector ten{ + {"q1", std::string(100, 'a')}, {"q2", std::string(100, 'b')}, + {"q3", std::string(100, 'c')}, {"q4", std::string(100, 'd')}}; + const auto by_bytes = ops::agent_history_window(ten, 8, 250); + REQUIRE(by_bytes.size() == 2); + CHECK(by_bytes.front().question == "q3"); + CHECK(by_bytes.back().question == "q4"); + + const std::vector answerless{{"q1", ""}, {"q2", "a2"}}; + const auto kept = ops::agent_history_window(answerless); + REQUIRE(kept.size() == 1); + CHECK(kept.front().question == "q2"); +} + +TEST_CASE("the history budget is the context less the answer, prompt and slack", + "[agent][ops]") { + CHECK(ops::agent_history_budget(65536, 2000) == 24000); + CHECK(ops::agent_history_budget(4000, 2000) == (4000 - 400) * 4 - 2000 - 1024); + CHECK(ops::agent_history_budget(1000, 2000) == 0); + CHECK(ops::agent_history_budget(400, 0) == 0); +} + +TEST_CASE("the prompt appends the session's exchanges before the current question", + "[agent][ops]") { + const std::vector passages{ + passage(1, "Hello", messages::hit_kind::knowledge)}; + const std::vector history{{"What is the log?", "It records [1]."}}; + const auto prompt = ops::agent_prompt_for("And why?", passages, history); + REQUIRE(prompt.history.size() == 2); + CHECK(prompt.history[0].role == "user"); + CHECK(prompt.history[0].content == "What is the log?"); + CHECK(prompt.history[1].role == "assistant"); + CHECK(prompt.history[1].content == "It records [cited earlier]."); + CHECK(prompt.user.ends_with("Question: And why?")); + + const auto body = compass::db::codec::json_document::parse(ops::agent_chat_body(prompt)); + REQUIRE(body); + const auto messages = body->root().member("messages"); + REQUIRE(messages.size() == 4); + CHECK(messages.element(0).member("role").text_or() == "system"); + CHECK(messages.element(1).member("role").text_or() == "user"); + CHECK(messages.element(2).member("role").text_or() == "assistant"); + CHECK(messages.element(3).member("role").text_or() == "user"); +} + +TEST_CASE("a follow-up without keywords searches the previous question's", + "[agent][ops]") { + std::vector asked; + const auto search = [&](const std::string& q) { + asked.push_back(q); + return std::vector{}; + }; + const auto no_sections = [](const search_hit&) { return std::vector{}; }; + static_cast(ops::agent_retrieve("and why?", search, no_sections, + "Who is the lighthouse keeper?")); + REQUIRE_FALSE(asked.empty()); + CHECK(asked.front() == "lighthouse keeper"); + + asked.clear(); + static_cast(ops::agent_retrieve("and what about the GPU?", search, no_sections, + "Who is the lighthouse keeper?")); + REQUIRE_FALSE(asked.empty()); + CHECK(asked.front() == "gpu"); +} + +TEST_CASE("with no passages and a history, the system rule answers from the conversation", + "[agent][ops]") { + const std::vector history{ + {"What is the log?", "It records weather [1]."}}; + const auto with = ops::agent_prompt_for("and why?", {}, history); + CHECK_THAT(with.system, ContainsSubstring("conversation above")); + CHECK(with.user == "Question: and why?"); + CHECK(with.history.size() == 2); + + const auto without = ops::agent_prompt_for("and why?", {}, {}); + CHECK_THAT(without.system, ContainsSubstring("no document matched")); + CHECK_THAT(without.system, !ContainsSubstring("conversation above")); + CHECK(without.user == "Question: and why?"); +} From 5f0bb5212e444fd43ac818612a3b94d5d5318cbc Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:34:44 +0000 Subject: [PATCH 05/24] [web] Open, restore and delete the agent's conversations The Agent screen names its conversation in the address as ?session=, the panel lists the caller's conversations and can start or delete one, and the provider rebuilds the transcript from the stored passages and done events, so a reload restores the answers, citations and timings. A stored streaming row shows as cut until the poll sees it settle, a conversation this tab streamed is never refetched under live turns, and a session the caller does not own shows the notice and the list rather than a new conversation. The shell test covers restore, history in the prompt, delete and an abandoned stream in Chromium. Co-Authored-By: Claude Code --- .../packages/pages/src/AgentPanel.tsx | 165 +++++++++++- .../packages/pages/src/agent.test.tsx | 123 +++++++++ .../compass.web/packages/pages/src/agent.ts | 65 ++++- .../packages/pages/src/client.test.ts | 164 ++++++++++++ .../compass.web/packages/pages/src/client.ts | 181 ++++++++++++- .../packages/pages/src/conversation.tsx | 253 +++++++++++++++--- .../compass.web/packages/pages/src/i18n/en.ts | 11 + .../compass.web/packages/pages/src/i18n/fr.ts | 11 + .../compass.web/packages/pages/src/i18n/pt.ts | 11 + .../packages/pages/src/pages.test.tsx | 7 + .../compass.web/packages/pages/src/pages.tsx | 8 +- .../packages/web/e2e/agent.spec.ts | 61 +++++ .../packages/web/e2e/llama_stub.mjs | 16 +- 13 files changed, 1020 insertions(+), 56 deletions(-) diff --git a/projects/compass.web/packages/pages/src/AgentPanel.tsx b/projects/compass.web/packages/pages/src/AgentPanel.tsx index 33b5d3e9..e73e6cf3 100644 --- a/projects/compass.web/packages/pages/src/AgentPanel.tsx +++ b/projects/compass.web/packages/pages/src/AgentPanel.tsx @@ -20,7 +20,7 @@ import { useQuery } from '@tanstack/react-query'; import { useEffect, useRef, useState, type ReactNode } from 'react'; -import { Link, useSearchParams } from 'react-router'; +import { Link, useNavigate, useSearchParams } from 'react-router'; import { answerBlocks, citedPassage, @@ -44,6 +44,7 @@ import { import { useCompass } from './context.js'; import { agentStatusKey, useConversation } from './conversation.js'; import { useTranslation } from './i18n/Provider.js'; +import { linkTo } from './pages.js'; const STATUS_POLL_MS = 5000; @@ -63,14 +64,16 @@ export function AgentPanel({ initialQuestion, onClose, onFollow, + onSessionDeleted, }: { readonly environment: string; readonly initialQuestion?: string; readonly onClose?: () => void; readonly onFollow?: () => void; + readonly onSessionDeleted?: () => void; }): ReactNode { const { t } = useTranslation(); - const { turns, ask } = useConversation(); + const { turns, ask, missing } = useConversation(); const [draft, setDraft] = useState(''); const started = useRef(false); @@ -99,6 +102,12 @@ export function AgentPanel({ data-testid="agent-panel" > + + {missing ? ( +

+ {t('agent.sessions.missing')} +

+ ) : null} {turns.length === 0 ? (

{t('agent.home')}

) : ( @@ -149,6 +158,121 @@ export function AgentPanel({ ); } +/** + * The conversations a person may open, and the controls that make a new one + * or delete the open one. A conversation created here becomes the provider's + * selection; the Agent screen puts it in the address, and a host's shell + * shows it beside its screen. + */ +function SessionBar({ + environment, + onDeleted, +}: { + readonly environment: string; + readonly onDeleted?: () => void; +}): ReactNode { + const { t, language } = useTranslation(); + const { client } = useCompass(); + const { session, sessions, open, remove } = useConversation(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + const created = async () => { + setBusy(true); + setError(null); + try { + const made = await client.createAgentSession(environment); + open(environment, made.session); + } catch (failure) { + setError( + t('agent.sessions.failed', { + reason: failure instanceof Error ? failure.message : String(failure), + }), + ); + } finally { + setBusy(false); + } + }; + + const deleted = async () => { + if (session === null || !globalThis.confirm(t('agent.sessions.confirmDelete'))) { + return; + } + setBusy(true); + setError(null); + try { + await remove(); + onDeleted?.(); + } catch (failure) { + setError( + t('agent.sessions.failed', { + reason: failure instanceof Error ? failure.message : String(failure), + }), + ); + } finally { + setBusy(false); + } + }; + + const when = (iso: string): string => { + const at = new Date(iso); + return Number.isNaN(at.getTime()) + ? iso + : new Intl.DateTimeFormat(language, { + dateStyle: 'short', + timeStyle: 'short', + }).format(at); + }; + + return ( +
+
+ + + + +
+ {error === null ? null : ( +

+ {error} +

+ )} +
+ ); +} + function AgentHeader({ onClose }: { readonly onClose?: () => void }): ReactNode { const { t } = useTranslation(); const { inputs, client } = useCompass(); @@ -665,14 +789,45 @@ function Given({ retrieval }: { readonly retrieval: PassagesEvent }): ReactNode } /** - * The Agent screen: the panel at the width of a reading column, asking the - * question the address names, as AI mode leaves it. + * The Agent screen: the panel at the width of a reading column, its + * conversation in the address as ?session=, so a reload restores it. Opening + * the address restores that conversation; a conversation made in the panel is + * put there; a conversation deleted leaves the address without one. */ export function AgentScreen({ environment }: { readonly environment: string }): ReactNode { const [params] = useSearchParams(); + const navigate = useNavigate(); + const { session, open } = useConversation(); + const wanted = sessionOf(params.get('session')); + + useEffect(() => { + open(environment, wanted); + }, [environment, wanted, open]); + + useEffect(() => { + if (session !== null && session !== wanted) { + navigate(linkTo({ environment, screen: 'agent', session }), { replace: true }); + } + }, [session, wanted, environment, navigate]); + return (
- + + navigate(linkTo({ environment, screen: 'agent' }), { replace: true }) + } + />
); } + +/** The session an address names, a positive integer, or none for anything else. */ +function sessionOf(value: string | null): number | null { + if (value === null || !/^\d+$/.test(value)) { + return null; + } + const session = Number(value); + return Number.isSafeInteger(session) && session > 0 ? session : null; +} diff --git a/projects/compass.web/packages/pages/src/agent.test.tsx b/projects/compass.web/packages/pages/src/agent.test.tsx index a8687b1a..4c5b4e6b 100644 --- a/projects/compass.web/packages/pages/src/agent.test.tsx +++ b/projects/compass.web/packages/pages/src/agent.test.tsx @@ -33,6 +33,9 @@ import { conversationReducer, sources, statusText, + stillStreaming, + turnsOf, + UNFINISHED_MS, type Turn, } from './agent.js'; import { AgentPanel, AgentScreen, TurnView } from './AgentPanel.js'; @@ -43,6 +46,7 @@ import { type AgentStatus, type CompassInputs, type DoneEvent, + type GetAgentSessionResponse, type Passage, } from './client.js'; import { CompassPagesProvider } from './context.js'; @@ -588,4 +592,123 @@ describe('the agent panel', () => { 'llama-server at 127.0.0.1:8081 is failing: out of memory', ); }); + + it('shows the conversations and the controls that make or delete one', () => { + const html = drawPanel(status); + expect(html).toContain(enFlat['agent.sessions.label']); + expect(html).toContain(enFlat['agent.sessions.create']); + expect(html).toContain(enFlat['agent.sessions.delete']); + expect(html).toContain('data-testid="agent-sessions"'); + }); +}); + +const storedSession: GetAgentSessionResponse = { + session: 7, + environment: 'compass', + title: 'The log', + created_at: '2026-12-02T09:00:00Z', + updated_at: '2026-12-02T10:00:01Z', + turns: [ + { + id: 1, + ord: 1, + question: 'Done?', + asked_at: '2026-12-02T10:00:00Z', + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: 'A [1].', + status: 'done', + done, + failure: null, + }, + { + id: 2, + ord: 2, + question: 'Failed?', + asked_at: '2026-12-02T10:00:01Z', + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: '', + status: 'failed', + done: null, + failure: { code: 'not_running', message: 'not running' }, + }, + { + id: 3, + ord: 3, + question: 'Stopped?', + asked_at: '2026-12-02T10:00:02Z', + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: 'Half', + status: 'stopped', + done: null, + failure: null, + }, + { + id: 4, + ord: 4, + question: 'Cut?', + asked_at: '2026-12-02T10:00:03Z', + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: '', + status: 'cut', + done: null, + failure: null, + }, + { + id: 5, + ord: 5, + question: 'Streaming?', + asked_at: new Date().toISOString(), + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: 'Half', + status: 'streaming', + done: null, + failure: null, + }, + ], +}; + +describe('a restored conversation', () => { + it('rebuilds each turn from the stored events and status', () => { + const turns = turnsOf(storedSession); + expect(turns.map((turn) => turn.end?.kind)).toEqual([ + 'done', + 'failure', + 'stopped', + 'cut', + 'cut', + ]); + expect(turns[0]?.retrieval?.retrieval_ms).toBe(1); + expect(turns[0]?.end).toEqual({ kind: 'done', done }); + expect(turns[1]?.end).toEqual({ + kind: 'failure', + failure: { code: 'not_running', message: 'not running' }, + }); + expect(turns[2]?.text).toBe('Half'); + expect(turns[0]?.asked).toBe(Date.parse('2026-12-02T10:00:00Z')); + expect(turns[0]?.environment).toBe('compass'); + expect(turns[0]?.id).toBe(1); + }); + + it('replaces the turns rather than appending them, so a StrictMode double restore is one copy', () => { + const restored = conversationReducer([asked], { + type: 'restore', + turns: turnsOf(storedSession), + }); + expect(restored).toHaveLength(5); + const twice = conversationReducer(restored, { + type: 'restore', + turns: turnsOf(storedSession), + }); + expect(twice).toHaveLength(5); + expect(twice).toEqual(restored); + }); + + it('polls a streaming turn until it settles or is too old to be alive', () => { + const fresh = storedSession.turns[4]!; + expect(stillStreaming(fresh)).toBe(true); + expect(stillStreaming(fresh, Date.parse(fresh.asked_at) + UNFINISHED_MS + 1)).toBe( + false, + ); + expect(stillStreaming(storedSession.turns[0]!)).toBe(false); + }); }); diff --git a/projects/compass.web/packages/pages/src/agent.ts b/projects/compass.web/packages/pages/src/agent.ts index ada0b8a0..0c7d35d5 100644 --- a/projects/compass.web/packages/pages/src/agent.ts +++ b/projects/compass.web/packages/pages/src/agent.ts @@ -18,7 +18,15 @@ * */ -import type { AgentEvent, DoneEvent, FailureEvent, Passage, PassagesEvent } from './client.js'; +import type { + AgentEvent, + AgentTurn, + DoneEvent, + FailureEvent, + GetAgentSessionResponse, + Passage, + PassagesEvent, +} from './client.js'; import type { Translator } from './i18n/translate.js'; export type TurnEnd = @@ -41,7 +49,8 @@ export interface Turn { export type ConversationAction = | { readonly type: 'ask'; readonly turn: Turn } | { readonly type: 'event'; readonly id: number; readonly event: AgentEvent } - | { readonly type: 'end'; readonly id: number; readonly end: TurnEnd }; + | { readonly type: 'end'; readonly id: number; readonly end: TurnEnd } + | { readonly type: 'restore'; readonly turns: readonly Turn[] }; function applyEvent(turn: Turn, event: AgentEvent): Turn { switch (event.event) { @@ -60,6 +69,9 @@ export function conversationReducer( turns: readonly Turn[], action: ConversationAction, ): readonly Turn[] { + if (action.type === 'restore') { + return action.turns; + } if (action.type === 'ask') { return [...turns, action.turn]; } @@ -73,6 +85,55 @@ export function conversationReducer( }); } +/** How long a stored stream may stay streaming before it is shown as cut. */ +export const UNFINISHED_MS = 15 * 60 * 1000; + +/** + * Whether a stored turn still streams an answer another tab or a just-closed + * stream wrote: the session query polls while one does, and treats one older + * than @p now less UNFINISHED_MS as cut, so a lost answer does not poll for + * ever. + */ +export function stillStreaming(turn: AgentTurn, now: number = Date.now()): boolean { + return turn.status === 'streaming' && now - Date.parse(turn.asked_at) < UNFINISHED_MS; +} + +function endOf(turn: AgentTurn): TurnEnd { + switch (turn.status) { + case 'done': + return turn.done === null + ? { kind: 'cut' } + : { kind: 'done', done: turn.done }; + case 'failed': + return turn.failure === null + ? { kind: 'cut' } + : { kind: 'failure', failure: turn.failure }; + case 'stopped': + return { kind: 'stopped' }; + case 'cut': + case 'streaming': + return { kind: 'cut' }; + } +} + +/** + * The browser's turns of a stored conversation: each stored exchange rebuilt + * as it streamed, because =retrieval=, =done= and =failure= are the events + * the live stream sent. A streaming row shows as cut; the caller polls until + * it settles. + */ +export function turnsOf(session: GetAgentSessionResponse): Turn[] { + return session.turns.map((turn) => ({ + id: turn.id, + environment: session.environment, + question: turn.question, + asked: Date.parse(turn.asked_at), + retrieval: turn.retrieval, + text: turn.answer, + end: endOf(turn), + })); +} + const QUESTION_LIMIT = 500; /** diff --git a/projects/compass.web/packages/pages/src/client.test.ts b/projects/compass.web/packages/pages/src/client.test.ts index f43454a2..8d6c58a6 100644 --- a/projects/compass.web/packages/pages/src/client.test.ts +++ b/projects/compass.web/packages/pages/src/client.test.ts @@ -217,6 +217,19 @@ describe('every request of the client', () => { for await (const event of c.askAgent('compass', 'how?', new AbortController().signal)) void event; }, + askAgentSession: async (c) => { + for await (const event of c.askAgentSession( + 'compass', + 7, + 'how?', + new AbortController().signal, + )) + void event; + }, + createAgentSession: (c) => c.createAgentSession('compass', 'Title'), + listAgentSessions: (c) => c.listAgentSessions('compass'), + getAgentSession: (c) => c.getAgentSession('compass', 7), + deleteAgentSession: (c) => c.deleteAgentSession('compass', 7), environments: (c) => c.environments(), search: (c) => c.search({ @@ -291,3 +304,154 @@ describe('every request of the client', () => { }, ); }); + +describe("the agent's conversations", () => { + const storedTurn = { + id: 1, + ord: 1, + question: 'What does the log record?', + asked_at: '2026-12-02T10:00:00Z', + retrieval: { queries: ['log'], passages: [], retrieval_ms: 3 }, + answer: 'The weather [1].', + status: 'done', + done: { + cited: [1], + dropped: [], + first_token_ms: 10, + total_ms: 20, + prompt_tokens: 30, + generated_tokens: 4, + tokens_per_second: 5, + finish_reason: 'stop', + }, + failure: null, + }; + const storedSession = { + session: 7, + environment: 'compass', + title: 'The log', + created_at: '2026-12-02T09:00:00Z', + updated_at: '2026-12-02T10:00:01Z', + turns: [ + storedTurn, + { + id: 2, + ord: 2, + question: 'And why?', + asked_at: '2026-12-02T10:01:00Z', + retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + answer: '', + status: 'cut', + done: null, + failure: null, + }, + ], + }; + + it('creates a conversation with an empty body when it gives no title', async () => { + const asked: { url: string; init: RequestInit | undefined }[] = []; + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + (input, init) => { + asked.push({ url: String(input), init }); + return Promise.resolve( + new Response(JSON.stringify({ session: 7, created_at: 'at' }), { + status: 200, + }), + ); + }, + ); + await expect(client.createAgentSession('compass')).resolves.toEqual({ + session: 7, + created_at: 'at', + }); + expect(asked[0]?.url).toBe('/v1/compass/agent/sessions'); + expect(asked[0]?.init?.method).toBe('POST'); + expect(asked[0]?.init?.body).toBe('{}'); + }); + + it('lists the caller\'s conversations with the page asked for', async () => { + const asked: string[] = []; + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + (input) => { + asked.push(String(input)); + return Promise.resolve( + new Response( + JSON.stringify({ + sessions: [ + { + session: 7, + title: 'The log', + created_at: 'a', + updated_at: 'b', + turns: 2, + }, + ], + }), + { status: 200 }, + ), + ); + }, + ); + await expect(client.listAgentSessions('compass', 10, 5)).resolves.toEqual([ + { session: 7, title: 'The log', created_at: 'a', updated_at: 'b', turns: 2 }, + ]); + expect(asked).toEqual(['/v1/compass/agent/sessions?limit=10&offset=5']); + }); + + it('reads a conversation with the stored events of each turn', async () => { + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + answering(200, storedSession), + ); + const session = await client.getAgentSession('compass', 7); + expect(session.turns[0]?.retrieval.retrieval_ms).toBe(3); + expect(session.turns[0]?.done?.cited).toEqual([1]); + expect(session.turns[1]?.status).toBe('cut'); + expect(session.turns[1]?.done).toBeNull(); + }); + + it('asks in a conversation with a POST whose body holds the question', async () => { + const asked: { url: string; init: RequestInit | undefined }[] = []; + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + (input, init) => { + asked.push({ url: String(input), init }); + return Promise.resolve( + new Response( + 'event: token\ndata: {"text":"The weather"}\n\n' + + 'event: done\ndata: {"cited":[1],"dropped":[],"first_token_ms":1,' + + '"total_ms":2,"prompt_tokens":3,"generated_tokens":4,' + + '"tokens_per_second":5,"finish_reason":"stop"}\n\n', + { status: 200 }, + ), + ); + }, + ); + const events = []; + for await (const event of client.askAgentSession( + 'compass', + 7, + 'and why?', + new AbortController().signal, + )) { + events.push(event.event); + } + expect(asked[0]?.url).toBe('/v1/compass/agent/sessions/7/ask'); + expect(asked[0]?.init?.method).toBe('POST'); + expect(asked[0]?.init?.body).toBe('{"q":"and why?"}'); + expect(events).toEqual(['token', 'done']); + }); + + it('surfaces a 404 for a conversation of another caller as the refusal it is', async () => { + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + answering(404, { code: 'not_found', message: 'No such conversation.' }), + ); + await expect(client.getAgentSession('compass', 7)).rejects.toMatchObject({ + status: 404, + code: 'not_found', + }); + }); +}); diff --git a/projects/compass.web/packages/pages/src/client.ts b/projects/compass.web/packages/pages/src/client.ts index 0bf50221..79356320 100644 --- a/projects/compass.web/packages/pages/src/client.ts +++ b/projects/compass.web/packages/pages/src/client.ts @@ -394,6 +394,59 @@ export type DoneEvent = z.infer; export type FailureEvent = z.infer; export type AgentEvent = z.infer; +/** How a stored exchange ended, as agent.agent_turn.status holds it. */ +export const AGENT_TURN_STATUSES = ['streaming', 'done', 'failed', 'stopped', 'cut'] as const; +export const agentTurnStatusSchema = z.enum(AGENT_TURN_STATUSES); + +/** One conversation in the caller's list. */ +export const agentSessionSummarySchema = z.object({ + session: z.number().int(), + title: z.string(), + created_at: z.string(), + updated_at: z.string(), + turns: count, +}); + +export const listAgentSessionsResponseSchema = z.object({ + sessions: z.array(agentSessionSummarySchema), +}); + +export const createAgentSessionResponseSchema = z.object({ + session: z.number().int(), + created_at: z.string(), +}); + +/** + * One stored exchange: the question, the passages event the stream sent, the + * answer as stored, and the event that settled it. + */ +export const agentTurnSchema = z.object({ + id: z.number().int(), + ord: z.number().int(), + question: z.string(), + asked_at: z.string(), + retrieval: passagesEventSchema, + answer: z.string(), + status: agentTurnStatusSchema, + done: doneEventSchema.nullable(), + failure: failureEventSchema.nullable(), +}); + +export const getAgentSessionResponseSchema = z.object({ + session: z.number().int(), + environment: z.string(), + title: z.string(), + created_at: z.string(), + updated_at: z.string(), + turns: z.array(agentTurnSchema), +}); + +export type AgentTurnStatus = z.infer; +export type AgentSessionSummary = z.infer; +export type AgentTurn = z.infer; +export type GetAgentSessionResponse = z.infer; +export type CreateAgentSessionResponse = z.infer; + export interface SseFrame { readonly event: string; readonly data: string; @@ -623,6 +676,11 @@ export interface SearchQuery { */ export type Place = | { readonly environment: string; readonly screen?: ScreenKey } + | { + readonly environment: string; + readonly screen: 'agent'; + readonly session: number; + } | { readonly environment: string; readonly screen: 'documents'; @@ -717,6 +775,33 @@ export interface CompassClient { question: string, signal: AbortSignal, ) => AsyncIterable; + /** Makes a conversation in @p environment, titled when @p title is given. */ + readonly createAgentSession: ( + environment: string, + title?: string, + ) => Promise; + /** The caller's conversations in @p environment, most recently changed first. */ + readonly listAgentSessions: ( + environment: string, + limit?: number, + offset?: number, + ) => Promise; + /** A conversation and its exchanges, or a 404 when this caller does not own it. */ + readonly getAgentSession: ( + environment: string, + session: number, + ) => Promise; + readonly deleteAgentSession: (environment: string, session: number) => Promise; + /** + * Asks @p question in conversation @p session, as the stateless ask does: + * the same events, yielded as they arrive. + */ + readonly askAgentSession: ( + environment: string, + session: number, + question: string, + signal: AbortSignal, + ) => AsyncIterable; readonly environments: () => Promise; /** A search; @p signal abandons it, as when a newer keystroke supersedes it. */ readonly search: (query: SearchQuery, signal?: AbortSignal) => Promise; @@ -871,26 +956,28 @@ export function createClient( return parsed.data; } - async function* askAgent( - environment: string, - question: string, + /** + * The events of an answer compass.http streams, whatever opened it. A + * refusal is thrown before the first event; a frame of another name, or + * one whose data is not the shape the event names, is unreadable. + */ + async function* answerStream( + method: string, + path: string, + init: RequestInit, signal: AbortSignal, ): AsyncGenerator { - const path = `${environmentPath(environment)}/agent?${new URLSearchParams({ q: question })}`; - const response = await fetchImpl(inputs.httpBase + path, { - headers: { ...hostHeaders, Accept: 'text/event-stream' }, - signal, - }); + const response = await fetchImpl(inputs.httpBase + path, { ...init, signal }); if (!response.ok) { throw refused( - 'GET', + method, path, response.status, await response.json().catch(() => undefined), ); } if (response.body === null) { - throw unreadable('GET', path); + throw unreadable(method, path); } const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); const frames = createFrameReader(); @@ -908,11 +995,11 @@ export function createClient( try { data = JSON.parse(frame.data); } catch { - throw unreadable('GET', path); + throw unreadable(method, path); } const event = agentEventSchema.safeParse({ event: frame.event, data }); if (!event.success) { - throw unreadable('GET', path); + throw unreadable(method, path); } yield event.data; } @@ -922,6 +1009,43 @@ export function createClient( } } + function askAgent( + environment: string, + question: string, + signal: AbortSignal, + ): AsyncIterable { + const path = `${environmentPath(environment)}/agent?${new URLSearchParams({ q: question })}`; + return answerStream( + 'GET', + path, + { headers: { ...hostHeaders, Accept: 'text/event-stream' } }, + signal, + ); + } + + function askAgentSession( + environment: string, + session: number, + question: string, + signal: AbortSignal, + ): AsyncIterable { + const path = `${environmentPath(environment)}/agent/sessions/${session}/ask`; + return answerStream( + 'POST', + path, + { + method: 'POST', + headers: { + ...hostHeaders, + Accept: 'text/event-stream', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ q: question }), + }, + signal, + ); + } + async function read(path: string, schema: z.ZodType, signal?: AbortSignal): Promise { const body = await ask('GET', path, { headers: { Accept: 'application/json' }, @@ -954,6 +1078,39 @@ export function createClient( return { agent: () => read('v1/agent', agentStatusSchema), askAgent, + askAgentSession, + createAgentSession: (environment, title) => + write( + 'POST', + `${environmentPath(environment)}/agent/sessions`, + title === undefined ? {} : { title }, + createAgentSessionResponseSchema, + ), + listAgentSessions: async (environment, limit = 50, offset = 0) => { + const params = new URLSearchParams({ + limit: String(limit), + offset: String(offset), + }); + return ( + await read( + `${environmentPath(environment)}/agent/sessions?${params}`, + listAgentSessionsResponseSchema, + ) + ).sessions; + }, + getAgentSession: (environment, session) => + read( + `${environmentPath(environment)}/agent/sessions/${session}`, + getAgentSessionResponseSchema, + ), + deleteAgentSession: async (environment, session) => { + await write( + 'DELETE', + `${environmentPath(environment)}/agent/sessions/${session}`, + undefined, + none, + ); + }, environments: async () => (await read('v1/environments', environmentsSchema)).environments, search: (query, signal) => { const params = filterParameters(query.filter); diff --git a/projects/compass.web/packages/pages/src/conversation.tsx b/projects/compass.web/packages/pages/src/conversation.tsx index a667c76a..fbe04604 100644 --- a/projects/compass.web/packages/pages/src/conversation.tsx +++ b/projects/compass.web/packages/pages/src/conversation.tsx @@ -18,7 +18,7 @@ * */ -import { useQueryClient } from '@tanstack/react-query'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; import { createContext, use, @@ -27,18 +27,55 @@ import { useMemo, useReducer, useRef, + useState, type ReactNode, } from 'react'; -import { conversationReducer, type Turn } from './agent.js'; -import type { AgentEvent, CompassClient } from './client.js'; +import { conversationReducer, stillStreaming, turnsOf, type Turn } from './agent.js'; +import { + CompassRequestError, + retryable, + type AgentEvent, + type AgentSessionSummary, + type CompassClient, +} from './client.js'; export function agentStatusKey(httpBase: string): readonly unknown[] { return ['compass', httpBase, 'agent']; } +export function agentSessionsKey( + httpBase: string, + environment: string, +): readonly unknown[] { + return ['compass', httpBase, 'agent', 'sessions', environment]; +} + +export function agentSessionKey( + httpBase: string, + environment: string, + session: number, +): readonly unknown[] { + return ['compass', httpBase, 'agent', 'session', environment, session]; +} + +/** The conversation a person has open: its environment and session, if any. */ +interface Opened { + readonly environment: string | null; + readonly session: number | null; +} + interface ConversationValue { + /** The conversation open in this provider; null until one is made or restored. */ + readonly session: number | null; + /** The caller's conversations in the open environment, most recent first. */ + readonly sessions: readonly AgentSessionSummary[]; readonly turns: readonly Turn[]; + /** True when the address named a conversation this caller does not own. */ + readonly missing: boolean; readonly ask: (environment: string, question: string) => void; + readonly open: (environment: string, session: number | null) => void; + /** Deletes the open conversation and starts a new, empty one. */ + readonly remove: () => Promise; } const ConversationContext = createContext(undefined); @@ -54,50 +91,165 @@ export function ConversationProvider({ }): ReactNode { const queries = useQueryClient(); const [turns, dispatch] = useReducer(conversationReducer, []); - const running = useRef<{ readonly id: number; readonly abort: AbortController } | null>(null); - const next = useRef(1); + const [opened, setOpened] = useState({ environment: null, session: null }); + const [owned, setOwned] = useState(null); + const [missing, setMissing] = useState(false); + const running = useRef<{ + readonly id: number; + readonly session: number; + readonly abort: AbortController; + } | null>(null); + const current = useRef({ environment: null, session: null }); + const next = useRef(-1); + + const sessions = useQuery({ + queryKey: agentSessionsKey(httpBase, opened.environment ?? ''), + queryFn: () => client.listAgentSessions(opened.environment!), + enabled: opened.environment !== null, + retry: retryable, + }); + + const sessionQuery = useQuery({ + queryKey: agentSessionKey( + httpBase, + opened.environment ?? '', + opened.session ?? 0, + ), + queryFn: () => client.getAgentSession(opened.environment!, opened.session!), + // A conversation this provider streamed is never refetched under the + // live turns: the terminal write is asynchronous, and a read of it + // could race that write and restore a turn the person is watching. + enabled: + opened.environment !== null && opened.session !== null && owned !== opened.session, + retry: retryable, + refetchInterval: (query) => { + const data = query.state.data; + if (data === undefined) { + return false; + } + return data.turns.some((turn) => stillStreaming(turn)) ? 2_000 : false; + }, + }); + + useEffect( + () => () => { + running.current?.abort.abort(); + running.current = null; + }, + [], + ); + + useEffect(() => { + const data = sessionQuery.data; + if (data === undefined || data.session !== opened.session || opened.session === null) { + return; + } + if (running.current?.session === data.session || owned === data.session) { + return; + } + dispatch({ type: 'restore', turns: turnsOf(data) }); + }, [sessionQuery.data, opened.session, owned]); - useEffect(() => () => running.current?.abort.abort(), []); + useEffect(() => { + if ( + opened.session !== null && + sessionQuery.error instanceof CompassRequestError && + sessionQuery.error.status === 404 + ) { + setMissing(true); + } + }, [sessionQuery.error, opened.session]); + + const open = useCallback((environment: string, session: number | null) => { + if (current.current.environment === environment && current.current.session === session) { + return; + } + if (running.current !== null) { + running.current.abort.abort(); + dispatch({ type: 'end', id: running.current.id, end: { kind: 'stopped' } }); + running.current = null; + } + current.current = { environment, session }; + setOpened({ environment, session }); + setOwned(null); + setMissing(false); + dispatch({ type: 'restore', turns: [] }); + }, []); const ask = useCallback( (environment: string, question: string) => { if (running.current !== null) { running.current.abort.abort(); dispatch({ type: 'end', id: running.current.id, end: { kind: 'stopped' } }); + running.current = null; } - const id = next.current++; - const abort = new AbortController(); - running.current = { id, abort }; - dispatch({ - type: 'ask', - turn: { - id, - environment, - question, - asked: Date.now(), - retrieval: null, - text: '', - end: null, - }, - }); - const refreshStatus = () => - queries.invalidateQueries({ queryKey: agentStatusKey(httpBase) }); - void (async () => { + const start = async () => { + let session = current.current.session; + if (current.current.environment !== environment || session === null) { + try { + const created = await client.createAgentSession(environment); + session = created.session; + } catch (error) { + const id = next.current--; + dispatch({ + type: 'ask', + turn: { + id, + environment, + question, + asked: Date.now(), + retrieval: null, + text: '', + end: null, + }, + }); + dispatch({ + type: 'end', + id, + end: { + kind: 'error', + message: + error instanceof Error ? error.message : String(error), + }, + }); + return; + } + current.current = { environment, session }; + setOpened({ environment, session }); + setOwned(session); + setMissing(false); + dispatch({ type: 'restore', turns: [] }); + } else { + setOwned(session); + } + const id = next.current--; + const abort = new AbortController(); + running.current = { id, session, abort }; + dispatch({ + type: 'ask', + turn: { + id, + environment, + question, + asked: Date.now(), + retrieval: null, + text: '', + end: null, + }, + }); try { let last: AgentEvent['event'] | undefined; - for await (const event of client.askAgent( + for await (const event of client.askAgentSession( environment, + session, question, abort.signal, )) { dispatch({ type: 'event', id, event }); last = event.event; } - if (last !== 'done') { - if (last !== 'failure') { - dispatch({ type: 'end', id, end: { kind: 'cut' } }); - } - await refreshStatus(); + if (last !== 'done' && last !== 'failure') { + dispatch({ type: 'end', id, end: { kind: 'cut' } }); } } catch (error) { if (abort.signal.aborted) { @@ -111,18 +263,53 @@ export function ConversationProvider({ message: error instanceof Error ? error.message : String(error), }, }); - await refreshStatus(); } finally { if (running.current?.id === id) { running.current = null; + void queries.invalidateQueries({ + queryKey: agentSessionsKey(httpBase, environment), + }); } } - })(); + }; + void start(); }, [client, httpBase, queries], ); - const value = useMemo(() => ({ turns, ask }), [turns, ask]); + const remove = useCallback(async () => { + const { environment, session } = current.current; + if (environment === null || session === null) { + return; + } + if (running.current !== null) { + running.current.abort.abort(); + dispatch({ type: 'end', id: running.current.id, end: { kind: 'stopped' } }); + running.current = null; + } + await client.deleteAgentSession(environment, session); + current.current = { environment, session: null }; + setOpened({ environment, session: null }); + setOwned(null); + setMissing(false); + dispatch({ type: 'restore', turns: [] }); + void queries.invalidateQueries({ + queryKey: agentSessionsKey(httpBase, environment), + }); + }, [client, httpBase, queries]); + + const value = useMemo( + () => ({ + session: opened.session, + sessions: sessions.data ?? [], + turns, + missing, + ask, + open, + remove, + }), + [opened.session, sessions.data, turns, missing, ask, open, remove], + ); return {children}; } diff --git a/projects/compass.web/packages/pages/src/i18n/en.ts b/projects/compass.web/packages/pages/src/i18n/en.ts index 9ad4dddd..cff34a96 100644 --- a/projects/compass.web/packages/pages/src/i18n/en.ts +++ b/projects/compass.web/packages/pages/src/i18n/en.ts @@ -457,6 +457,17 @@ export const en: Catalogue = { question: 'Ask the compass agent', ask: 'Ask', close: 'Close the compass agent', + sessions: { + label: 'Conversation', + none: 'No conversation', + create: 'New conversation', + untitled: 'Untitled conversation', + delete: 'Delete conversation', + confirmDelete: 'Delete this conversation and its turns?', + missing: + 'This conversation is not available to you in this view. Choose another, or start a new one.', + failed: 'compass.http did not answer the conversation: {reason}', + }, statusReading: "Reading the agent's status…", statusFailed: "compass.http did not answer the agent's status: {reason}", statusUnreadable: diff --git a/projects/compass.web/packages/pages/src/i18n/fr.ts b/projects/compass.web/packages/pages/src/i18n/fr.ts index c1635261..031ccade 100644 --- a/projects/compass.web/packages/pages/src/i18n/fr.ts +++ b/projects/compass.web/packages/pages/src/i18n/fr.ts @@ -468,6 +468,17 @@ const fr: Catalogue = { question: "Poser une question à l'agent de compass", ask: 'Demander', close: "Fermer l'agent de compass", + sessions: { + label: 'Conversation', + none: 'Aucune conversation', + create: 'Nouvelle conversation', + untitled: 'Conversation sans titre', + delete: 'Supprimer la conversation', + confirmDelete: 'Supprimer cette conversation et ses échanges ?', + missing: + "Cette conversation ne vous est pas accessible dans cette vue. Choisissez-en une autre ou commencez-en une nouvelle.", + failed: "compass.http n'a pas répondu pour la conversation : {reason}", + }, statusReading: "Lecture de l'état de l'agent…", statusFailed: "compass.http n'a pas répondu avec l'état de l'agent : {reason}", statusUnreadable: diff --git a/projects/compass.web/packages/pages/src/i18n/pt.ts b/projects/compass.web/packages/pages/src/i18n/pt.ts index 5eced1be..e29fd912 100644 --- a/projects/compass.web/packages/pages/src/i18n/pt.ts +++ b/projects/compass.web/packages/pages/src/i18n/pt.ts @@ -464,6 +464,17 @@ const pt: Catalogue = { question: 'Perguntar ao agente do compass', ask: 'Perguntar', close: 'Fechar o agente do compass', + sessions: { + label: 'Conversa', + none: 'Nenhuma conversa', + create: 'Nova conversa', + untitled: 'Conversa sem título', + delete: 'Eliminar conversa', + confirmDelete: 'Eliminar esta conversa e os seus turnos?', + missing: + 'Esta conversa não está disponível para si nesta vista. Escolha outra ou comece uma nova.', + failed: 'O compass.http não respondeu sobre a conversa: {reason}', + }, statusReading: 'A ler o estado do agente…', statusFailed: 'O compass.http não respondeu com o estado do agente: {reason}', statusUnreadable: diff --git a/projects/compass.web/packages/pages/src/pages.test.tsx b/projects/compass.web/packages/pages/src/pages.test.tsx index 96982f07..621a4dc1 100644 --- a/projects/compass.web/packages/pages/src/pages.test.tsx +++ b/projects/compass.web/packages/pages/src/pages.test.tsx @@ -301,6 +301,13 @@ describe("the pages' addresses", () => { ); }); + it('name a conversation with the agent in the query', () => { + expect(linkTo({ environment: 'compass', screen: 'agent', session: 7 })).toBe( + '/compass/agent?session=7', + ); + expect(linkTo({ environment: 'compass', screen: 'agent' })).toBe('/compass/agent'); + }); + it('open a scenario by its :ID:, with the view of it and the run it shows', () => { expect(linkTo({ environment: 'compass', screen: 'testing', scenario: 'SC 1' })).toBe( '/compass/scenarios/SC%201', diff --git a/projects/compass.web/packages/pages/src/pages.tsx b/projects/compass.web/packages/pages/src/pages.tsx index c259423a..4a2b49fe 100644 --- a/projects/compass.web/packages/pages/src/pages.tsx +++ b/projects/compass.web/packages/pages/src/pages.tsx @@ -60,12 +60,16 @@ export function compassRoutes(): RouteObject[] { * The address of a place in compassRoutes(), from where the host mounts them: * /{environment}/{screen}, for a document /{environment}/docs/{id}#{anchor}, * by its :ID:, never its path, for a sprint other than the present one - * /{environment}/{screen}?sprint={id}, and for a scenario - * /{environment}/scenarios/{id}?tab={tab}&run={run}. A host that mounts the + * /{environment}/{screen}?sprint={id}, for a scenario + * /{environment}/scenarios/{id}?tab={tab}&run={run}, and for a conversation + * with the agent /{environment}/agent?session={id}. A host that mounts the * pages under a path of its own puts that path in front. */ export function linkTo(place: Place): string { const environment = `/${encodeURIComponent(place.environment)}`; + if ('session' in place) { + return `${environment}/agent?${new URLSearchParams({ session: String(place.session) })}`; + } if ('document' in place) { const anchor = place.anchor === undefined ? '' : `#${encodeURIComponent(place.anchor)}`; return `${environment}/docs/${encodeURIComponent(place.document)}${anchor}`; diff --git a/projects/compass.web/packages/web/e2e/agent.spec.ts b/projects/compass.web/packages/web/e2e/agent.spec.ts index 5986d888..be9cc47f 100644 --- a/projects/compass.web/packages/web/e2e/agent.spec.ts +++ b/projects/compass.web/packages/web/e2e/agent.spec.ts @@ -58,6 +58,7 @@ test('an answer streams with its citations, and a citation opens the document at "The lighthouse keeper's log records the weather", ); await expect(turn.getByTestId('agent-status')).toContainText('Answered in'); + await expect(page).toHaveURL(new RegExp(`/${environment}/agent\\?session=\\d+$`)); const asked = await (await request.get(`${STUB}/__last`)).json(); expect(JSON.stringify(asked)).toContain("the lighthouse keeper's log records the weather"); @@ -95,6 +96,66 @@ test('an answer streams with its citations, and a citation opens the document at await expect(page.getByTestId('agent-turn').first()).toContainText( "What does the lighthouse keeper's log record?", ); + + const with_history = await (await request.get(`${STUB}/__last`)).json(); + const messages = with_history.messages as { role: string; content: string }[]; + const first = messages.find( + (m) => m.role === 'user' && m.content === "What does the lighthouse keeper's log record?", + ); + expect(first).toBeDefined(); + expect(messages.some((m) => m.role === 'assistant' && m.content.includes('[cited earlier]'))).toBe( + true, + ); +}); + +test('a reload restores the conversation, and deleting it removes it', async ({ page }) => { + const environment = await environmentOf(page); + await page.goto(`/${environment}/agent`); + await ask(page, "What does the lighthouse keeper's log record?"); + const turn = page.getByTestId('agent-turn').last(); + await expect(turn.getByTestId('agent-status')).toContainText('Answered in'); + const saved = page.url(); + expect(saved).toMatch(/\?session=\d+$/); + + await page.reload(); + const restored = page.getByTestId('agent-turn').last(); + await expect(restored.getByTestId('agent-answer')).toContainText( + "The lighthouse keeper's log records the weather", + ); + await expect(restored.getByTestId('agent-source')).toHaveCount(1); + await expect(restored.getByTestId('agent-times')).toContainText('first token after'); + + page.on('dialog', (dialog) => void dialog.accept()); + await page.getByRole('button', { name: 'Delete conversation' }).click(); + await expect(page).toHaveURL(`/${environment}/agent`); + await expect(page.getByTestId('agent-turn')).toHaveCount(0); + + await page.reload(); + await expect(page.getByTestId('agent-turn')).toHaveCount(0); +}); + +test('an abandoned answer restores as stopped with its partial text', async ({ + page, + request, +}) => { + expect((await request.post(`${STUB}/__slow`)).ok()).toBe(true); + const environment = await environmentOf(page); + await page.goto(`/${environment}/agent`); + await ask(page, "What does the lighthouse keeper's log record?"); + const turn = page.getByTestId('agent-turn').last(); + await expect(turn.getByTestId('agent-answer')).toContainText("The lighthouse keeper's log"); + await expect(page).toHaveURL(new RegExp(`/${environment}/agent\\?session=\\d+$`)); + + await page.reload(); + const restored = page.getByTestId('agent-turn').last(); + await expect(restored.getByTestId('agent-status')).toContainText('Stopped', { + timeout: 15_000, + }); + await expect(restored.getByTestId('agent-answer')).toContainText( + "The lighthouse keeper's log", + ); + await expect(restored.getByTestId('agent-failure')).toHaveCount(0); + expect((await request.post(`${STUB}/__fast`)).ok()).toBe(true); }); test('the agent beside another screen keeps its conversation as the person moves', async ({ diff --git a/projects/compass.web/packages/web/e2e/llama_stub.mjs b/projects/compass.web/packages/web/e2e/llama_stub.mjs index ac893ab3..fddd9495 100644 --- a/projects/compass.web/packages/web/e2e/llama_stub.mjs +++ b/projects/compass.web/packages/web/e2e/llama_stub.mjs @@ -36,6 +36,8 @@ const NO_MATCH = [ ]; let last = null; +let firstTokenMs = FIRST_TOKEN_MS; +let betweenMs = BETWEEN_TOKENS_MS; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -82,10 +84,10 @@ async function complete(request, response) { Connection: 'keep-alive', }); const send = (chunk) => response.write(`data: ${JSON.stringify(chunk)}\n\n`); - await wait(FIRST_TOKEN_MS); + await wait(firstTokenMs); for (const piece of pieces) { send({ choices: [{ index: 0, delta: { content: piece }, finish_reason: null }] }); - await wait(BETWEEN_TOKENS_MS); + await wait(betweenMs); } send({ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], timings }); response.end('data: [DONE]\n\n'); @@ -105,6 +107,16 @@ const server = createServer((request, response) => { case 'GET /__last': json(response, 200, last); return; + case 'POST /__slow': + firstTokenMs = 500; + betweenMs = 700; + json(response, 200, { slow: true }); + return; + case 'POST /__fast': + firstTokenMs = FIRST_TOKEN_MS; + betweenMs = BETWEEN_TOKENS_MS; + json(response, 200, { slow: false }); + return; case 'POST /__quit': json(response, 200, { quitting: true }); server.close(); From 8c1ea850810f81c7546afc7452438311eed54a2e Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:38:20 +0000 Subject: [PATCH 06/24] [agile] Record the agent's server-owned conversations Add the task that stores and restores the agent's conversations, its six delivery units, the measurements from the release build and the product calls still open, and list it in the story. The gateway tests prove a team session is invisible to the knowledge view and another subject, that a knowledge-view transcript names no sprint page, that the ask needs the gateway's CSRF headers, and that delete belongs to its owner. Co-Authored-By: Claude Code --- .../build_the_compass_web_front_end/story.org | 11 +- ..._store_and_restore_agent_conversations.org | 198 ++++++++++++++++++ .../packages/web/gateway/gateway.spec.ts | 145 +++++++++++++ 3 files changed, 349 insertions(+), 5 deletions(-) create mode 100644 doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org index 497721bc..b5566114 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org @@ -7,7 +7,7 @@ #+level: s2 #+filetags: :docs:ui:service:sprint_01:v0: #+created: 2026-11-29 -#+updated: 2026-12-01 +#+updated: 2026-12-02 #+environment: #+todo: BACKLOG STARTED | DONE ABANDONED @@ -39,10 +39,10 @@ its own documentation screens in its favour. |---------------+----------------------------------------| | State | STARTED | | Parent sprint | [[id:850C1BC8-FE02-4EE0-A5D6-6085DC34CE27][Sprint 1]] | -| Now | Captured with its tasks. Rename, the OpenAPI document and the inventory are done. Prototype the shell and the document view (#234), Prototype the link graph in WebGL (#236), Prototype the agent panel on llama.cpp (#237) and Prototype the sprint and testing views (#239) are signed off. Stand up compass.web on the ores.web stack (#241) is signed off: compass serve serves compass.web. Search the documents in the browser (#242) is signed off with decision 10's ranking. Read a document in the browser (#243) is signed off and merged. Retire the HTML document route (#244) is signed off and merged. Show the sprint board, its stories and its tasks (#246) is signed off and merged. Draw the sprint charts (#247) is signed off and merged. Run test scenarios with screenshots in the browser (#248) is signed off and merged. Draw the link graph in WebGL (#249) is signed off and merged. Talk to the compass agent in the browser (#252) is signed off and merged. Serve compass behind ORE Studio's gateway (#254) is signed off and merged. Open compass.web from ores.web (#256) is signed off and merged. Publish the developer link (#257) merged the packaging and install work; the team address remains the product owner's. Suggest searches and offer an AI mode (#259) is STARTED: the landing page keeps its box centered while typing, lists the closest documents in a combo box, and hands the typed query to the agent from AI mode. The agent's retrieval dropped compass itself; the fix is in review. The agent's model server runs as a tracked systemd user unit on the GPU with Qwen3.5-9B; verified, waiting on the product owner's sign-off. | -| Waiting on | The product owner's team address for compass.web. | -| Next | Publish the developer link once the address is decided. | -| Last touched | 2026-12-01 | +| Now | Captured with its tasks. Rename, the OpenAPI document and the inventory are done. Prototype the shell and the document view (#234), Prototype the link graph in WebGL (#236), Prototype the agent panel on llama.cpp (#237) and Prototype the sprint and testing views (#239) are signed off. Stand up compass.web on the ores.web stack (#241) is signed off: compass serve serves compass.web. Search the documents in the browser (#242) is signed off with decision 10's ranking. Read a document in the browser (#243) is signed off and merged. Retire the HTML document route (#244) is signed off and merged. Show the sprint board, its stories and its tasks (#246) is signed off and merged. Draw the sprint charts (#247) is signed off and merged. Run test scenarios with screenshots in the browser (#248) is signed off and merged. Draw the link graph in WebGL (#249) is signed off and merged. Talk to the compass agent in the browser (#252) is signed off and merged. Serve compass behind ORE Studio's gateway (#254) is signed off and merged. Open compass.web from ores.web (#256) is signed off and merged. Publish the developer link (#257) merged the packaging and install work; the team address remains the product owner's. Suggest searches and offer an AI mode (#259) is STARTED: the landing page keeps its box centered while typing, lists the closest documents in a combo box, and hands the typed query to the agent from AI mode. The agent's retrieval dropped compass itself; the fix is in review. The agent's model server runs as a tracked systemd user unit on the GPU with Qwen3.5-9B; verified, waiting on the product owner's sign-off. Store and restore the agent's conversations is STARTED: built and verified in six units on =feature/agent-sessions=, in a pull request awaiting review and the product owner's sign-off. | +| Waiting on | The product owner's team address for compass.web, and the sign-off of the agent's server-owned conversations. | +| Next | Review the agent sessions' pull request and sign it off; publish the developer link once the address is decided. | +| Last touched | 2026-12-02 | * Acceptance @@ -111,6 +111,7 @@ its own documentation screens in its favour. | [[id:D6F014EB-CB9F-44D6-B14A-9544B2691943][Serve compass behind ORE Studio's gateway]] | DONE | 2026-12-01 | 2026-12-01 | Run compass.http behind ores.http as its gateway and compass.web inside ores.web on ores.web's session, while compass on its own keeps running with no sign-in, and hand ORE Studio the forwarder and view mapping its side needs. | | [[id:44146C3F-FE10-4832-9311-7C2A87D17CDC][Open compass.web from ores.web]] | DONE | 2026-12-01 | 2026-12-01 | Make compass.web reachable from ores.web: first an external menu entry, then compass.web's pages as a package ores.web adds as a dependency and mounts, reading compass through ores.http, so ORE Studio can decommission its own documentation screens. | | [[id:131CF0B6-CF93-40A0-A6AC-4635F4A3CE8A][Publish the developer link]] | STARTED | 2026-12-01 | | Run compass.web for the team at a stable address, link it from compass's developer pages, and ship its built files with compass's releases. | +| [[id:CE6EDA24-65B9-4D57-96F8-640DDE04324B][Store and restore the agent's conversations]] | STARTED | 2026-12-02 | | Make the agent's conversations server-owned: two retained tables in a new =agent= schema, a session ask that writes the question before it streams and settles the answer off the io thread, done-only history and follow-up retrieval in the prompt, and a browser that opens, restores and deletes a conversation by its id. | | [[id:DF412233-B923-4151-A9B7-D896688F7C83][Offer the compass agent as an MCP tool]] | BACKLOG | | | Explore offering the compass agent as an MCP tool that runs the same loop as the panel's stream and returns the whole answer with its citations at once, and settle the timeouts a CPU model needs and whether an MCP caller with a model of its own needs it. | | [[id:D7A2C472-466E-42AB-AF5D-3D21FC46BBC2][Suggest searches and offer an AI mode]] | STARTED | 2026-12-01 | | Keep the landing page's box centered and its address unchanged while the person types, list the closest documents in a debounced combo box, and add an AI mode that takes the typed query to the agent screen. | diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org new file mode 100644 index 00000000..26a1960c --- /dev/null +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -0,0 +1,198 @@ +:PROPERTIES: +:ID: CE6EDA24-65B9-4D57-96F8-640DDE04324B +:END: +#+title: Task: Store and restore the agent's conversations +#+description: Make the compass agent's conversations server-owned: two retained tables in a new agent schema, a session ask that writes the question before it streams and settles the answer off the io thread, history and follow-up retrieval in the prompt, and a browser that opens, restores and deletes a conversation by its id. +#+type: task +#+level: s1 +#+filetags: :build_the_compass_web_front_end:sprint_01:v0: +#+owner: marco +#+branch: feature/agent-sessions +#+pr: +#+blocked_on: +#+blocked_since: +#+created: 2026-12-02 +#+updated: 2026-12-02 +#+environment: +#+todo: DISCOVERED BACKLOG STARTED BLOCKED | DONE ABANDONED + +This page documents a [[id:31C868B9-306E-4282-BA8C-07E647021B34][task]] in the [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] story. It captures the goal, current status, acceptance, and any notes or results. + +* Goal + +A conversation with the compass agent belongs to the service, not to the +browser tab. A reload, a second tab and a later visit open the same +transcript, and the follow-up question is answered with the conversation +before it as context, so "and why?" means something. + +The product direction is server-owned sessions: a conversation belongs to +the caller's environment, subject and view, and restoring it requires the +same triple. Sign-off by the product owner is pending. + +* Status + +| Field | Value | +|--------------+----------------------------------------| +| State | STARTED | +| Parent story | [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] | +| Now | Built and verified in six units, in a pull request awaiting review and the product owner's sign-off. Nothing is merged. | +| Waiting on | The product owner's sign-off, and the answer to the open product calls below. | +| Next | Review the pull request; then the product owner's calls on retention and audit. | +| Last touched | 2026-12-02 | + +* Acceptance + +- A conversation and its turns live in the database and exist nowhere else: + =agent.agent_session= and =agent.agent_turn= in a new =agent= schema, both + retained under the profile =conversation-record=, added by migration 7. +- Every read, ask and delete is filtered by the caller's environment, subject + and view name in SQL; a mismatch answers as an absent row, 404 for a read, + ask or delete, absent from a list. +- The ask is a streamed =POST= that writes. The question and the exact + =passages= event are inserted on the handler's worker thread before the + stream opens; the answer is settled by a terminal sink that enqueues to one + writer thread, so no database work runs on the connection's io thread. +- A client that leaves records =stopped= with the partial answer; a restart + turns a leftover =streaming= row into =cut=; a partial snapshot is taken at + most every two seconds, so a crash restores the last partial. +- The prompt gives the model the newest done exchanges, at most eight and + within a byte budget reserved from the context window; prior citations are + neutralised to =[cited earlier]=; a question with no keywords searches with + the previous question's; with no passages but a history the model is told + to answer from the conversation. +- The browser names its conversation in the address as =?session=, restores + the transcript from the stored events (answers, citations, sources and + timings), starts and deletes conversations, and polls an unfinished turn + that another tab or a lost stream left =streaming=, bounded at 15 minutes. +- The gateway tests prove the view and subject isolation and the gateway's + CSRF rule over the ask; the shell test drives the real page in Chromium. + +* Plan + +The design was chosen in an arena and synthesized in +=/tmp/arena-agent-sessions/synthesis.md=; the base package is +=/tmp/arena-agent-sessions/candidate-sonnet/design.md=. The load-bearing +decisions: + +- *A separate =agent= schema*, not =activity=: chat is a different domain + from test campaigns, with its own profile, =conversation-record=, retained. +- *One row per exchange*, not per message: the row is the browser's =Turn= + and the model's history entry, and the stored =retrieval=, =done= and + =failure= are the events the live stream sent, because the handler builds + one =agent_passages_event= and serialises it for both. +- *A streamed writing POST*, admitted by an explicit codegen change: the + parser allows =:stream:= with =:writes:= on a POST and no =:response:=; + the router's catalogue records =stream= and admits it, while still + refusing a stream that is a tool or writes as another method. The + stateless =GET /v1/{environment}/agent?q== stays. +- *The question on the worker, the answer off the io thread*: the handler's + short transaction locks the session, numbers the exchange and inserts it + =streaming=; the stream's terminal sink enqueues to a =turn_writer=, which + drains through the pool in short transactions. A failed terminal write + leaves the row =streaming=, and startup recovery cuts it. +- *Done-only history*: a cut, stopped or failed partial never becomes a + premise; the SQL reads =status = 'done'= only. The window is 8 exchanges + and the context-reserve byte budget, + =min(24k, (context_tokens - max_answer_tokens) * 4 - system - user - slack)= + with =context_tokens= 65536. +- *The view name, not a document, is the scoping anchor*: the live retrieval + uses the same =view_filter= as the search route, so current passages are + inside the caller's view, and the stored history is the caller's own. + +* Delivery order + +One branch, =feature/agent-sessions=, cut from =origin/main=, with one +verifiable commit per unit: + +1. =2ca641c2= [db] The two entity models, =compass generate=, migration 7 + with the generated DDL verbatim, the profile page, the schema and component + overviews, and the generated row codecs in CMake. Nothing behavioural. +2. =ccf87819= [codegen] The streamed-POST change alone: parser, router gate, + catalogue =stream= flag, templates and tangled mustache, regenerated + routes, and the parser and router-gate tests. +3. =f0eef5d7= [http] The session routes and the operation model; the query + layer with the triple in every statement; the terminal sink and writer + thread; startup recovery; the ask handler's question write; the stream's + partial snapshots and =stopped=; the isolation and lifecycle tests. +4. =c56c1bff= [http] History, citation neutralisation, the context-reserve + budget, the follow-up retrieval fallback, the no-match-with-history + prompt, =agent_settings.context_tokens= 65536 and =start_command=. +5. =408cec47= [web] Create, list, restore and delete sessions; =?session= in + the address; =turnsOf= rebuilding the =Turn[]= from the stored events; + StrictMode-safe restore; the bounded unfinished-turn poll; i18n; unit and + Playwright tests. +6. This commit: the gateway view/subject isolation and CSRF tests, and the + task and story documents. + +* Measurements + +Measured on 2026-12-02, from a release build +(=linux-clang-release-ninja=) in the worktree: + +| What | Result | +|------+--------| +| =compass.db.tests "[migrations]"= | 144 assertions in 5 cases, green: migration 7 builds the catalog =schema.sql= builds | +| =compass.db.tests "agent_*"= | 42 assertions in 6 cases, green: both new row codecs round-trip and their schemas | +| =compass.model.tests "[masd]"= | 106 assertions in 15 cases, green: the streamed POST parses, the streamed PUT and the named response are refused | +| =compass.http.tests= | 385 cases, 9674 assertions, green: the session lifecycle, isolation, writer, prompt and sink, plus regenerated counts 21 read routes and 31 write/tool routes | +| =@compass/pages= vitest | 241 tests in 11 files, green; =@compass/web= 3 tests | +| =shell_test.sh= (real Chromium) | 40 Playwright tests, green, including session create, restore, history in the llama body, delete and an abandoned stream restored as stopped | +| =gateway_test.sh= | 49 Playwright tests, green: a team session is invisible to the knowledge view and another subject; the knowledge view's transcript names no sprint page; the ask needs the gateway's =X-Ores-Request= and matching =Origin=; delete is 204 twice for its owner and 404 for another | +| History budget | 65,536-token context, 400 max answer tokens and about 2,000 bytes of system and current user leave the 24,000-byte ceiling binding: 24,000 bytes of history | +| Startup command | =llama-server … --ctx-size 65536 …= | + +* Open product calls + +Recorded, not decided, pending the product owner: + +- *Retention.* No expiry, with an explicit delete, is the default built; an + age or size policy would be a new migration and sweep. +- *Auto-open.* The screen shows the list with a new-conversation control + rather than opening the last conversation; either is a small change. +- *View drift.* A conversation is bound to the view name; if the definition + behind that name changes, old answers can name documents the new definition + excludes. A =view_digest= on the session, refused on restore when it + differs, is the optional hardening and is not built. +- *Environment deletion.* The environment is a text name, so conversations + outlive it, as campaigns do; deleting them with it would need a reference. +- *Abort and crash statuses.* The client leaving records =stopped= and a + crash records =cut=. Whether a person's abort should be distinguished from + a crash in the UI is not settled. +- *Audit.* No =activity.action= row is written for create, delete or ask; + the session and turn rows are their own record. A delete tombstone or the + action rows would be migration churn for no read path today. +- *Auto-title.* A conversation without a given title takes the first 80 code + points of its first question; renaming is not built. +- *One ask at a time.* The UI aborts the previous ask; a server-enforced rule + could turn an abort race into a false 409, so it is not built. + +* Notes + +- The migration is unreleased, so the retained-table test skips the new + tables until a release includes them; that release pins migration 7's hash + and adds both tables to =released_retained=. +- Prompt-cache reuse is a benefit, not a guarantee: the stored question is + bare (the passages are not stored), so reuse stops at the previous + exchange. +- The writer's queue is bounded at 64 and drops with a count and a log line + that names the turn, never the text. + +* Related captures + +- [[id:A4FFB55D-43E3-4E2E-AA22-2503F0A49090][Talk to the compass agent in the browser]]: the stateless agent this task + makes session-aware. +- [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]]: the story. +- [[id:C1DC377F-4A1B-4131-B734-FE28DB63CF03][Serve the documents]]: the query layer and views the retrieval reuses. +- [[id:E3C81059-FE00-4403-AA56-190FDBB9904A][Own the MASD meta model and generate compass with it]]: the operation + model and generated routes. + +* Result + +Built in six commits on =feature/agent-sessions=, each verified before the +next, and pushed in a pull request that is not merged. Migration 7 builds +the catalog =schema.sql= builds; the parser and router gates admit the +streamed writing POST and refuse the shapes they should; the session +isolation, lifecycle, writer and prompt tests pass; the web's unit, browser +and gateway tests pass. The product owner's sign-off and the open product +calls are outstanding. + diff --git a/projects/compass.web/packages/web/gateway/gateway.spec.ts b/projects/compass.web/packages/web/gateway/gateway.spec.ts index a7b0d908..5e817496 100644 --- a/projects/compass.web/packages/web/gateway/gateway.spec.ts +++ b/projects/compass.web/packages/web/gateway/gateway.spec.ts @@ -488,6 +488,10 @@ test.describe('a run of a scenario the knowledge view does not hold', () => { test("through /mcp, the knowledge view's tools find no sprint page, and the team's do", async () => { const r = recorded; + const developerHttp = await as('developer'); + const made = await write(developerHttp, 'POST', v1('agent/sessions'), { title: 'MCP' }); + expect(made.status(), await made.text()).toBe(200); + const mcpSession = ((await json(made)) as { session: number }).session; const reads: Readonly< Record< string, @@ -530,6 +534,8 @@ test.describe('a run of a scenario the knowledge view does not hold', () => { get_version: { args: {}, aboutTheService: true }, get_agent: { args: {}, agentDetails: true }, get_catalogue: { args: {}, aboutTheService: true }, + list_agent_sessions: { args: {} }, + get_agent_session: { args: { session: mcpSession }, refusedAs: 'not_found' }, }; const writes: Readonly> = { start_run: { scenario_id: SCENARIO }, @@ -551,7 +557,12 @@ test.describe('a run of a scenario the knowledge view does not hold', () => { text: 'x', }, address_note: { note: r.note, reply: 'x' }, + create_agent_session: { title: 'MCP' }, + delete_agent_session: { session: 0 }, }; + // A conversation belongs to no campaign, so the reader may make and + // delete its own; the campaign writes are the ones scoped to it. + const NO_CAMPAIGN = new Set(['create_agent_session', 'delete_agent_session']); const NOT_A_VIEWS_MATTER = new Set(['sync_environment']); const OF_EVERY_ENVIRONMENT = new Set([ 'list_environments', @@ -615,6 +626,9 @@ test.describe('a run of a scenario the knowledge view does not hold', () => { ).not.toEqual([]); } for (const [name, args] of Object.entries(writes)) { + if (NO_CAMPAIGN.has(name)) { + continue; + } const refused = await reader.call(name, { ...args, environment: ENVIRONMENT }); expect(refused.isError, name).toBe(true); expect(refused.answer, name).toMatchObject({ code: 'not_found' }); @@ -755,3 +769,134 @@ test.describe("compass.web's pages, installed from their tarball, in a host shap expect(page.url()).toBe(at); }); }); + +test.describe("the agent's conversations", () => { + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + + async function made(people: APIRequestContext, title?: string): Promise { + const answer = await write( + people, + 'POST', + v1('agent/sessions'), + title === undefined ? {} : { title }, + ); + expect(answer.status(), await answer.text()).toBe(200); + return ((await json(answer)) as { session: number }).session; + } + + async function asked( + people: APIRequestContext, + session: number, + question: string, + ): Promise { + const answer = await write(people, 'POST', v1(`agent/sessions/${session}/ask`), { + q: question, + }); + expect(answer.status(), await answer.text()).toBe(200); + await answer.text(); + } + + interface StoredTurn { + readonly status: string; + readonly retrieval: { + readonly passages: readonly { readonly title: string; readonly path: string }[]; + }; + } + + /** The stored conversation once no turn still streams. */ + async function stored( + people: APIRequestContext, + session: number, + ): Promise<{ readonly turns: readonly StoredTurn[] }> { + for (let attempt = 0; attempt < 100; ++attempt) { + const read = await people.get(v1(`agent/sessions/${session}`)); + expect(read.status(), await read.text()).toBe(200); + const body = (await json(read)) as { readonly turns: readonly StoredTurn[] }; + if (body.turns.every((turn) => turn.status !== 'streaming')) { + return body; + } + await sleep(100); + } + throw new Error('the turn did not settle'); + } + + test('belong to the view and subject that made them, and are no one else’s', async () => { + const developer = await as('developer'); + const reader = await as('reader'); + const session = await made(developer); + await asked(developer, session, 'lighthouse lamp wick brass'); + + const read = await stored(developer, session); + expect(read.turns[0]?.retrieval.passages.map((p) => p.title)).toContain( + 'Task: Light the lamp', + ); + + expect((await reader.get(v1(`agent/sessions/${session}`))).status()).toBe(404); + const list = (await json(await reader.get(v1('agent/sessions')))) as { + sessions: { session: number }[]; + }; + expect(list.sessions.map((s) => s.session)).not.toContain(session); + expect( + (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), + ).toBe(404); + expect( + ( + await write(reader, 'POST', v1(`agent/sessions/${session}/ask`), { + q: 'and why?', + }) + ).status(), + ).toBe(404); + }); + + test('from the knowledge view never name a sprint page, and follow the subject', async () => { + const reader = await as('reader'); + const agent = await as('agent'); + const developer = await as('developer'); + const session = await made(reader); + await asked(reader, session, 'lighthouse lamp wick brass'); + + const transcript = JSON.stringify(await stored(reader, session)); + expect(transcript).not.toContain('Task: Light the lamp'); + expect(transcript).not.toContain('Sprint 1'); + + // The same subject and view, through an agent acting for them, reads it. + expect((await agent.get(v1(`agent/sessions/${session}`))).status()).toBe(200); + // Another subject and view does not. + expect((await developer.get(v1(`agent/sessions/${session}`))).status()).toBe(404); + }); + + test("ask with a POST only with the gateway's CSRF headers", async () => { + const reader = await as('reader'); + const session = await made(reader); + const path = v1(`agent/sessions/${session}/ask`); + const withoutRequest = await reader.post(path, { data: { q: 'why?' } }); + expect(withoutRequest.status()).toBe(403); + expect(await json(withoutRequest)).toMatchObject({ + message: 'A session request must carry the X-Ores-Request header', + }); + const withoutOrigin = await reader.post(path, { + headers: { 'X-Ores-Request': '1' }, + data: { q: 'why?' }, + }); + expect(withoutOrigin.status()).toBe(403); + expect(await json(withoutOrigin)).toMatchObject({ + message: 'A session request must carry an Origin', + }); + }); + + test('is deleted by its owner, twice, and gone from the list', async () => { + const reader = await as('reader'); + const session = await made(reader, 'To delete'); + expect( + (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), + ).toBe(204); + expect((await reader.get(v1(`agent/sessions/${session}`))).status()).toBe(404); + expect( + (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), + ).toBe(204); + const list = (await json(await reader.get(v1('agent/sessions')))) as { + sessions: { session: number }[]; + }; + expect(list.sessions.map((s) => s.session)).not.toContain(session); + }); +}); From 8b0fce3ed08e598e8622ee6dff810349ca8052be Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:39:33 +0000 Subject: [PATCH 07/24] [agile] Name the agent sessions' pull request, 262 Co-Authored-By: Claude Code --- .../v0/sprint_01/build_the_compass_web_front_end/story.org | 2 +- .../task_store_and_restore_agent_conversations.org | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org index b5566114..6aba7d6f 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org @@ -41,7 +41,7 @@ its own documentation screens in its favour. | Parent sprint | [[id:850C1BC8-FE02-4EE0-A5D6-6085DC34CE27][Sprint 1]] | | Now | Captured with its tasks. Rename, the OpenAPI document and the inventory are done. Prototype the shell and the document view (#234), Prototype the link graph in WebGL (#236), Prototype the agent panel on llama.cpp (#237) and Prototype the sprint and testing views (#239) are signed off. Stand up compass.web on the ores.web stack (#241) is signed off: compass serve serves compass.web. Search the documents in the browser (#242) is signed off with decision 10's ranking. Read a document in the browser (#243) is signed off and merged. Retire the HTML document route (#244) is signed off and merged. Show the sprint board, its stories and its tasks (#246) is signed off and merged. Draw the sprint charts (#247) is signed off and merged. Run test scenarios with screenshots in the browser (#248) is signed off and merged. Draw the link graph in WebGL (#249) is signed off and merged. Talk to the compass agent in the browser (#252) is signed off and merged. Serve compass behind ORE Studio's gateway (#254) is signed off and merged. Open compass.web from ores.web (#256) is signed off and merged. Publish the developer link (#257) merged the packaging and install work; the team address remains the product owner's. Suggest searches and offer an AI mode (#259) is STARTED: the landing page keeps its box centered while typing, lists the closest documents in a combo box, and hands the typed query to the agent from AI mode. The agent's retrieval dropped compass itself; the fix is in review. The agent's model server runs as a tracked systemd user unit on the GPU with Qwen3.5-9B; verified, waiting on the product owner's sign-off. Store and restore the agent's conversations is STARTED: built and verified in six units on =feature/agent-sessions=, in a pull request awaiting review and the product owner's sign-off. | | Waiting on | The product owner's team address for compass.web, and the sign-off of the agent's server-owned conversations. | -| Next | Review the agent sessions' pull request and sign it off; publish the developer link once the address is decided. | +| Next | Review #262 and sign it off; publish the developer link once the address is decided. | | Last touched | 2026-12-02 | * Acceptance diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index 26a1960c..cad1c42a 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -8,7 +8,7 @@ #+filetags: :build_the_compass_web_front_end:sprint_01:v0: #+owner: marco #+branch: feature/agent-sessions -#+pr: +#+pr: 262 #+blocked_on: #+blocked_since: #+created: 2026-12-02 @@ -35,7 +35,7 @@ same triple. Sign-off by the product owner is pending. |--------------+----------------------------------------| | State | STARTED | | Parent story | [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] | -| Now | Built and verified in six units, in a pull request awaiting review and the product owner's sign-off. Nothing is merged. | +| Now | Built and verified in six units, in #262, awaiting review and the product owner's sign-off. Nothing is merged. | | Waiting on | The product owner's sign-off, and the answer to the open product calls below. | | Next | Review the pull request; then the product owner's calls on retention and audit. | | Last touched | 2026-12-02 | @@ -189,7 +189,7 @@ Recorded, not decided, pending the product owner: * Result Built in six commits on =feature/agent-sessions=, each verified before the -next, and pushed in a pull request that is not merged. Migration 7 builds +next, and pushed in #262, which is not merged. Migration 7 builds the catalog =schema.sql= builds; the parser and router gates admit the streamed writing POST and refuse the shapes they should; the session isolation, lifecycle, writer and prompt tests pass; the web's unit, browser From b3ffd00c4bdd9d31cbea1678d59215c3e0b1d560 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:40:28 +0000 Subject: [PATCH 08/24] [codegen] Expect a streamed route to state stream() The context test pinned the route template's old no_tool output. The streamed route now states stream() after no_tool(), so the test names it. Co-Authored-By: Claude Code --- projects/compass.codegen/tests/ops_masd_context_tests.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/projects/compass.codegen/tests/ops_masd_context_tests.cpp b/projects/compass.codegen/tests/ops_masd_context_tests.cpp index 0afce7e8..d1a54009 100644 --- a/projects/compass.codegen/tests/ops_masd_context_tests.cpp +++ b/projects/compass.codegen/tests/ops_masd_context_tests.cpp @@ -653,6 +653,7 @@ TEST_CASE("a streamed route's handler answers the response itself and it is " CHECK_THAT(impl, ContainsSubstring( " .input()\n" " .no_tool()\n" + " .stream()\n" " .handler(")); CHECK(impl.find("tool_call") == std::string::npos); CHECK(impl.find(".response<") == std::string::npos); From c69cb2bb48ff12c70f090879b16ddc71803d1d4a Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:42:39 +0000 Subject: [PATCH 09/24] [http] Wake every waiter when the writer takes a record The writer and a flush wait on one condition variable. A notify_one after enqueueing could wake the flush, which has nothing to do while the queue is not empty, and leave the writer asleep. notify_all wakes both. Co-Authored-By: Claude Code --- projects/compass.http/src/agent/turn_writer.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/projects/compass.http/src/agent/turn_writer.cpp b/projects/compass.http/src/agent/turn_writer.cpp index ce8f9977..b02c9de0 100644 --- a/projects/compass.http/src/agent/turn_writer.cpp +++ b/projects/compass.http/src/agent/turn_writer.cpp @@ -44,7 +44,10 @@ void turn_writer::push(queued_turn q) noexcept { const std::lock_guard lock(mutex_); if (queue_.size() < max_queued) { queue_.push_back(std::move(q)); - ready_.notify_one(); + // Both the writer and a flush wait here: notify_one could wake the + // flush, which has nothing to do while the queue is not empty, + // and leave the writer asleep. + ready_.notify_all(); return; } dropped_.fetch_add(1, std::memory_order_relaxed); From 2d5c6fc74b1ed9b2697af1c48f2805931edb578a Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:43:36 +0000 Subject: [PATCH 10/24] [agile] Record the agent sessions' two verification fixes Co-Authored-By: Claude Code --- .../task_store_and_restore_agent_conversations.org | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index cad1c42a..b40675da 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -124,6 +124,12 @@ verifiable commit per unit: 6. This commit: the gateway view/subject isolation and CSRF tests, and the task and story documents. +Two fixes came from the final pass. =c468f4cf= updated the codegen context +test that pinned the streamed route's old output; it now expects +=.no_tool()= and =.stream()=. =58505488= made the writer wake every waiter: +the writer and a flush share one condition variable, so a =notify_one= after +enqueueing could wake the flush and leave the writer asleep. + * Measurements Measured on 2026-12-02, from a release build @@ -188,8 +194,9 @@ Recorded, not decided, pending the product owner: * Result -Built in six commits on =feature/agent-sessions=, each verified before the -next, and pushed in #262, which is not merged. Migration 7 builds +Built in six units and two verification fixes on +=feature/agent-sessions=, each verified before the next, and pushed in #262, +which is not merged. Migration 7 builds the catalog =schema.sql= builds; the parser and router gates admit the streamed writing POST and refuse the shapes they should; the session isolation, lifecycle, writer and prompt tests pass; the web's unit, browser From f9cb18331fc8eb2567d2d448193c01c95ce3a98d Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:44:42 +0000 Subject: [PATCH 11/24] [http] Hold the session model to the service model checks The struct check pins the ten conversation messages, which compass.db does not own. The binding check learns agent_turn_status and names the two reads that take the subject, since a conversation belongs to a person as well as a view. The task records the rule extension. Co-Authored-By: Claude Code --- .../task_store_and_restore_agent_conversations.org | 6 ++++++ .../evidence/service_model_binding_check.py | 10 ++++++++-- .../evidence/service_model_struct_check.py | 7 +++++++ .../modeling/compass.http.agent_sessions.org | 1 - 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index b40675da..d0b5aabc 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -98,6 +98,11 @@ decisions: - *The view name, not a document, is the scoping anchor*: the live retrieval uses the same =view_filter= as the search route, so current passages are inside the caller's view, and the stored history is the caller's own. +- *A conversation's reads name the subject.* The meta-model's binding rule + was reads by view and writes by subject. A conversation also belongs to a + person, so =list_agent_sessions= and =get_agent_session= name the subject; + the binding check learns the two tools, and every SQL statement filters by + the triple. * Delivery order @@ -146,6 +151,7 @@ Measured on 2026-12-02, from a release build | =gateway_test.sh= | 49 Playwright tests, green: a team session is invisible to the knowledge view and another subject; the knowledge view's transcript names no sprint page; the ask needs the gateway's =X-Ores-Request= and matching =Origin=; delete is 204 twice for its owner and 404 for another | | History budget | 65,536-token context, 400 max answer tokens and about 2,000 bytes of system and current user leave the 24,000-byte ceiling binding: 24,000 bytes of history | | Startup command | =llama-server … --ctx-size 65536 …= | +| CI model checks | =service_model_struct_check.py= and =service_model_binding_check.py= pass: the ten new messages are pinned, =agent_turn_status= is known, and the two subject-scoped reads are named | * Open product calls diff --git a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_binding_check.py b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_binding_check.py index 472366bd..3bb5ecc0 100644 --- a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_binding_check.py +++ b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_binding_check.py @@ -20,7 +20,12 @@ "std::int32_t", "double", "bool"} ENUMS = {"scenario_state", "step_outcome", "run_outcome", "environment_kind", "error_code", "hit_kind", "disagreement_kind", - "agent_health"} + "agent_health", "agent_turn_status"} +# A conversation belongs to a subject as well as an environment and a view, +# so its reads name the subject too: a view alone cannot scope one person's +# chat, and a mismatch must answer as an absent row. Every other read is +# scoped by the view alone. +SUBJECT_READS = {"list_agent_sessions", "get_agent_session"} ROUTE_PROPS = ("tool", "area", "entity", "writes", "summary", "http_method", "http_path", "caller") ERROR_CODES = ["invalid", "no_view", "no_subject", "forbidden", "not_found", @@ -164,7 +169,8 @@ def check(msgs, fail): fail(f"{where}: read {tool} has no read prefix {READ_PREFIXES}") if writes == "true" and reads_by_name: fail(f"{where}: write {tool} is named as a read") - expected_caller = "subject" if writes == "true" else "view" + expected_caller = "subject" if writes == "true" or tool in SUBJECT_READS \ + else "view" if p.get("caller") != expected_caller: fail(f"{where}: :caller: {p.get('caller')}, want " f"{expected_caller}") diff --git a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py index 02362622..c1f5b260 100644 --- a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py +++ b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py @@ -54,6 +54,13 @@ "agent_request", "agent_status_request", "agent_status_response", "agent_passage", "agent_passages_event", "agent_token_event", "agent_done_event", "agent_failure_event", + # The agent's conversations; the query layer of compass.http owns them, + # and compass.db has no conversation. + "create_agent_session_request", "create_agent_session_response", + "list_agent_sessions_request", "agent_session_summary", + "list_agent_sessions_response", "get_agent_session_request", "agent_turn", + "get_agent_session_response", "delete_agent_session_request", + "agent_session_ask_request", } UNMODELLED = { diff --git a/projects/compass.http/modeling/compass.http.agent_sessions.org b/projects/compass.http/modeling/compass.http.agent_sessions.org index 46d2e4f5..6c326687 100644 --- a/projects/compass.http/modeling/compass.http.agent_sessions.org +++ b/projects/compass.http/modeling/compass.http.agent_sessions.org @@ -60,7 +60,6 @@ The environment the conversation belongs to. :PROPERTIES: :cpp_type: std::optional :http_in: body -:required: false :END: The conversation's title; absent or blank leaves it until the first From fb634a02f9252715d707748d416ca4edc5f550e8 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:47:02 +0000 Subject: [PATCH 12/24] [web] Open the panel on the screen's environment The panel's conversation list is per environment, so opening it beside a screen of another environment lists that one and leaves the conversation opened before. The Agent screen still names its conversation in the address and opens it after. Co-Authored-By: Claude Code --- .../compass.web/packages/pages/src/AgentPanel.tsx | 11 ++++++++++- .../compass.web/packages/pages/src/conversation.tsx | 5 ++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/projects/compass.web/packages/pages/src/AgentPanel.tsx b/projects/compass.web/packages/pages/src/AgentPanel.tsx index e73e6cf3..bdf90bf4 100644 --- a/projects/compass.web/packages/pages/src/AgentPanel.tsx +++ b/projects/compass.web/packages/pages/src/AgentPanel.tsx @@ -73,7 +73,7 @@ export function AgentPanel({ readonly onSessionDeleted?: () => void; }): ReactNode { const { t } = useTranslation(); - const { turns, ask, missing } = useConversation(); + const { turns, ask, missing, environment: openEnvironment, open } = useConversation(); const [draft, setDraft] = useState(''); const started = useRef(false); @@ -95,6 +95,15 @@ export function AgentPanel({ }; }, [ask, environment, initialQuestion]); + // The panel belongs to the screen's environment. Opening it beside a + // screen of another environment lists that environment's conversations + // and leaves the one open before, which belongs to the other. + useEffect(() => { + if (openEnvironment !== environment) { + open(environment, null); + } + }, [environment, openEnvironment, open]); + return (
({ + environment: opened.environment, session: opened.session, sessions: sessions.data ?? [], turns, @@ -308,7 +311,7 @@ export function ConversationProvider({ open, remove, }), - [opened.session, sessions.data, turns, missing, ask, open, remove], + [opened.environment, opened.session, sessions.data, turns, missing, ask, open, remove], ); return {children}; } From 6609eb60ddd4ee4a0777b86f607ff52e1ab7e201 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 11:52:34 +0000 Subject: [PATCH 13/24] [agile] Record the final-head verification and four fixes Co-Authored-By: Claude Code --- .../task_store_and_restore_agent_conversations.org | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index d0b5aabc..bd39a8de 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -129,11 +129,15 @@ verifiable commit per unit: 6. This commit: the gateway view/subject isolation and CSRF tests, and the task and story documents. -Two fixes came from the final pass. =c468f4cf= updated the codegen context -test that pinned the streamed route's old output; it now expects +Four fixes came from the final passes. =c468f4cf= updated the codegen +context test that pinned the streamed route's old output; it now expects =.no_tool()= and =.stream()=. =58505488= made the writer wake every waiter: the writer and a flush share one condition variable, so a =notify_one= after -enqueueing could wake the flush and leave the writer asleep. +enqueueing could wake the flush and leave the writer asleep. =56870961= +pinned the ten messages in the CI struct check and taught the binding check +=agent_turn_status= and the two subject-scoped reads. =f970a5ae= made the +panel open on the screen's environment, so the session list is the right +one before the first question. * Measurements @@ -152,6 +156,7 @@ Measured on 2026-12-02, from a release build | History budget | 65,536-token context, 400 max answer tokens and about 2,000 bytes of system and current user leave the 24,000-byte ceiling binding: 24,000 bytes of history | | Startup command | =llama-server … --ctx-size 65536 …= | | CI model checks | =service_model_struct_check.py= and =service_model_binding_check.py= pass: the ten new messages are pinned, =agent_turn_status= is known, and the two subject-scoped reads are named | +| Final-head rerun | =compass.db.tests= migrations 144 assertions in 5 cases and codecs 42 in 6; =compass.model.tests= 106 in 15; =compass.codegen.tests= 1957 in 185; =compass.cli.tests= 2754 in 266; =compass.http.tests= 9674 in 385; pages vitest 241; shell test 40; gateway test 49; both model scripts exit 0 | * Open product calls @@ -200,7 +205,7 @@ Recorded, not decided, pending the product owner: * Result -Built in six units and two verification fixes on +Built in six units and four verification fixes on =feature/agent-sessions=, each verified before the next, and pushed in #262, which is not merged. Migration 7 builds the catalog =schema.sql= builds; the parser and router gates admit the From e896569076a15b953e83d3ad15c0afb84c7946d4 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 12:09:24 +0000 Subject: [PATCH 14/24] [web] Format the session work as the repository does Prettier, which compass.web.format checks in CI, had not run over the new and changed files. Co-Authored-By: Claude Code --- .../packages/pages/src/AgentPanel.tsx | 5 +- .../packages/pages/src/agent.test.tsx | 4 +- .../compass.web/packages/pages/src/agent.ts | 4 +- .../packages/pages/src/client.test.ts | 89 +++++++++---------- .../packages/pages/src/conversation.tsx | 17 +--- .../compass.web/packages/pages/src/i18n/fr.ts | 2 +- .../packages/web/e2e/agent.spec.ts | 15 ++-- .../packages/web/gateway/gateway.spec.ts | 12 +-- 8 files changed, 59 insertions(+), 89 deletions(-) diff --git a/projects/compass.web/packages/pages/src/AgentPanel.tsx b/projects/compass.web/packages/pages/src/AgentPanel.tsx index bdf90bf4..2d2644a6 100644 --- a/projects/compass.web/packages/pages/src/AgentPanel.tsx +++ b/projects/compass.web/packages/pages/src/AgentPanel.tsx @@ -111,7 +111,10 @@ export function AgentPanel({ data-testid="agent-panel" > - + {missing ? (

{t('agent.sessions.missing')} diff --git a/projects/compass.web/packages/pages/src/agent.test.tsx b/projects/compass.web/packages/pages/src/agent.test.tsx index 4c5b4e6b..e35d5596 100644 --- a/projects/compass.web/packages/pages/src/agent.test.tsx +++ b/projects/compass.web/packages/pages/src/agent.test.tsx @@ -706,9 +706,7 @@ describe('a restored conversation', () => { it('polls a streaming turn until it settles or is too old to be alive', () => { const fresh = storedSession.turns[4]!; expect(stillStreaming(fresh)).toBe(true); - expect(stillStreaming(fresh, Date.parse(fresh.asked_at) + UNFINISHED_MS + 1)).toBe( - false, - ); + expect(stillStreaming(fresh, Date.parse(fresh.asked_at) + UNFINISHED_MS + 1)).toBe(false); expect(stillStreaming(storedSession.turns[0]!)).toBe(false); }); }); diff --git a/projects/compass.web/packages/pages/src/agent.ts b/projects/compass.web/packages/pages/src/agent.ts index 0c7d35d5..30a793a2 100644 --- a/projects/compass.web/packages/pages/src/agent.ts +++ b/projects/compass.web/packages/pages/src/agent.ts @@ -101,9 +101,7 @@ export function stillStreaming(turn: AgentTurn, now: number = Date.now()): boole function endOf(turn: AgentTurn): TurnEnd { switch (turn.status) { case 'done': - return turn.done === null - ? { kind: 'cut' } - : { kind: 'done', done: turn.done }; + return turn.done === null ? { kind: 'cut' } : { kind: 'done', done: turn.done }; case 'failed': return turn.failure === null ? { kind: 'cut' } diff --git a/projects/compass.web/packages/pages/src/client.test.ts b/projects/compass.web/packages/pages/src/client.test.ts index 8d6c58a6..1f8d869d 100644 --- a/projects/compass.web/packages/pages/src/client.test.ts +++ b/projects/compass.web/packages/pages/src/client.test.ts @@ -350,17 +350,14 @@ describe("the agent's conversations", () => { it('creates a conversation with an empty body when it gives no title', async () => { const asked: { url: string; init: RequestInit | undefined }[] = []; - const client = createClient( - { httpBase: '/', onDenied: () => undefined }, - (input, init) => { - asked.push({ url: String(input), init }); - return Promise.resolve( - new Response(JSON.stringify({ session: 7, created_at: 'at' }), { - status: 200, - }), - ); - }, - ); + const client = createClient({ httpBase: '/', onDenied: () => undefined }, (input, init) => { + asked.push({ url: String(input), init }); + return Promise.resolve( + new Response(JSON.stringify({ session: 7, created_at: 'at' }), { + status: 200, + }), + ); + }); await expect(client.createAgentSession('compass')).resolves.toEqual({ session: 7, created_at: 'at', @@ -370,30 +367,27 @@ describe("the agent's conversations", () => { expect(asked[0]?.init?.body).toBe('{}'); }); - it('lists the caller\'s conversations with the page asked for', async () => { + it("lists the caller's conversations with the page asked for", async () => { const asked: string[] = []; - const client = createClient( - { httpBase: '/', onDenied: () => undefined }, - (input) => { - asked.push(String(input)); - return Promise.resolve( - new Response( - JSON.stringify({ - sessions: [ - { - session: 7, - title: 'The log', - created_at: 'a', - updated_at: 'b', - turns: 2, - }, - ], - }), - { status: 200 }, - ), - ); - }, - ); + const client = createClient({ httpBase: '/', onDenied: () => undefined }, (input) => { + asked.push(String(input)); + return Promise.resolve( + new Response( + JSON.stringify({ + sessions: [ + { + session: 7, + title: 'The log', + created_at: 'a', + updated_at: 'b', + turns: 2, + }, + ], + }), + { status: 200 }, + ), + ); + }); await expect(client.listAgentSessions('compass', 10, 5)).resolves.toEqual([ { session: 7, title: 'The log', created_at: 'a', updated_at: 'b', turns: 2 }, ]); @@ -414,21 +408,18 @@ describe("the agent's conversations", () => { it('asks in a conversation with a POST whose body holds the question', async () => { const asked: { url: string; init: RequestInit | undefined }[] = []; - const client = createClient( - { httpBase: '/', onDenied: () => undefined }, - (input, init) => { - asked.push({ url: String(input), init }); - return Promise.resolve( - new Response( - 'event: token\ndata: {"text":"The weather"}\n\n' + - 'event: done\ndata: {"cited":[1],"dropped":[],"first_token_ms":1,' + - '"total_ms":2,"prompt_tokens":3,"generated_tokens":4,' + - '"tokens_per_second":5,"finish_reason":"stop"}\n\n', - { status: 200 }, - ), - ); - }, - ); + const client = createClient({ httpBase: '/', onDenied: () => undefined }, (input, init) => { + asked.push({ url: String(input), init }); + return Promise.resolve( + new Response( + 'event: token\ndata: {"text":"The weather"}\n\n' + + 'event: done\ndata: {"cited":[1],"dropped":[],"first_token_ms":1,' + + '"total_ms":2,"prompt_tokens":3,"generated_tokens":4,' + + '"tokens_per_second":5,"finish_reason":"stop"}\n\n', + { status: 200 }, + ), + ); + }); const events = []; for await (const event of client.askAgentSession( 'compass', diff --git a/projects/compass.web/packages/pages/src/conversation.tsx b/projects/compass.web/packages/pages/src/conversation.tsx index 5daba218..229f8d6b 100644 --- a/projects/compass.web/packages/pages/src/conversation.tsx +++ b/projects/compass.web/packages/pages/src/conversation.tsx @@ -43,10 +43,7 @@ export function agentStatusKey(httpBase: string): readonly unknown[] { return ['compass', httpBase, 'agent']; } -export function agentSessionsKey( - httpBase: string, - environment: string, -): readonly unknown[] { +export function agentSessionsKey(httpBase: string, environment: string): readonly unknown[] { return ['compass', httpBase, 'agent', 'sessions', environment]; } @@ -112,17 +109,12 @@ export function ConversationProvider({ }); const sessionQuery = useQuery({ - queryKey: agentSessionKey( - httpBase, - opened.environment ?? '', - opened.session ?? 0, - ), + queryKey: agentSessionKey(httpBase, opened.environment ?? '', opened.session ?? 0), queryFn: () => client.getAgentSession(opened.environment!, opened.session!), // A conversation this provider streamed is never refetched under the // live turns: the terminal write is asynchronous, and a read of it // could race that write and restore a turn the person is watching. - enabled: - opened.environment !== null && opened.session !== null && owned !== opened.session, + enabled: opened.environment !== null && opened.session !== null && owned !== opened.session, retry: retryable, refetchInterval: (query) => { const data = query.state.data; @@ -210,8 +202,7 @@ export function ConversationProvider({ id, end: { kind: 'error', - message: - error instanceof Error ? error.message : String(error), + message: error instanceof Error ? error.message : String(error), }, }); return; diff --git a/projects/compass.web/packages/pages/src/i18n/fr.ts b/projects/compass.web/packages/pages/src/i18n/fr.ts index 031ccade..2e928ba7 100644 --- a/projects/compass.web/packages/pages/src/i18n/fr.ts +++ b/projects/compass.web/packages/pages/src/i18n/fr.ts @@ -476,7 +476,7 @@ const fr: Catalogue = { delete: 'Supprimer la conversation', confirmDelete: 'Supprimer cette conversation et ses échanges ?', missing: - "Cette conversation ne vous est pas accessible dans cette vue. Choisissez-en une autre ou commencez-en une nouvelle.", + 'Cette conversation ne vous est pas accessible dans cette vue. Choisissez-en une autre ou commencez-en une nouvelle.', failed: "compass.http n'a pas répondu pour la conversation : {reason}", }, statusReading: "Lecture de l'état de l'agent…", diff --git a/projects/compass.web/packages/web/e2e/agent.spec.ts b/projects/compass.web/packages/web/e2e/agent.spec.ts index be9cc47f..03e5c263 100644 --- a/projects/compass.web/packages/web/e2e/agent.spec.ts +++ b/projects/compass.web/packages/web/e2e/agent.spec.ts @@ -103,9 +103,9 @@ test('an answer streams with its citations, and a citation opens the document at (m) => m.role === 'user' && m.content === "What does the lighthouse keeper's log record?", ); expect(first).toBeDefined(); - expect(messages.some((m) => m.role === 'assistant' && m.content.includes('[cited earlier]'))).toBe( - true, - ); + expect( + messages.some((m) => m.role === 'assistant' && m.content.includes('[cited earlier]')), + ).toBe(true); }); test('a reload restores the conversation, and deleting it removes it', async ({ page }) => { @@ -134,10 +134,7 @@ test('a reload restores the conversation, and deleting it removes it', async ({ await expect(page.getByTestId('agent-turn')).toHaveCount(0); }); -test('an abandoned answer restores as stopped with its partial text', async ({ - page, - request, -}) => { +test('an abandoned answer restores as stopped with its partial text', async ({ page, request }) => { expect((await request.post(`${STUB}/__slow`)).ok()).toBe(true); const environment = await environmentOf(page); await page.goto(`/${environment}/agent`); @@ -151,9 +148,7 @@ test('an abandoned answer restores as stopped with its partial text', async ({ await expect(restored.getByTestId('agent-status')).toContainText('Stopped', { timeout: 15_000, }); - await expect(restored.getByTestId('agent-answer')).toContainText( - "The lighthouse keeper's log", - ); + await expect(restored.getByTestId('agent-answer')).toContainText("The lighthouse keeper's log"); await expect(restored.getByTestId('agent-failure')).toHaveCount(0); expect((await request.post(`${STUB}/__fast`)).ok()).toBe(true); }); diff --git a/projects/compass.web/packages/web/gateway/gateway.spec.ts b/projects/compass.web/packages/web/gateway/gateway.spec.ts index 5e817496..00b4f87d 100644 --- a/projects/compass.web/packages/web/gateway/gateway.spec.ts +++ b/projects/compass.web/packages/web/gateway/gateway.spec.ts @@ -836,9 +836,7 @@ test.describe("the agent's conversations", () => { sessions: { session: number }[]; }; expect(list.sessions.map((s) => s.session)).not.toContain(session); - expect( - (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), - ).toBe(404); + expect((await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status()).toBe(404); expect( ( await write(reader, 'POST', v1(`agent/sessions/${session}/ask`), { @@ -887,13 +885,9 @@ test.describe("the agent's conversations", () => { test('is deleted by its owner, twice, and gone from the list', async () => { const reader = await as('reader'); const session = await made(reader, 'To delete'); - expect( - (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), - ).toBe(204); + expect((await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status()).toBe(204); expect((await reader.get(v1(`agent/sessions/${session}`))).status()).toBe(404); - expect( - (await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status(), - ).toBe(204); + expect((await write(reader, 'DELETE', v1(`agent/sessions/${session}`))).status()).toBe(204); const list = (await json(await reader.get(v1('agent/sessions')))) as { sessions: { session: number }[]; }; From 677b07ccb7a1a497ca4cbffeeb7704f7ab76adfd Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 13:33:26 +0000 Subject: [PATCH 15/24] [db] Keep the model's reasoning beside its answer agent.agent_turn gains a thought column, defaulting to empty, so a restored turn shows the reasoning the person saw while it streamed. The generated row codec and schema carry it; migration 7 gains the column verbatim because it is unreleased. Co-Authored-By: Claude Code --- .../compass.db/types/agent_turn_row.hpp | 1 + .../compass.db/types/agent_turn_row_codec.hpp | 1 + .../modeling/compass.db.agent_turn.org | 19 ++++++++++++++++--- projects/compass.db/sql/schema.sql | 1 + projects/compass.db/src/ops/migrations.cpp | 1 + 5 files changed, 20 insertions(+), 3 deletions(-) diff --git a/projects/compass.db/include/compass.db/types/agent_turn_row.hpp b/projects/compass.db/include/compass.db/types/agent_turn_row.hpp index bdf3c42c..3105baed 100644 --- a/projects/compass.db/include/compass.db/types/agent_turn_row.hpp +++ b/projects/compass.db/include/compass.db/types/agent_turn_row.hpp @@ -82,6 +82,7 @@ struct agent_turn_row { std::chrono::sys_time asked_at; std::string retrieval; std::string answer; + std::string thought; agent_turn_status status = agent_turn_status::streaming; std::optional done; std::optional failure; diff --git a/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp b/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp index a93b5b95..ef24c98a 100644 --- a/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp +++ b/projects/compass.db/include/compass.db/types/agent_turn_row_codec.hpp @@ -52,6 +52,7 @@ namespace compass::db::types { ::compass::db::codec::field{"asked_at", &agent_turn_row::asked_at}, ::compass::db::codec::field{"retrieval", &agent_turn_row::retrieval}, ::compass::db::codec::field{"answer", &agent_turn_row::answer}, + ::compass::db::codec::field{"thought", &agent_turn_row::thought}, ::compass::db::codec::field{"status", &agent_turn_row::status}, ::compass::db::codec::field{"done", &agent_turn_row::done}, ::compass::db::codec::field{"failure", &agent_turn_row::failure}, diff --git a/projects/compass.db/modeling/compass.db.agent_turn.org b/projects/compass.db/modeling/compass.db.agent_turn.org index 3bd46cb8..8c793b36 100644 --- a/projects/compass.db/modeling/compass.db.agent_turn.org +++ b/projects/compass.db/modeling/compass.db.agent_turn.org @@ -86,9 +86,22 @@ transcript names documents, never their text. :default: '' :END: -The answer as it has streamed so far. Every two seconds while it streams, -a snapshot replaces it, so a crash restores the last partial rather than an -empty cut. A terminal write replaces it with the whole answer. +The answer as it has streamed so far, without the model's reasoning. Every +two seconds while it streams, a snapshot replaces it, so a crash restores +the last partial rather than an empty cut. A terminal write replaces it with +the whole answer. + +** thought +:PROPERTIES: +:type: text +:default: '' +:END: + +The model's reasoning as it has streamed so far, kept for the panel's +collapsed =Thinking= element and never sent back to the model. It is +snapshotted with the answer, so a restore shows the reasoning the person +saw while the answer streamed, and it is empty when the model reasoned +nothing or the server did not stream its reasoning. ** status :PROPERTIES: diff --git a/projects/compass.db/sql/schema.sql b/projects/compass.db/sql/schema.sql index 380e78d0..fec19e15 100644 --- a/projects/compass.db/sql/schema.sql +++ b/projects/compass.db/sql/schema.sql @@ -266,6 +266,7 @@ CREATE TABLE agent.agent_turn ( asked_at timestamptz NOT NULL, retrieval jsonb NOT NULL, answer text NOT NULL DEFAULT '', + thought text NOT NULL DEFAULT '', status text NOT NULL DEFAULT 'streaming' CHECK (status IN ('streaming', 'done', 'failed', 'stopped', 'cut')), done jsonb, failure jsonb, diff --git a/projects/compass.db/src/ops/migrations.cpp b/projects/compass.db/src/ops/migrations.cpp index baf0f056..9ca5ee3b 100644 --- a/projects/compass.db/src/ops/migrations.cpp +++ b/projects/compass.db/src/ops/migrations.cpp @@ -350,6 +350,7 @@ CREATE TABLE agent.agent_turn ( asked_at timestamptz NOT NULL, retrieval jsonb NOT NULL, answer text NOT NULL DEFAULT '', + thought text NOT NULL DEFAULT '', status text NOT NULL DEFAULT 'streaming' CHECK (status IN ('streaming', 'done', 'failed', 'stopped', 'cut')), done jsonb, failure jsonb, From 4231bfd71f819ca581941fcbdcabec34277c1e87 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 13:33:34 +0000 Subject: [PATCH 16/24] [http] Stream the model's thinking and the context it used Thinking is on and capped at 4,096 tokens, reasoning included. llama-server's reasoning_content delta (or a build's reasoning) becomes agent_thought_event, and the turn stores the reasoning beside its answer, snapshotted with it. The done event carries the context window, the history budget and bytes, and the done turns the window left out, so the panel measures the last answer from llama-server's usage chunk: the whole prompt, not only what the cache did not reuse. Co-Authored-By: Claude Code --- .../evidence/service_model_struct_check.py | 2 +- .../include/compass.http/agent/llama.hpp | 13 ++- .../include/compass.http/agent/turn.hpp | 9 +- .../compass.http/agent/turn_writer.hpp | 4 +- .../compass.http/messages/agent_protocol.hpp | 37 +++++++ .../messages/agent_sessions_protocol.hpp | 2 + .../include/compass.http/ops/agent.hpp | 38 ++++++- .../include/compass.http/query/sessions.hpp | 8 +- .../modeling/compass.http.agent.org | 101 ++++++++++++++++-- .../modeling/compass.http.agent_sessions.org | 9 ++ projects/compass.http/src/agent/llama.cpp | 55 ++++++++-- .../compass.http/src/agent/turn_writer.cpp | 6 +- projects/compass.http/src/app/service.cpp | 9 ++ .../src/messages/agent_protocol.cpp | 8 ++ projects/compass.http/src/ops/agent.cpp | 12 ++- projects/compass.http/src/query/sessions.cpp | 31 ++++-- .../compass.http/src/routes/agent_routes.cpp | 2 +- .../compass.http/tests/agent_llama_tests.cpp | 61 +++++++++-- projects/compass.http/tests/llama_stub.hpp | 14 ++- .../tests/messages_agent_protocol_tests.cpp | 43 ++++++++ .../tests/openapi_document_tests.cpp | 5 +- .../compass.http/tests/ops_agent_tests.cpp | 13 ++- .../compass.http/tests/query_reads_tests.cpp | 4 +- .../tests/query_sessions_tests.cpp | 29 ++++- .../compass.http/tests/turn_writer_tests.cpp | 25 +++-- 25 files changed, 465 insertions(+), 75 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py index c1f5b260..b456a132 100644 --- a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py +++ b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/service_model_struct_check.py @@ -53,7 +53,7 @@ # The agent's messages; compass.db has no agent. "agent_request", "agent_status_request", "agent_status_response", "agent_passage", "agent_passages_event", "agent_token_event", - "agent_done_event", "agent_failure_event", + "agent_thought_event", "agent_done_event", "agent_failure_event", # The agent's conversations; the query layer of compass.http owns them, # and compass.db has no conversation. "create_agent_session_request", "create_agent_session_response", diff --git a/projects/compass.http/include/compass.http/agent/llama.hpp b/projects/compass.http/include/compass.http/agent/llama.hpp index 5d122740..3012ff61 100644 --- a/projects/compass.http/include/compass.http/agent/llama.hpp +++ b/projects/compass.http/include/compass.http/agent/llama.hpp @@ -88,15 +88,18 @@ struct answer_options { std::int64_t turn = 0; /// Where the stream records the turn; null on the stateless ask. std::shared_ptr sink; + /// What the answer's prompt holds, for the done event's context indicator. + ops::agent_context_usage context; }; /** * @brief The agent's answer as server-sent events, produced as it is read: - * the passages, then llama-server's answer a piece at a time as it streams - * it, then the citations, or a failure when the server cannot answer. While - * the model is silent, a comment line every heartbeat keeps a proxy from - * closing the stream. The connection to llama-server lives as long as the - * stream, so a client that goes away ends the model's work too. + * the passages, then llama-server's reasoning and answer a piece at a time + * as it streams them, then the citations and context usage, or a failure + * when the server cannot answer. While the model is silent, a comment line + * every heartbeat keeps a proxy from closing the stream. The connection to + * llama-server lives as long as the stream, so a client that goes away ends + * the model's work too. */ class answer_stream final : public domain::awaitable_body_source { public: diff --git a/projects/compass.http/include/compass.http/agent/turn.hpp b/projects/compass.http/include/compass.http/agent/turn.hpp index abc8a431..cb189e87 100644 --- a/projects/compass.http/include/compass.http/agent/turn.hpp +++ b/projects/compass.http/include/compass.http/agent/turn.hpp @@ -34,12 +34,14 @@ namespace compass::http::agent { enum class turn_end { done, failed, stopped }; /** - * @brief The terminal record of one exchange: its turn, the answer as it - * ended, how it ended, and the event the stream sent with it. + * @brief The terminal record of one exchange: its turn, the answer and the + * model's reasoning as they ended, how it ended, and the event the stream + * sent with it. */ struct turn_record { std::int64_t turn = 0; std::string answer; + std::string thought; turn_end end = turn_end::stopped; std::optional done; std::optional failure; @@ -53,7 +55,8 @@ class turn_sink { public: virtual ~turn_sink() = default; virtual void record(turn_record r) noexcept = 0; - virtual void record_partial(std::int64_t turn, std::string answer) noexcept = 0; + virtual void record_partial(std::int64_t turn, std::string answer, + std::string thought) noexcept = 0; }; } diff --git a/projects/compass.http/include/compass.http/agent/turn_writer.hpp b/projects/compass.http/include/compass.http/agent/turn_writer.hpp index 1a567931..ea68afa5 100644 --- a/projects/compass.http/include/compass.http/agent/turn_writer.hpp +++ b/projects/compass.http/include/compass.http/agent/turn_writer.hpp @@ -46,6 +46,7 @@ struct queued_turn { turn_record record; std::int64_t turn = 0; std::string answer; + std::string thought; }; /** @@ -68,7 +69,8 @@ class turn_writer final : public turn_sink { turn_writer& operator=(const turn_writer&) = delete; void record(turn_record r) noexcept override; - void record_partial(std::int64_t turn, std::string answer) noexcept override; + void record_partial(std::int64_t turn, std::string answer, + std::string thought) noexcept override; /// Waits until nothing is queued or being written; a test seam. void flush(); diff --git a/projects/compass.http/include/compass.http/messages/agent_protocol.hpp b/projects/compass.http/include/compass.http/messages/agent_protocol.hpp index 3dbaa897..b8ec59a9 100644 --- a/projects/compass.http/include/compass.http/messages/agent_protocol.hpp +++ b/projects/compass.http/include/compass.http/messages/agent_protocol.hpp @@ -139,6 +139,7 @@ struct agent_status_request { struct agent_status_response { std::string model; std::string server; + std::uint32_t context_tokens = 0; agent_health health{}; std::string detail; std::string start; @@ -154,6 +155,7 @@ struct agent_status_response { return ::compass::db::codec::field_list{ ::compass::db::codec::field{"model", &agent_status_response::model}, ::compass::db::codec::field{"server", &agent_status_response::server}, + ::compass::db::codec::field{"context_tokens", &agent_status_response::context_tokens, true}, ::compass::db::codec::field{"health", &agent_status_response::health}, ::compass::db::codec::field{"detail", &agent_status_response::detail}, ::compass::db::codec::field{"start", &agent_status_response::start}, @@ -226,6 +228,22 @@ struct agent_token_event { }; } +struct agent_thought_event { + std::string text; + + friend bool operator==(const agent_thought_event&, const agent_thought_event&) = default; +}; + +/** + * @brief The members of agent_thought_event, named as the wire names them and in the + * order the type declares them. + */ +[[nodiscard]] constexpr auto wire_fields(std::type_identity) { + return ::compass::db::codec::field_list{ + ::compass::db::codec::field{"text", &agent_thought_event::text}, + }; +} + struct agent_done_event { std::vector cited; std::vector dropped; @@ -235,6 +253,11 @@ struct agent_done_event { std::uint32_t generated_tokens = 0; double tokens_per_second = 0; std::string finish_reason; + std::uint32_t context_tokens = 0; + std::uint32_t history_budget = 0; + std::uint32_t history_turns = 0; + std::uint32_t history_bytes = 0; + std::uint32_t dropped_turns = 0; friend bool operator==(const agent_done_event&, const agent_done_event&) = default; }; @@ -253,6 +276,11 @@ struct agent_done_event { ::compass::db::codec::field{"generated_tokens", &agent_done_event::generated_tokens, true}, ::compass::db::codec::field{"tokens_per_second", &agent_done_event::tokens_per_second, true}, ::compass::db::codec::field{"finish_reason", &agent_done_event::finish_reason}, + ::compass::db::codec::field{"context_tokens", &agent_done_event::context_tokens, true}, + ::compass::db::codec::field{"history_budget", &agent_done_event::history_budget, true}, + ::compass::db::codec::field{"history_turns", &agent_done_event::history_turns, true}, + ::compass::db::codec::field{"history_bytes", &agent_done_event::history_bytes, true}, + ::compass::db::codec::field{"dropped_turns", &agent_done_event::dropped_turns, true}, }; } @@ -384,6 +412,15 @@ struct wire_traits { static compass::http::messages::agent_token_event read_json(std::string_view text); }; +template <> +struct wire_traits { + static constexpr bool is_generated = true; + + static std::string write_json(const compass::http::messages::agent_thought_event& v); + + static compass::http::messages::agent_thought_event read_json(std::string_view text); +}; + template <> struct wire_traits { static constexpr bool is_generated = true; diff --git a/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp b/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp index 58828eb7..da088e64 100644 --- a/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp +++ b/projects/compass.http/include/compass.http/messages/agent_sessions_protocol.hpp @@ -209,6 +209,7 @@ struct agent_turn { std::string asked_at; agent_passages_event retrieval; std::string answer; + std::string thought; agent_turn_status status{}; std::optional done; std::optional failure; @@ -228,6 +229,7 @@ struct agent_turn { ::compass::db::codec::field{"asked_at", &agent_turn::asked_at}, ::compass::db::codec::field{"retrieval", &agent_turn::retrieval}, ::compass::db::codec::field{"answer", &agent_turn::answer}, + ::compass::db::codec::field{"thought", &agent_turn::thought}, ::compass::db::codec::field{"status", &agent_turn::status}, ::compass::db::codec::field{"done", &agent_turn::done}, ::compass::db::codec::field{"failure", &agent_turn::failure}, diff --git a/projects/compass.http/include/compass.http/ops/agent.hpp b/projects/compass.http/include/compass.http/ops/agent.hpp index 82c590df..e4ba1f9b 100644 --- a/projects/compass.http/include/compass.http/ops/agent.hpp +++ b/projects/compass.http/include/compass.http/ops/agent.hpp @@ -125,6 +125,30 @@ struct agent_message { friend bool operator==(const agent_message&, const agent_message&) = default; }; +/** + * @brief The most tokens one answer may generate, reasoning included. The + * prompt asks for at most five sentences, so the cap leaves room for a + * thinking model's reasoning before it writes them. + */ +inline constexpr std::uint32_t answer_token_cap = 4096; + +/** + * @brief What one answer's prompt and completion used, for the panel's + * context indicator. The first five fields describe the model's window and + * the earlier exchanges the prompt held; =prompt_tokens= and + * =generated_tokens= arrive in the =done= event from llama-server's own + * timings. + */ +struct agent_context_usage { + std::uint32_t context_tokens = 0; + std::uint32_t history_budget = 0; + std::uint32_t history_turns = 0; + std::uint32_t history_bytes = 0; + std::uint32_t dropped_turns = 0; + + friend bool operator==(const agent_context_usage&, const agent_context_usage&) = default; +}; + /** * @brief @p answer with every citation group replaced by "[cited earlier]": * a stored answer's numbers name the passages of its own exchange, which the @@ -144,6 +168,13 @@ struct agent_message { std::span turns, std::size_t max_turns = 8, std::size_t max_chars = 24000); +/** + * @brief The bytes @p exchanges take as history: their questions and + * neutralised answers, which is what @ref agent_history_window counted + * against its budget. + */ +[[nodiscard]] std::uint32_t agent_history_bytes(std::span exchanges); + /** * @brief The bytes of history a context of @p context_tokens leaves after * @p prompt_bytes of system and current user message, @p max_answer_tokens @@ -152,7 +183,8 @@ struct agent_message { */ [[nodiscard]] std::size_t agent_history_budget(std::uint32_t context_tokens, std::size_t prompt_bytes, - std::uint32_t max_answer_tokens = 400, + std::uint32_t max_answer_tokens = + answer_token_cap, std::size_t slack = 1024); /** @@ -180,8 +212,8 @@ struct agent_prompt { /** * @brief The body of llama-server's /v1/chat/completions request for - * @p prompt: streamed, with the prototype's sampling and at most 400 - * tokens. + * @p prompt: streamed, with thinking on, the prototype's sampling and at + * most @ref answer_token_cap tokens. */ [[nodiscard]] std::string agent_chat_body(const agent_prompt& prompt); diff --git a/projects/compass.http/include/compass.http/query/sessions.hpp b/projects/compass.http/include/compass.http/query/sessions.hpp index 7ac88fab..774aa2be 100644 --- a/projects/compass.http/include/compass.http/query/sessions.hpp +++ b/projects/compass.http/include/compass.http/query/sessions.hpp @@ -53,6 +53,9 @@ struct agent_session_state { std::string title; std::vector history; std::string last_question; + /// Every done exchange the session holds, including those the history + /// window does not carry. + std::uint32_t done_turns = 0; }; /// The turn an ask opened: its row and its place in the session. @@ -98,9 +101,10 @@ void delete_agent_session(db::io::connection& c, const domain::caller& who, std::int64_t session, std::string_view question, std::string_view retrieval_json, std::string_view model); -/// Replaces the answer of a streaming turn with the snapshot taken so far. +/// Replaces the answer and reasoning of a streaming turn with the snapshot +/// taken so far. void save_agent_partial(db::io::connection& c, std::int64_t turn, - std::string_view answer); + std::string_view answer, std::string_view thought); /** * @brief Settles a streaming turn with its answer and end. A turn already diff --git a/projects/compass.http/modeling/compass.http.agent.org b/projects/compass.http/modeling/compass.http.agent.org index 432d3b0f..a07034e1 100644 --- a/projects/compass.http/modeling/compass.http.agent.org +++ b/projects/compass.http/modeling/compass.http.agent.org @@ -47,14 +47,16 @@ name. A question answered from the environment's documents inside the caller's view, as server-sent events (=text/event-stream=), each event's data one line of JSON: =passages= once, an =agent_passages_event=, the sections -handed to the model; =token=, an =agent_token_event=, for each piece of the -answer as the model writes it; then =done=, an =agent_done_event=, with the -citations, or =failure=, an =agent_failure_event=, when the model's server -cannot answer. A line that begins with a colon is a comment, sent every 15 -seconds while the model is silent, and carries nothing. When no section -matches, the model is still asked, and tells the user no document matched. -A question searches at most twelve times. Four questions are answered at -once; one more is refused with 503 =busy=. +handed to the model; =thought=, an =agent_thought_event=, for each piece of +the model's reasoning as it thinks; =token=, an =agent_token_event=, for +each piece of the answer as the model writes it; then =done=, an +=agent_done_event=, with the citations, timings and context the answer used, +or =failure=, an =agent_failure_event=, when the model's server cannot +answer. A line that begins with a colon is a comment, sent every 15 seconds +while the model is silent, and carries nothing. When no section matches, the +model is still asked, and tells the user no document matched. A question +searches at most twelve times. Four questions are answered at once; one more +is refused with 503 =busy=. *** environment :PROPERTIES: @@ -108,6 +110,16 @@ it. The address of =llama-server=, host and port. +*** context_tokens +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +The model's context window in tokens, as =llama-server= was started with +it. The panel shows the last answer's prompt and generated tokens against +it. + *** health :PROPERTIES: :cpp_type: agent_health @@ -225,6 +237,18 @@ The =token= event: the next piece of the answer. :cpp_type: std::string :END: +** agent_thought_event + +The =thought= event: the next piece of the model's reasoning, as +llama-server streams it under its reasoning format. It is not part of the +answer: the panel shows it in a collapsed =Thinking= element and never cites +it. + +*** text +:PROPERTIES: +:cpp_type: std::string +:END: + ** agent_done_event The =done= event, the last of an answered stream. @@ -267,7 +291,9 @@ From the question's arrival to the answer's end. :default: 0 :END: -The prompt's tokens the model read, as =llama-server= counts them. +The prompt's tokens, as llama-server's usage chunk counts them: the whole +prompt, including a prefix its cache reused this request. Zero when the +server sends no usage. *** generated_tokens :PROPERTIES: @@ -275,6 +301,9 @@ The prompt's tokens the model read, as =llama-server= counts them. :default: 0 :END: +Everything the model generated, reasoning included, as llama-server's usage +chunk counts it; the timings' =predicted_n= when the server sends no usage. + *** tokens_per_second :PROPERTIES: :cpp_type: double @@ -291,6 +320,54 @@ How fast the model wrote, as =llama-server= measures it. =stop= when the model ended the answer, =length= when it reached the token limit. +*** context_tokens +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +The model's context window in tokens when the answer was given. The +panel measures the last answer against it. + +*** history_budget +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +The bytes of earlier exchanges the prompt for this answer kept, after the +system and current user messages and the completion reserve. It is zero +when the question is the session's first or the window holds no earlier +exchange. + +*** history_turns +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +How many earlier exchanges this answer's prompt held. + +*** history_bytes +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +The bytes those exchanges took, as their questions and neutralised answers +count. + +*** dropped_turns +:PROPERTIES: +:cpp_type: std::uint32_t +:default: 0 +:END: + +The session's done exchanges this answer's prompt left out, because the +eight-exchange or byte window dropped them. The panel names them as not +sent; a session summary is the compaction that would keep them, and is not +built. + ** agent_failure_event The =failure= event, the last of a stream the model could not answer. @@ -325,6 +402,12 @@ when it is not running. model's =agent_*_event= messages, written by their codecs. It is no MCP tool: an agent over MCP has a model of its own and searches with =search_documents=. +- Thinking is on. The request sets =chat_template_kwargs.enable_thinking= + true, so a reasoning model thinks before it answers, and compass parses + the =reasoning_content= delta llama-server streams under its reasoning + format as =agent_thought_event=. The completion cap is 4,096 tokens, which + covers the reasoning and the five-sentence answer; a =finish_reason= of + =length= says the cap was reached. - =agent_failure_event.code= takes =agent_health=, since a failure is the server's state; it is never =ready=. - =agent_passage.kind= is =hit_kind= of [[id:4152E925-E32D-40C3-AFF1-24F2AB244C5F][compass.http.document_queries]], diff --git a/projects/compass.http/modeling/compass.http.agent_sessions.org b/projects/compass.http/modeling/compass.http.agent_sessions.org index 6c326687..c03d170d 100644 --- a/projects/compass.http/modeling/compass.http.agent_sessions.org +++ b/projects/compass.http/modeling/compass.http.agent_sessions.org @@ -240,6 +240,15 @@ The =passages= event the stream sent. The answer as stored: the whole one, or the last partial snapshot. +*** thought +:PROPERTIES: +:cpp_type: std::string +:END: + +The model's reasoning as stored with the answer: the whole of it, or the +last partial snapshot. The panel shows it collapsed under =Thinking=; it is +never sent back to the model. + *** status :PROPERTIES: :cpp_type: agent_turn_status diff --git a/projects/compass.http/src/agent/llama.cpp b/projects/compass.http/src/agent/llama.cpp index a81ce3d6..1506b67f 100644 --- a/projects/compass.http/src/agent/llama.cpp +++ b/projects/compass.http/src/agent/llama.cpp @@ -115,6 +115,7 @@ asio::awaitable check(types::agent_settings s) out.model = file_name(s.model); out.server = address(s); out.start = start_command(s); + out.context_tokens = s.context_tokens; beast::tcp_stream stream(co_await asio::this_coro::executor); if (const auto failed = co_await connect(stream, s)) { out.health = agent_health::not_running; @@ -179,6 +180,7 @@ messages::agent_status_response status(const types::agent_settings& s) { out.model = file_name(s.model); out.server = address(s); out.start = start_command(s); + out.context_tokens = s.context_tokens; out.health = agent_health::failing; out.detail = "llama-server at " + out.server + " did not answer within three seconds."; return out; @@ -204,7 +206,7 @@ struct answer_stream::exchange { exchange(const asio::any_io_executor& on, types::agent_settings s, std::string chat, std::size_t passages_given, std::chrono::steady_clock::time_point asked_at, bool names, std::int64_t turn_number, std::shared_ptr record_to, - std::chrono::milliseconds snapshot_every) + std::chrono::milliseconds snapshot_every, ops::agent_context_usage usage) : events(on, 64) , stream(on) , server(std::move(s)) @@ -215,7 +217,8 @@ struct answer_stream::exchange { , turn(turn_number) , sink(std::move(record_to)) , last_partial(asked_at) - , partial_every(snapshot_every) {} + , partial_every(snapshot_every) + , context(usage) {} asio::awaitable run(); asio::awaitable ask(); @@ -239,11 +242,13 @@ struct answer_stream::exchange { std::shared_ptr sink; std::chrono::steady_clock::time_point last_partial; std::chrono::milliseconds partial_every; + ops::agent_context_usage context; std::atomic recorded{false}; bool told_done = false; bool ended = false; std::string out; std::string answer; + std::string thought; messages::agent_done_event done; }; @@ -273,7 +278,7 @@ void answer_stream::start(const asio::any_io_executor& on) { on, server_, ops::agent_chat_body(ops::agent_prompt_for(question_, found_.passages, history_)), found_.passages.size(), asked_, options_.names_server, options_.turn, options_.sink, - options_.partial_every); + options_.partial_every, options_.context); asio::co_spawn( on, [x = exchange_] { return x->run(); }, asio::bind_cancellation_slot(exchange_->leaving.slot(), asio::detached)); @@ -407,16 +412,33 @@ void answer_stream::exchange::take_lines() { break; } const auto choice = root.member("choices").element(0); - if (const auto piece = choice.member("delta").member("content").text(); - piece && !piece->empty()) { + const auto delta = choice.member("delta"); + // llama-server names the reasoning delta reasoning_content under its + // reasoning format; some builds name it reasoning. + if (const auto reasoning = delta.member("reasoning_content").text(); + reasoning && !reasoning->empty()) { + thought += *reasoning; + messages::agent_thought_event e; + e.text = std::string(*reasoning); + out += ops::agent_event( + "thought", db::codec::wire_traits::write_json(e)); + } else if (const auto legacy_reasoning = delta.member("reasoning").text(); + legacy_reasoning && !legacy_reasoning->empty()) { + thought += *legacy_reasoning; + messages::agent_thought_event e; + e.text = std::string(*legacy_reasoning); + out += ops::agent_event( + "thought", db::codec::wire_traits::write_json(e)); + } else if (const auto content = delta.member("content").text(); + content && !content->empty()) { if (answer.empty()) done.first_token_ms = static_cast( std::chrono::duration_cast( std::chrono::steady_clock::now() - asked) .count()); - answer += *piece; + answer += *content; messages::agent_token_event e; - e.text = std::string(*piece); + e.text = std::string(*content); out += ops::agent_event( "token", db::codec::wire_traits::write_json(e)); } @@ -429,15 +451,23 @@ void answer_stream::exchange::take_lines() { static_cast(timings.member("predicted_n").integer().value_or(0)); done.tokens_per_second = timings.member("predicted_per_second").real().value_or(0); } + // The usage chunk carries the whole prompt's length; timings.prompt_n + // counts only the tokens this request evaluated after a cache reuse. + if (const auto usage = root.member("usage"); usage.exists()) { + if (const auto tokens = usage.member("prompt_tokens").integer()) + done.prompt_tokens = static_cast(*tokens); + if (const auto tokens = usage.member("completion_tokens").integer()) + done.generated_tokens = static_cast(*tokens); + } } text.erase(0, start); if (ended) return; - if (sink && !answer.empty()) { + if (sink && (!answer.empty() || !thought.empty())) { const auto now = std::chrono::steady_clock::now(); if (now - last_partial >= partial_every) { last_partial = now; - sink->record_partial(turn, answer); + sink->record_partial(turn, answer, thought); } } if (text.size() > line_limit) @@ -451,6 +481,7 @@ void answer_stream::exchange::settle(turn_end end) { turn_record r; r.turn = turn; r.answer = answer; + r.thought = thought; r.end = end; if (end == turn_end::done) r.done = done; @@ -465,6 +496,11 @@ void answer_stream::exchange::finish() { std::chrono::duration_cast(std::chrono::steady_clock::now() - asked) .count()); + done.context_tokens = context.context_tokens; + done.history_budget = context.history_budget; + done.history_turns = context.history_turns; + done.history_bytes = context.history_bytes; + done.dropped_turns = context.dropped_turns; settle(turn_end::done); out += ops::agent_event( "done", db::codec::wire_traits::write_json(done)); @@ -479,6 +515,7 @@ void answer_stream::exchange::fail(agent_health code, std::string message) { turn_record r; r.turn = turn; r.answer = answer; + r.thought = thought; r.end = turn_end::failed; r.failure = e; sink->record(std::move(r)); diff --git a/projects/compass.http/src/agent/turn_writer.cpp b/projects/compass.http/src/agent/turn_writer.cpp index b02c9de0..4653cac2 100644 --- a/projects/compass.http/src/agent/turn_writer.cpp +++ b/projects/compass.http/src/agent/turn_writer.cpp @@ -63,11 +63,13 @@ void turn_writer::record(turn_record r) noexcept { push(std::move(q)); } -void turn_writer::record_partial(std::int64_t turn, std::string answer) noexcept { +void turn_writer::record_partial(std::int64_t turn, std::string answer, + std::string thought) noexcept { queued_turn q; q.what = queued_turn::kind::partial; q.turn = turn; q.answer = std::move(answer); + q.thought = std::move(thought); push(std::move(q)); } @@ -101,7 +103,7 @@ void turn_writer::run(std::stop_token stop) { }); else pool_.write([&q](db::io::connection& c) { - query::save_agent_partial(c, q.turn, q.answer); + query::save_agent_partial(c, q.turn, q.answer, q.thought); }); } catch (const std::exception& e) { if (log_) diff --git a/projects/compass.http/src/app/service.cpp b/projects/compass.http/src/app/service.cpp index 259770bd..de975d68 100644 --- a/projects/compass.http/src/app/service.cpp +++ b/projects/compass.http/src/app/service.cpp @@ -313,6 +313,7 @@ void service::add_agent_routes(net::router& r) { agent::answer_options options; options.names_server = runs_the_service(c); options.slot = take_stream_slot(open); + options.context.context_tokens = settings_.agent.context_tokens; const auto asked = std::chrono::steady_clock::now(); const auto& view = view_of(c); auto found = refusing([&] { @@ -345,6 +346,7 @@ void service::add_agent_routes(net::router& r) { const auto asked = std::chrono::steady_clock::now(); const auto& view = view_of(c); std::vector history; + std::uint32_t done_turns = 0; auto found = refusing([&] { return pool_.read([&](connection& conn) { require_environment(conn, q.environment); @@ -356,6 +358,7 @@ void service::add_agent_routes(net::router& r) { q.environment + "."); auto found = retrieve(conn, q.environment, view, q.q, state->last_question); history = std::move(state->history); + done_turns = state->done_turns; return found; }); }); @@ -376,6 +379,12 @@ void service::add_agent_routes(net::router& r) { const auto budget = ops::agent_history_budget( settings_.agent.context_tokens, current.system.size() + current.user.size()); auto window = ops::agent_history_window(history, history_turns, budget); + const auto kept = static_cast(window.size()); + options.context.context_tokens = settings_.agent.context_tokens; + options.context.history_budget = static_cast(budget); + options.context.history_turns = kept; + options.context.history_bytes = ops::agent_history_bytes(window); + options.context.dropped_turns = done_turns > kept ? done_turns - kept : 0; options.turn = begun.turn; options.sink = writer_; domain::http_response out; diff --git a/projects/compass.http/src/messages/agent_protocol.cpp b/projects/compass.http/src/messages/agent_protocol.cpp index 2bd51835..fa020bbb 100644 --- a/projects/compass.http/src/messages/agent_protocol.cpp +++ b/projects/compass.http/src/messages/agent_protocol.cpp @@ -77,6 +77,14 @@ compass::http::messages::agent_token_event wire_traits(text); } +std::string wire_traits::write_json(const compass::http::messages::agent_thought_event& v) { + return object::write_json(v); +} + +compass::http::messages::agent_thought_event wire_traits::read_json(std::string_view text) { + return object::read_json(text); +} + std::string wire_traits::write_json(const compass::http::messages::agent_done_event& v) { return object::write_json(v); } diff --git a/projects/compass.http/src/ops/agent.cpp b/projects/compass.http/src/ops/agent.cpp index e48a2e02..8dd9c572 100644 --- a/projects/compass.http/src/ops/agent.cpp +++ b/projects/compass.http/src/ops/agent.cpp @@ -294,6 +294,13 @@ std::vector agent_history_window(std::span return out; } +std::uint32_t agent_history_bytes(std::span exchanges) { + std::uint32_t bytes = 0; + for (const auto& e : exchanges) + bytes += static_cast(e.question.size() + e.answer.size()); + return bytes; +} + std::size_t agent_history_budget(std::uint32_t context_tokens, std::size_t prompt_bytes, std::uint32_t max_answer_tokens, std::size_t slack) { constexpr std::size_t bytes_per_token = 4; @@ -355,12 +362,13 @@ std::string agent_chat_body(const agent_prompt& prompt) { user.set("role", "user"); user.set("content", prompt.user); root.set("stream", true); + root.add_object("stream_options").set("include_usage", true); root.set("temperature", 0.1); root.set("top_k", std::int64_t{50}); root.set("repeat_penalty", 1.1); root.set("seed", std::int64_t{42}); - root.set("max_tokens", std::int64_t{400}); - root.add_object("chat_template_kwargs").set("enable_thinking", false); + root.set("max_tokens", static_cast(answer_token_cap)); + root.add_object("chat_template_kwargs").set("enable_thinking", true); return doc.write(); } diff --git a/projects/compass.http/src/query/sessions.cpp b/projects/compass.http/src/query/sessions.cpp index 8faec7fc..42cea003 100644 --- a/projects/compass.http/src/query/sessions.cpp +++ b/projects/compass.http/src/query/sessions.cpp @@ -195,7 +195,7 @@ std::optional get_agent_session( out.updated_at = std::string(session.value(0, 4)); const auto turns = c.exec( "SELECT id, ord, question, " + utc("asked_at") + - ", retrieval::text, answer, status, done::text, failure::text\n" + ", retrieval::text, answer, thought, status, done::text, failure::text\n" "FROM agent.agent_turn\n" "WHERE session_id = $1::bigint\n" "ORDER BY ord", @@ -210,14 +210,15 @@ std::optional get_agent_session( t.retrieval = read_event( turns.value(row, 4), "retrieval", t.id); t.answer = std::string(turns.value(row, 5)); - t.status = messages::agent_turn_status_of(turns.value(row, 6)) + t.thought = std::string(turns.value(row, 6)); + t.status = messages::agent_turn_status_of(turns.value(row, 7)) .value_or(messages::agent_turn_status::streaming); - if (!turns.is_null(row, 7)) - t.done = read_event( - turns.value(row, 7), "done event", t.id); if (!turns.is_null(row, 8)) + t.done = read_event( + turns.value(row, 8), "done event", t.id); + if (!turns.is_null(row, 9)) t.failure = read_event( - turns.value(row, 8), "failure event", t.id); + turns.value(row, 9), "failure event", t.id); out.turns.push_back(std::move(t)); } return out; @@ -272,6 +273,13 @@ std::optional load_agent_session( {number(session)}); if (last.rows() > 0) out.last_question = std::string(last.value(0, 0)); + const auto done = c.exec( + "SELECT count(*) FROM agent.agent_turn\n" + "WHERE session_id = $1::bigint AND status = 'done'", + {number(session)}); + if (done.rows() > 0) + std::from_chars(done.value(0, 0).data(), done.value(0, 0).data() + done.value(0, 0).size(), + out.done_turns); return out; } @@ -311,12 +319,13 @@ agent_begin_turn begin_agent_turn(io::connection& c, const domain::caller& who, return out; } -void save_agent_partial(io::connection& c, std::int64_t turn, std::string_view answer) { +void save_agent_partial(io::connection& c, std::int64_t turn, std::string_view answer, + std::string_view thought) { io::transaction tx(c); c.exec("UPDATE agent.agent_turn\n" - "SET answer = $2, updated_at = now()\n" + "SET answer = $2, thought = $3, updated_at = now()\n" "WHERE id = $1::bigint AND status = 'streaming'", - {number(turn), std::string(answer)}); + {number(turn), std::string(answer), std::string(thought)}); tx.commit(); } @@ -329,10 +338,10 @@ void finish_agent_turn(io::connection& c, const agent::turn_record& r) { failure = db::codec::wire_traits::write_json(*r.failure); io::transaction tx(c); c.exec("UPDATE agent.agent_turn\n" - "SET answer = $2, status = $3, done = $4::jsonb, failure = $5::jsonb,\n" + "SET answer = $2, thought = $3, status = $4, done = $5::jsonb, failure = $6::jsonb,\n" " updated_at = now()\n" "WHERE id = $1::bigint AND status = 'streaming'", - {number(r.turn), r.answer, status_of(r.end), done, failure}); + {number(r.turn), r.answer, r.thought, status_of(r.end), done, failure}); tx.commit(); } diff --git a/projects/compass.http/src/routes/agent_routes.cpp b/projects/compass.http/src/routes/agent_routes.cpp index 272d3c8e..b00436eb 100644 --- a/projects/compass.http/src/routes/agent_routes.cpp +++ b/projects/compass.http/src/routes/agent_routes.cpp @@ -46,7 +46,7 @@ compass::http::messages::agent_request bind_get_agent_answer(const domain::http_ void add_get_agent_answer(net::router& r, get_agent_answer_handler h) { r.add_route(r.get("/v1/{environment}/agent") .summary("Ask the compass agent") - .description("A question answered from the environment's documents inside the caller's view, as server-sent events (text/event-stream), each event's data one line of JSON: passages once, an agent_passages_event, the sections handed to the model; token, an agent_token_event, for each piece of the answer as the model writes it; then done, an agent_done_event, with the citations, or failure, an agent_failure_event, when the model's server cannot answer. A line that begins with a colon is a comment, sent every 15 seconds while the model is silent, and carries nothing. When no section matches, the model is still asked, and tells the user no document matched. A question searches at most twelve times. Four questions are answered at once; one more is refused with 503 busy.") + .description("A question answered from the environment's documents inside the caller's view, as server-sent events (text/event-stream), each event's data one line of JSON: passages once, an agent_passages_event, the sections handed to the model; thought, an agent_thought_event, for each piece of the model's reasoning as it thinks; token, an agent_token_event, for each piece of the answer as the model writes it; then done, an agent_done_event, with the citations, timings and context the answer used, or failure, an agent_failure_event, when the model's server cannot answer. A line that begins with a colon is a comment, sent every 15 seconds while the model is silent, and carries nothing. When no section matches, the model is still asked, and tells the user no document matched. A question searches at most twelve times. Four questions are answered at once; one more is refused with 503 busy.") .catalogue("get_agent_answer", "documents", "agent", false) .caller(domain::caller_need::view) .query_param("q", "string", "", true, "The question, at most 500 characters, counted as code points; an empty or longer one is refused as invalid.") diff --git a/projects/compass.http/tests/agent_llama_tests.cpp b/projects/compass.http/tests/agent_llama_tests.cpp index cc270e6b..f88f5048 100644 --- a/projects/compass.http/tests/agent_llama_tests.cpp +++ b/projects/compass.http/tests/agent_llama_tests.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -92,13 +93,14 @@ struct recording_sink final : agent::turn_sink { const std::lock_guard lock(mutex); terminals.push_back(std::move(r)); } - void record_partial(std::int64_t turn, std::string answer) noexcept override { + void record_partial(std::int64_t turn, std::string answer, + std::string thought) noexcept override { const std::lock_guard lock(mutex); - partials.emplace_back(turn, std::move(answer)); + partials.push_back({turn, std::move(answer), std::move(thought)}); } std::mutex mutex; std::vector terminals; - std::vector> partials; + std::vector> partials; }; } @@ -126,8 +128,8 @@ TEST_CASE("the agent streams the passages, the model's answer a piece at a time, CHECK(done->root().member("cited").element(0).integer() == 1); CHECK(done->root().member("cited").size() == 1); CHECK(done->root().member("dropped").element(0).integer() == 7); - CHECK(done->root().member("prompt_tokens").integer() == 120); - CHECK(done->root().member("generated_tokens").integer() == 12); + CHECK(done->root().member("prompt_tokens").integer() == 1234); + CHECK(done->root().member("generated_tokens").integer() == 56); CHECK(done->root().member("finish_reason").text() == "stop"); CHECK(done->root().member("first_token_ms").integer() > 0); @@ -137,6 +139,52 @@ TEST_CASE("the agent streams the passages, the model's answer a piece at a time, ContainsSubstring("[1] (knowledge) Hello › The log")); } +TEST_CASE("the agent streams the model's reasoning as thought events and settles it " + "with the answer", + "[agent][llama]") { + llama_stub stub(llama_stub::mode::ready, {"The log records the weather [1]."}, + {"First,", " I think."}); + const auto found = one_passage(); + auto sink = std::make_shared(); + agent::answer_options options; + options.turn = 7; + options.sink = sink; + options.context.context_tokens = 65536; + options.context.history_budget = 24000; + options.context.history_turns = 2; + options.context.history_bytes = 317; + options.context.dropped_turns = 3; + agent::answer_stream s(stub.settings(), found, event_of(found, 3), + "What does the keeper's log record?", {}, + std::chrono::steady_clock::now(), options); + const auto events = drain(s); + REQUIRE(events.size() == 5); + CHECK(events[0].name == "passages"); + CHECK(events[1].name == "thought"); + CHECK(events[1].data == R"({"text":"First,"})"); + CHECK(events[2].name == "thought"); + CHECK(events[2].data == R"({"text":" I think."})"); + CHECK(events[3].name == "token"); + CHECK(events[4].name == "done"); + const auto done = json_document::parse(events[4].data); + REQUIRE(done); + CHECK(done->root().member("context_tokens").integer() == 65536); + CHECK(done->root().member("history_budget").integer() == 24000); + CHECK(done->root().member("history_turns").integer() == 2); + CHECK(done->root().member("history_bytes").integer() == 317); + CHECK(done->root().member("dropped_turns").integer() == 3); + + REQUIRE(sink->terminals.size() == 1); + CHECK(sink->terminals.front().turn == 7); + CHECK(sink->terminals.front().answer == "The log records the weather [1]."); + CHECK(sink->terminals.front().thought == "First, I think."); + + const auto asked = json_document::parse(stub.last_body()); + REQUIRE(asked); + CHECK(asked->root().member("max_tokens").integer() == ops::answer_token_cap); + CHECK(asked->root().member("chat_template_kwargs").member("enable_thinking").flag() == true); +} + TEST_CASE("with no passages the agent still asks the model, which is told no document " "matched, and nothing is cited", "[agent][llama]") { @@ -655,9 +703,10 @@ TEST_CASE("a growing answer is snapshotted while it streams", "[agent][llama][si REQUIRE(sink->terminals.size() == 1); const auto& done = sink->terminals.front(); CHECK(done.end == agent::turn_end::done); - for (const auto& [turn, answer] : sink->partials) { + for (const auto& [turn, answer, thinking] : sink->partials) { CHECK(turn == 12); CHECK_FALSE(answer.empty()); + CHECK(thinking.empty()); CHECK(done.answer.starts_with(answer)); } } diff --git a/projects/compass.http/tests/llama_stub.hpp b/projects/compass.http/tests/llama_stub.hpp index f3d4915d..6733dfc9 100644 --- a/projects/compass.http/tests/llama_stub.hpp +++ b/projects/compass.http/tests/llama_stub.hpp @@ -54,9 +54,11 @@ class llama_stub final { public: enum class mode { ready, loading, slow, huge_error, endless_line }; - explicit llama_stub(mode m, std::vector pieces = {}) + explicit llama_stub(mode m, std::vector pieces = {}, + std::vector thoughts = {}) : mode_(m) , pieces_(std::move(pieces)) + , thoughts_(std::move(thoughts)) , acceptor_(io_, tcp::endpoint(asio::ip::make_address("127.0.0.1"), 0)) { thread_ = std::thread([this] { serve(); }); } @@ -151,6 +153,12 @@ class llama_stub final { return; } std::vector events; + for (const auto& p : thoughts_) { + auto doc = json_document::make_object(); + auto delta = doc.root().add_array("choices").push_object().add_object("delta"); + delta.set("reasoning_content", p); + events.push_back("data: " + doc.write() + "\n\n"); + } for (const auto& p : pieces_) { auto doc = json_document::make_object(); auto delta = doc.root().add_array("choices").push_object().add_object("delta"); @@ -160,6 +168,9 @@ class llama_stub final { events.push_back( R"(data: {"choices":[{"finish_reason":"stop","delta":{}}],"timings":{"prompt_n":120,"predicted_n":12,"predicted_per_second":5.5}})" "\n\n"); + events.push_back( + R"(data: {"choices":[],"usage":{"prompt_tokens":1234,"completion_tokens":56},"timings":{"prompt_n":120,"predicted_n":12,"predicted_per_second":5.5}})" + "\n\n"); events.push_back("data: [DONE]\n\n"); for (const auto& e : events) { std::this_thread::sleep_for(pause); @@ -172,6 +183,7 @@ class llama_stub final { mode mode_; std::vector pieces_; + std::vector thoughts_; asio::io_context io_; tcp::acceptor acceptor_; std::thread thread_; diff --git a/projects/compass.http/tests/messages_agent_protocol_tests.cpp b/projects/compass.http/tests/messages_agent_protocol_tests.cpp index edd267b4..dc378b20 100644 --- a/projects/compass.http/tests/messages_agent_protocol_tests.cpp +++ b/projects/compass.http/tests/messages_agent_protocol_tests.cpp @@ -293,6 +293,49 @@ TEST_CASE("agent_token_event's reader and JSON Schema refuse the same members", } } +static_assert(compass::db::codec::names_every_member(), + "agent_thought_event has a member its wire shape does not name"); + +TEST_CASE("agent_thought_event reads back the JSON it writes, which its JSON Schema " + "allows", "[codec][roundtrip][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + for (const auto which : {std::size_t(0), std::size_t(1)}) { + const auto v = compass::db::codec::sample(which); + const auto text = traits::write_json(v); + INFO(text); + CHECK(traits::read_json(text) == v); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); + } + const compass::http::messages::agent_thought_event empty{}; + const auto text = traits::write_json(empty); + INFO(text); + CHECK(traits::read_json(text) == empty); + CHECK(compass::db::codec::schema_violation(schema, text).value_or("") == ""); +} + +TEST_CASE("agent_thought_event's reader and JSON Schema refuse the same members", + "[codec][schema][protocol]") { + using traits = compass::db::codec::wire_traits; + const auto schema = compass::db::codec::json_schema(); + const auto text = traits::write_json(compass::db::codec::sample(0)); + const auto added = compass::db::codec::with_unknown_member(text); + CHECK_THROWS_AS(traits::read_json(added), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, added).has_value()); + for (const auto name : compass::db::codec::required_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_THROWS_AS(traits::read_json(removed), std::invalid_argument); + CHECK(compass::db::codec::schema_violation(schema, removed).has_value()); + } + for (const auto name : compass::db::codec::absent_members()) { + INFO(name); + const auto removed = compass::db::codec::without_member(text, name); + CHECK_NOTHROW(traits::read_json(removed)); + CHECK(compass::db::codec::schema_violation(schema, removed).value_or("") == ""); + } +} + static_assert(compass::db::codec::names_every_member(), "agent_done_event has a member its wire shape does not name"); diff --git a/projects/compass.http/tests/openapi_document_tests.cpp b/projects/compass.http/tests/openapi_document_tests.cpp index 39f9ea58..c7063a0e 100644 --- a/projects/compass.http/tests/openapi_document_tests.cpp +++ b/projects/compass.http/tests/openapi_document_tests.cpp @@ -376,8 +376,9 @@ TEST_CASE("the OpenAPI document says the agent answers server-sent events and na .member("get") .member("description") .text_or()); - for (const auto* named : {"text/event-stream", "agent_passages_event", "agent_token_event", - "agent_done_event", "agent_failure_event", "503"}) + for (const auto* named : {"text/event-stream", "agent_passages_event", "agent_thought_event", + "agent_token_event", "agent_done_event", "agent_failure_event", + "503"}) CHECK_THAT(described, Catch::Matchers::ContainsSubstring(named)); } diff --git a/projects/compass.http/tests/ops_agent_tests.cpp b/projects/compass.http/tests/ops_agent_tests.cpp index f7094bcb..40cb8b82 100644 --- a/projects/compass.http/tests/ops_agent_tests.cpp +++ b/projects/compass.http/tests/ops_agent_tests.cpp @@ -228,7 +228,9 @@ TEST_CASE("with no passages the model is still asked, told to say no document ma REQUIRE(body); const auto root = body->root(); CHECK(root.member("stream").flag() == true); - CHECK(root.member("max_tokens").integer() == 400); + CHECK(root.member("max_tokens").integer() == ops::answer_token_cap); + CHECK(root.member("chat_template_kwargs").member("enable_thinking").flag() == true); + CHECK(root.member("stream_options").member("include_usage").flag() == true); CHECK(root.member("messages").element(0).member("role").text() == "system"); CHECK(root.member("messages").element(1).member("content").text() == "Question: how do i build qwen"); @@ -286,9 +288,14 @@ TEST_CASE("the history keeps the newest exchanges that fit both caps, whole", TEST_CASE("the history budget is the context less the answer, prompt and slack", "[agent][ops]") { CHECK(ops::agent_history_budget(65536, 2000) == 24000); - CHECK(ops::agent_history_budget(4000, 2000) == (4000 - 400) * 4 - 2000 - 1024); + CHECK(ops::agent_history_budget(8000, 2000) == + (8000 - ops::answer_token_cap) * 4 - 2000 - 1024); + CHECK(ops::agent_history_budget(8000, 2000, 400) == 24000); CHECK(ops::agent_history_budget(1000, 2000) == 0); - CHECK(ops::agent_history_budget(400, 0) == 0); + CHECK(ops::agent_history_budget(ops::answer_token_cap, 0) == 0); + + const std::vector exchanges{{"q1", "an answer"}, {"q2", "another"}}; + CHECK(ops::agent_history_bytes(exchanges) == 2 + 9 + 2 + 7); } TEST_CASE("the prompt appends the session's exchanges before the current question", diff --git a/projects/compass.http/tests/query_reads_tests.cpp b/projects/compass.http/tests/query_reads_tests.cpp index 469e7c82..602ed48b 100644 --- a/projects/compass.http/tests/query_reads_tests.cpp +++ b/projects/compass.http/tests/query_reads_tests.cpp @@ -1111,7 +1111,9 @@ TEST_CASE("only a caller who runs the service is told where llama-server is and const auto knowledge = a.get("/v1/agent", "knowledge"); CHECK_THAT(knowledge.body, ContainsSubstring(R"("health":"not_running")")); CHECK_THAT(knowledge.body, ContainsSubstring(R"("model":"qwen.gguf")")); - CHECK_THAT(knowledge.body, ContainsSubstring(R"("server":"","health":"not_running","detail":"","start":"")")); + CHECK_THAT(knowledge.body, + ContainsSubstring( + R"("server":"","context_tokens":65536,"health":"not_running","detail":"","start":"")")); CHECK(knowledge.body.find("/secret") == std::string::npos); CHECK(knowledge.body.find("127.0.0.1") == std::string::npos); diff --git a/projects/compass.http/tests/query_sessions_tests.cpp b/projects/compass.http/tests/query_sessions_tests.cpp index 4bca1bbd..9b34a8cc 100644 --- a/projects/compass.http/tests/query_sessions_tests.cpp +++ b/projects/compass.http/tests/query_sessions_tests.cpp @@ -97,15 +97,22 @@ query::agent_begin_turn ask(db::io::connection& c, const domain::caller& who, json_of(passages()), "qwen.gguf"); } -agent::turn_record done_record(std::int64_t turn, std::string answer) { +agent::turn_record done_record(std::int64_t turn, std::string answer, + std::string thought = {}) { agent::turn_record r; r.turn = turn; r.answer = std::move(answer); + r.thought = std::move(thought); r.end = agent::turn_end::done; messages::agent_done_event d; d.cited = {1}; d.total_ms = 42; d.finish_reason = "stop"; + d.context_tokens = 65536; + d.history_budget = 24000; + d.history_turns = 1; + d.history_bytes = 42; + d.dropped_turns = 2; r.done = d; return r; } @@ -121,7 +128,7 @@ TEST_CASE("a session is created, listed, read and deleted within its triple", const auto titled = new_session(c, ana, " Given title "); static_cast(query::begin_agent_turn(c, ana, "main", first, "How do I build?", json_of(passages()), "qwen.gguf")); - query::finish_agent_turn(c, done_record(1, "With cmake [1].")); + query::finish_agent_turn(c, done_record(1, "With cmake [1].", "Build it first.")); messages::list_agent_sessions_request list; list.environment = "main"; @@ -147,10 +154,16 @@ TEST_CASE("a session is created, listed, read and deleted within its triple", CHECK(read->turns[0].ord == 1); CHECK(read->turns[0].question == "How do I build?"); CHECK(read->turns[0].answer == "With cmake [1]."); + CHECK(read->turns[0].thought == "Build it first."); CHECK(read->turns[0].status == messages::agent_turn_status::done); CHECK(read->turns[0].retrieval == passages()); REQUIRE(read->turns[0].done); CHECK(read->turns[0].done->cited == std::vector{1}); + CHECK(read->turns[0].done->context_tokens == 65536); + CHECK(read->turns[0].done->history_budget == 24000); + CHECK(read->turns[0].done->history_turns == 1); + CHECK(read->turns[0].done->history_bytes == 42); + CHECK(read->turns[0].done->dropped_turns == 2); CHECK_FALSE(read->turns[0].failure); messages::delete_agent_session_request del; @@ -236,7 +249,7 @@ TEST_CASE("a partial answer is visible while streaming, and the terminal record const auto session = new_session(c, ana); const auto began = ask(c, ana, session, "Q?"); - query::save_agent_partial(c, began.turn, "Half"); + query::save_agent_partial(c, began.turn, "Half", "Thinking"); messages::get_agent_session_request get; get.environment = "main"; get.session = session; @@ -245,9 +258,10 @@ TEST_CASE("a partial answer is visible while streaming, and the terminal record REQUIRE(read->turns.size() == 1); CHECK(read->turns[0].status == messages::agent_turn_status::streaming); CHECK(read->turns[0].answer == "Half"); + CHECK(read->turns[0].thought == "Thinking"); query::finish_agent_turn(c, done_record(began.turn, "Whole [1].")); - query::save_agent_partial(c, began.turn, "late"); + query::save_agent_partial(c, began.turn, "late", ""); query::finish_agent_turn(c, done_record(began.turn, "later")); read = query::get_agent_session(c, ana, get); REQUIRE(read); @@ -331,6 +345,13 @@ TEST_CASE("history holds only done exchanges, oldest first, and the last questio CHECK(state->history[1].question == "Three?"); CHECK(state->history[1].answer == "Answer three [2]."); CHECK(state->last_question == "Three?"); + CHECK(state->done_turns == 2); + + const auto newest = query::load_agent_session(c, ana, "main", session, 1); + REQUIRE(newest); + REQUIRE(newest->history.size() == 1); + CHECK(newest->history[0].question == "Three?"); + CHECK(newest->done_turns == 2); } TEST_CASE("a stored event that is not the one compass wrote is an error", "[http][sessions]") { diff --git a/projects/compass.http/tests/turn_writer_tests.cpp b/projects/compass.http/tests/turn_writer_tests.cpp index 42a4764f..12a7ec88 100644 --- a/projects/compass.http/tests/turn_writer_tests.cpp +++ b/projects/compass.http/tests/turn_writer_tests.cpp @@ -72,10 +72,12 @@ std::int64_t new_turn(db::io::connection& c, const std::string& question) { .turn; } -agent::turn_record done_record(std::int64_t turn, std::string answer) { +agent::turn_record done_record(std::int64_t turn, std::string answer, + std::string thought = {}) { agent::turn_record r; r.turn = turn; r.answer = std::move(answer); + r.thought = std::move(thought); r.end = agent::turn_end::done; messages::agent_done_event d; d.cited = {1}; @@ -94,13 +96,16 @@ TEST_CASE("the writer settles a turn through the pool and waits when asked to fl app::connection_pool pool(conninfo); agent::turn_writer writer(pool); - writer.record(done_record(turn, "Answer [1].")); + writer.record(done_record(turn, "Answer [1].", "I thought [first].")); writer.flush(); CHECK(writer.dropped() == 0); - CHECK(c.exec("SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", - {std::to_string(turn)}) - .value(0, 0) == "done"); + const auto settled = c.exec( + "SELECT status, answer, thought FROM agent.agent_turn WHERE id = $1::bigint", + {std::to_string(turn)}); + CHECK(settled.value(0, 0) == "done"); + CHECK(settled.value(0, 1) == "Answer [1]."); + CHECK(settled.value(0, 2) == "I thought [first]."); } TEST_CASE("a partial settles while streaming, and the terminal record replaces it", @@ -111,21 +116,23 @@ TEST_CASE("a partial settles while streaming, and the terminal record replaces i app::connection_pool pool(conninfo); agent::turn_writer writer(pool); - writer.record_partial(turn, "Half"); + writer.record_partial(turn, "Half", "Thinking"); writer.flush(); const auto streaming = c.exec( - "SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", + "SELECT status, answer, thought FROM agent.agent_turn WHERE id = $1::bigint", {std::to_string(turn)}); CHECK(streaming.value(0, 0) == "streaming"); CHECK(streaming.value(0, 1) == "Half"); + CHECK(streaming.value(0, 2) == "Thinking"); - writer.record(done_record(turn, "Whole [1].")); + writer.record(done_record(turn, "Whole [1].", "Thought it through.")); writer.flush(); const auto done = c.exec( - "SELECT status, answer FROM agent.agent_turn WHERE id = $1::bigint", + "SELECT status, answer, thought FROM agent.agent_turn WHERE id = $1::bigint", {std::to_string(turn)}); CHECK(done.value(0, 0) == "done"); CHECK(done.value(0, 1) == "Whole [1]."); + CHECK(done.value(0, 2) == "Thought it through."); } TEST_CASE("the writer drains what it holds when it stops", "[http][writer]") { From 833fc964918c37261f6f55959729e291214e2bf1 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 13:33:43 +0000 Subject: [PATCH 17/24] [web] Draw the conversations, the thinking and the context beside the agent The Agent screen gets Gemini's sessions panel: New conversation at the top, the caller's conversations with the open one highlighted, and a delete for it; it stacks above the transcript at phone width, and the host's side panel keeps the compact bar. Each turn shows a collapsed Thinking element that opens to the whole reasoning, and the panel measures the context from the done event's counts and the history the prompt kept, naming the turns the window dropped. Co-Authored-By: Claude Code --- .../packages/pages/src/AgentPanel.tsx | 371 +++++++++++++++--- .../packages/pages/src/agent.test.tsx | 79 +++- .../compass.web/packages/pages/src/agent.ts | 50 +++ .../packages/pages/src/client.test.ts | 16 +- .../compass.web/packages/pages/src/client.ts | 11 + .../packages/pages/src/conversation.tsx | 28 +- .../compass.web/packages/pages/src/i18n/en.ts | 23 ++ .../compass.web/packages/pages/src/i18n/fr.ts | 23 ++ .../compass.web/packages/pages/src/i18n/pt.ts | 23 ++ .../packages/web/e2e/agent.spec.ts | 44 +++ .../packages/web/e2e/llama_stub.mjs | 12 + 11 files changed, 630 insertions(+), 50 deletions(-) diff --git a/projects/compass.web/packages/pages/src/AgentPanel.tsx b/projects/compass.web/packages/pages/src/AgentPanel.tsx index 2d2644a6..d38632ed 100644 --- a/projects/compass.web/packages/pages/src/AgentPanel.tsx +++ b/projects/compass.web/packages/pages/src/AgentPanel.tsx @@ -25,9 +25,11 @@ import { answerBlocks, citedPassage, clipQuestion, + contextUsageOf, formatSeconds, sources, statusText, + type ContextUsage, type Inline, type Turn, type TurnEnd, @@ -36,6 +38,7 @@ import { CompassRequestError, retryable, UNREADABLE, + type AgentSessionSummary, type AgentStatus, type DoneEvent, type Passage, @@ -53,24 +56,26 @@ const TICK_MS = 100; /** * The compass agent, as the agent panel prototype signed off: its model and * the health of its llama-server, the conversation so far, oldest first, and - * a box for the next question. The Agent screen draws it at the width of the - * screen and a host's shell beside any screen; both show the one conversation. + * a box for the next question. The Agent screen draws it beside a sessions + * panel; a host's shell draws it alone with a compact conversation bar. * @p onClose, when given, draws a button that closes the panel, * @p onFollow is called when the person follows a link to a document, and * @p initialQuestion, when given, is asked once as the panel mounts. + * @p sessionsBar draws the compact bar that names, makes and deletes a + * conversation; the Agent screen turns it off for its sessions panel. */ export function AgentPanel({ environment, initialQuestion, onClose, onFollow, - onSessionDeleted, + sessionsBar = true, }: { readonly environment: string; readonly initialQuestion?: string; readonly onClose?: () => void; readonly onFollow?: () => void; - readonly onSessionDeleted?: () => void; + readonly sessionsBar?: boolean; }): ReactNode { const { t } = useTranslation(); const { turns, ask, missing, environment: openEnvironment, open } = useConversation(); @@ -111,10 +116,7 @@ export function AgentPanel({ data-testid="agent-panel" > - + {sessionsBar ? : null} {missing ? (

{t('agent.sessions.missing')} @@ -170,22 +172,25 @@ export function AgentPanel({ ); } +function whenLabel(language: string, iso: string): string { + const at = new Date(iso); + return Number.isNaN(at.getTime()) + ? iso + : new Intl.DateTimeFormat(language, { + dateStyle: 'short', + timeStyle: 'short', + }).format(at); +} + /** - * The conversations a person may open, and the controls that make a new one - * or delete the open one. A conversation created here becomes the provider's - * selection; the Agent screen puts it in the address, and a host's shell - * shows it beside its screen. + * The compact conversation bar a host's shell and a phone use: a select of + * the caller's conversations and controls that make a new one or delete the + * open one. The Agent screen replaces it with the sessions panel at the + * width that fits one. */ -function SessionBar({ - environment, - onDeleted, -}: { - readonly environment: string; - readonly onDeleted?: () => void; -}): ReactNode { +function SessionBar({ environment }: { readonly environment: string }): ReactNode { const { t, language } = useTranslation(); - const { client } = useCompass(); - const { session, sessions, open, remove } = useConversation(); + const { session, sessions, open, create, remove } = useConversation(); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); @@ -193,8 +198,7 @@ function SessionBar({ setBusy(true); setError(null); try { - const made = await client.createAgentSession(environment); - open(environment, made.session); + await create(environment); } catch (failure) { setError( t('agent.sessions.failed', { @@ -214,7 +218,6 @@ function SessionBar({ setError(null); try { await remove(); - onDeleted?.(); } catch (failure) { setError( t('agent.sessions.failed', { @@ -226,15 +229,7 @@ function SessionBar({ } }; - const when = (iso: string): string => { - const at = new Date(iso); - return Number.isNaN(at.getTime()) - ? iso - : new Intl.DateTimeFormat(language, { - dateStyle: 'short', - timeStyle: 'short', - }).format(at); - }; + const when = (iso: string): string => whenLabel(language, iso); return (

@@ -447,6 +442,7 @@ export function TurnView({ {turn.question}

+ {turn.text === '' ? null : } {turn.end === null ? null : } {turn.end !== null && turn.retrieval !== null ? ( @@ -456,6 +452,43 @@ export function TurnView({ ); } +/** + * The model's reasoning, collapsed: a one-line summary while it thinks and + * after it settles, which opens to the whole reasoning. It is never part of + * the answer and never cites anything. + */ +function Thinking({ turn }: { readonly turn: Turn }): ReactNode { + const { t, language } = useTranslation(); + if (turn.thought === '') { + return null; + } + const live = turn.end === null && turn.text === ''; + const summary = live + ? t('agent.thinking') + : turn.end?.kind === 'done' + ? t('agent.thought', { + seconds: formatSeconds(turn.end.done.first_token_ms, language), + }) + : t('agent.thoughts'); + return ( +
+ + {summary} + +
+ {turn.thought} +
+
+ ); +} + function Ending({ turn, end, @@ -801,10 +834,250 @@ function Given({ retrieval }: { readonly retrieval: PassagesEvent }): ReactNode } /** - * The Agent screen: the panel at the width of a reading column, its - * conversation in the address as ?session=, so a reload restores it. Opening - * the address restores that conversation; a conversation made in the panel is - * put there; a conversation deleted leaves the address without one. + * The conversations panel beside the Agent screen, as Gemini's sidebar: a + * new-conversation control at the top, the caller's conversations with the + * open one highlighted, a delete for it, and what the last answer used of + * the model's context. At phone width it stacks above the transcript. + */ +export function SessionsPanel({ + environment, + onDeleted, +}: { + readonly environment: string; + readonly onDeleted?: () => void; +}): ReactNode { + const { t, language } = useTranslation(); + const { inputs, client } = useCompass(); + const { session, sessions, turns, open, create, remove } = useConversation(); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const status = useQuery({ + queryKey: agentStatusKey(inputs.httpBase), + queryFn: client.agent, + retry: retryable, + refetchInterval: (query) => (query.state.data?.health === 'ready' ? false : STATUS_POLL_MS), + }); + const usage = contextUsageOf(turns); + const contextTokens = usage?.context_tokens ?? status.data?.context_tokens ?? 0; + + const created = async () => { + setBusy(true); + setError(null); + try { + await create(environment); + } catch (failure) { + setError( + t('agent.sessions.failed', { + reason: failure instanceof Error ? failure.message : String(failure), + }), + ); + } finally { + setBusy(false); + } + }; + + const deleted = async () => { + if (session === null || !globalThis.confirm(t('agent.sessions.confirmDelete'))) { + return; + } + setBusy(true); + setError(null); + try { + await remove(); + onDeleted?.(); + } catch (failure) { + setError( + t('agent.sessions.failed', { + reason: failure instanceof Error ? failure.message : String(failure), + }), + ); + } finally { + setBusy(false); + } + }; + + return ( + + ); +} + +function SessionRow({ + summary, + selected, + language, + onOpen, + onDelete, + busy = false, +}: { + readonly summary: AgentSessionSummary; + readonly selected: boolean; + readonly language: string; + readonly onOpen: () => void; + readonly onDelete?: () => void; + readonly busy?: boolean; +}): ReactNode { + const { t } = useTranslation(); + return ( +
  • + + {onDelete === undefined ? null : ( + + )} +
  • + ); +} + +/** + * What the conversation's last answer used and what it left, from + * llama-server's own token counts and the server's history budget. The + * history window is the compaction: it keeps the newest eight done turns + * within the byte budget and drops the rest, and the panel says how many + * were dropped. + */ +function ContextPanel({ + usage, + contextTokens, +}: { + readonly usage: ContextUsage | null; + readonly contextTokens: number; +}): ReactNode { + const { t, language, plural } = useTranslation(); + const number = (value: number) => new Intl.NumberFormat(language).format(value); + if (contextTokens === 0 && usage === null) { + return null; + } + return ( +
    +

    + {t('agent.context.title')} +

    +

    + {t('agent.context.window', { tokens: number(contextTokens) })} +

    + {usage === null ? ( +

    {t('agent.context.none')}

    + ) : ( + <> +

    + {t('agent.context.last', { + used: number(usage.used_tokens), + left: number(usage.left_tokens), + })} +

    +

    + {t('agent.context.lastDetail', { + prompt: number(usage.prompt_tokens), + generated: number(usage.generated_tokens), + })} +

    + {usage.history_budget === 0 ? null : ( +

    + {plural('agent.context.history', usage.history_turns, { + used: number(usage.history_bytes), + budget: number(usage.history_budget), + })} +

    + )} + {usage.dropped_turns === 0 ? null : ( +

    + {plural('agent.context.dropped', usage.dropped_turns)} +

    + )} + + )} +

    {t('agent.context.measure')}

    +
    + ); +} + +/** + * The Agent screen: the panel at the width of a reading column and the + * sessions panel beside it, its conversation in the address as ?session=, so + * a reload restores it. Opening the address restores that conversation; a + * conversation made in the panel is put there; a conversation deleted leaves + * the address without one. */ export function AgentScreen({ environment }: { readonly environment: string }): ReactNode { const [params] = useSearchParams(); @@ -823,14 +1096,22 @@ export function AgentScreen({ environment }: { readonly environment: string }): }, [session, wanted, environment, navigate]); return ( -
    - - navigate(linkTo({ environment, screen: 'agent' }), { replace: true }) - } - /> +
    +
    + +
    +
    + + navigate(linkTo({ environment, screen: 'agent' }), { replace: true }) + } + /> +
    ); } diff --git a/projects/compass.web/packages/pages/src/agent.test.tsx b/projects/compass.web/packages/pages/src/agent.test.tsx index e35d5596..60e71684 100644 --- a/projects/compass.web/packages/pages/src/agent.test.tsx +++ b/projects/compass.web/packages/pages/src/agent.test.tsx @@ -30,6 +30,7 @@ import { answerBlocks, citedPassage, clipQuestion, + contextUsageOf, conversationReducer, sources, statusText, @@ -38,7 +39,7 @@ import { UNFINISHED_MS, type Turn, } from './agent.js'; -import { AgentPanel, AgentScreen, TurnView } from './AgentPanel.js'; +import { AgentPanel, AgentScreen, SessionsPanel, TurnView } from './AgentPanel.js'; import { createClient, createFrameReader, @@ -87,6 +88,11 @@ const done: DoneEvent = { generated_tokens: 40, tokens_per_second: 4.9, finish_reason: 'stop', + context_tokens: 65536, + history_budget: 24000, + history_turns: 2, + history_bytes: 317, + dropped_turns: 3, }; const asked: Turn = { @@ -96,6 +102,7 @@ const asked: Turn = { asked: 0, retrieval: null, text: '', + thought: '', end: null, }; @@ -111,6 +118,7 @@ const passages = (...given: Passage[]): AgentEvent => ({ data: { queries: ['keeper log'], passages: given, retrieval_ms: 12 }, }); const token = (text: string): AgentEvent => ({ event: 'token', data: { text } }); +const thought = (text: string): AgentEvent => ({ event: 'thought', data: { text } }); describe('the frame reader', () => { it('reads a frame split across reads, at any byte', () => { @@ -355,6 +363,15 @@ describe('the status line', () => { ).toBe('Answered in 20 s'); }); + it('says it thinks while only the reasoning has arrived', () => { + expect(statusText(play(passages(hello), thought('I think')), 3000, english)).toBe( + 'Thinking · 3.0 s', + ); + expect( + statusText(play(passages(hello), thought('I think'), token('The')), 3000, english), + ).toBe('Writing'); + }); + it('is gone once the answer failed, which says why instead', () => { const failed = play(passages(hello), { event: 'failure', @@ -443,12 +460,66 @@ describe('the chips of an answer', () => { }); }); +describe('the model thinking', () => { + it('shows the reasoning in a collapsed element, summarised while it thinks', () => { + const live = play(passages(hello), thought('I check the log.')); + const liveHtml = draw(); + expect(liveHtml).toContain('data-testid="agent-thinking"'); + expect(liveHtml).toContain('data-live'); + expect(liveHtml).toContain(enFlat['agent.thinking']); + expect(liveHtml).toContain('I check the log.'); + expect(liveHtml).not.toContain(' open='); + + const doneTurn = play(passages(hello), thought('I check the log.'), token('The log.')); + const doneHtml = draw(); + expect(doneHtml).toContain('I check the log.'); + expect(doneHtml).not.toContain(enFlat['agent.thinking']); + }); + + it('measures the context from the last answered turn, dropped turns included', () => { + const turn = play(passages(hello), thought('I check.'), token('The log [1].'), { + event: 'done', + data: done, + }); + expect(contextUsageOf([turn])).toEqual({ + context_tokens: 65536, + prompt_tokens: 600, + generated_tokens: 40, + used_tokens: 640, + left_tokens: 64896, + history_budget: 24000, + history_turns: 2, + history_bytes: 317, + dropped_turns: 3, + }); + expect(contextUsageOf([asked])).toBeNull(); + }); + + it('shows the context indicator with its window, use and dropped turns', () => { + const html = draw(, status); + expect(html).toContain('data-testid="agent-context"'); + expect(html).toContain('65,536 token window'); + expect(html).toContain(enFlat['agent.context.none']); + expect(html).toContain(enFlat['agent.context.measure']); + }); + + it('writes the history count into the plural message', () => { + expect(english.plural('agent.context.history', 2, { used: '10', budget: '20' })).toBe( + 'History kept 2 turns, 10 of 20 bytes.', + ); + expect(english.plural('agent.context.history', 1, { used: '10', budget: '20' })).toBe( + 'History kept 1 turn, 10 of 20 bytes.', + ); + }); +}); + const status: AgentStatus = { model: 'Qwen2.5-7B-Instruct-Q4_K_M.gguf', server: '127.0.0.1:8081', health: 'ready', detail: '', start: 'llama-server --model qwen.gguf --host 127.0.0.1 --port 8081', + context_tokens: 65536, }; describe('the agent initial question', () => { @@ -616,6 +687,7 @@ const storedSession: GetAgentSessionResponse = { asked_at: '2026-12-02T10:00:00Z', retrieval: { queries: [], passages: [], retrieval_ms: 1 }, answer: 'A [1].', + thought: 'I thought about it.', status: 'done', done, failure: null, @@ -626,6 +698,7 @@ const storedSession: GetAgentSessionResponse = { question: 'Failed?', asked_at: '2026-12-02T10:00:01Z', retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + thought: '', answer: '', status: 'failed', done: null, @@ -637,6 +710,7 @@ const storedSession: GetAgentSessionResponse = { question: 'Stopped?', asked_at: '2026-12-02T10:00:02Z', retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + thought: '', answer: 'Half', status: 'stopped', done: null, @@ -648,6 +722,7 @@ const storedSession: GetAgentSessionResponse = { question: 'Cut?', asked_at: '2026-12-02T10:00:03Z', retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + thought: '', answer: '', status: 'cut', done: null, @@ -659,6 +734,7 @@ const storedSession: GetAgentSessionResponse = { question: 'Streaming?', asked_at: new Date().toISOString(), retrieval: { queries: [], passages: [], retrieval_ms: 1 }, + thought: '', answer: 'Half', status: 'streaming', done: null, @@ -678,6 +754,7 @@ describe('a restored conversation', () => { 'cut', ]); expect(turns[0]?.retrieval?.retrieval_ms).toBe(1); + expect(turns[0]?.thought).toBe('I thought about it.'); expect(turns[0]?.end).toEqual({ kind: 'done', done }); expect(turns[1]?.end).toEqual({ kind: 'failure', diff --git a/projects/compass.web/packages/pages/src/agent.ts b/projects/compass.web/packages/pages/src/agent.ts index 30a793a2..ea20d8a1 100644 --- a/projects/compass.web/packages/pages/src/agent.ts +++ b/projects/compass.web/packages/pages/src/agent.ts @@ -43,6 +43,7 @@ export interface Turn { readonly asked: number; readonly retrieval: PassagesEvent | null; readonly text: string; + readonly thought: string; readonly end: TurnEnd | null; } @@ -56,6 +57,8 @@ function applyEvent(turn: Turn, event: AgentEvent): Turn { switch (event.event) { case 'passages': return { ...turn, retrieval: event.data }; + case 'thought': + return { ...turn, thought: turn.thought + event.data.text }; case 'token': return { ...turn, text: turn.text + event.data.text }; case 'done': @@ -128,10 +131,54 @@ export function turnsOf(session: GetAgentSessionResponse): Turn[] { asked: Date.parse(turn.asked_at), retrieval: turn.retrieval, text: turn.answer, + thought: turn.thought, end: endOf(turn), })); } +/** + * What the conversation's last answered turn used, from llama-server's own + * timings: the prompt it read and everything it generated, reasoning + * included, against the model's context window; and the earlier exchanges + * that turn's prompt kept, of the session's done exchanges, and the ones the + * history window left out. + */ +export interface ContextUsage { + readonly context_tokens: number; + readonly prompt_tokens: number; + readonly generated_tokens: number; + readonly used_tokens: number; + readonly left_tokens: number; + readonly history_budget: number; + readonly history_turns: number; + readonly history_bytes: number; + readonly dropped_turns: number; +} + +/** The context the last answered turn used, or null before one. */ +export function contextUsageOf(turns: readonly Turn[]): ContextUsage | null { + for (let i = turns.length - 1; i >= 0; --i) { + const end = turns[i]?.end; + if (end?.kind !== 'done' || end.done.context_tokens === 0) { + continue; + } + const done = end.done; + const used = done.prompt_tokens + done.generated_tokens; + return { + context_tokens: done.context_tokens, + prompt_tokens: done.prompt_tokens, + generated_tokens: done.generated_tokens, + used_tokens: used, + left_tokens: Math.max(0, done.context_tokens - used), + history_budget: done.history_budget, + history_turns: done.history_turns, + history_bytes: done.history_bytes, + dropped_turns: done.dropped_turns, + }; + } + return null; +} + const QUESTION_LIMIT = 500; /** @@ -256,6 +303,9 @@ export function statusText( if (turn.text !== '') { return t('agent.writing'); } + if (turn.thought !== '') { + return t('agent.thinkingStatus', { seconds }); + } if (turn.retrieval === null) { return t('agent.searching', { seconds }); } diff --git a/projects/compass.web/packages/pages/src/client.test.ts b/projects/compass.web/packages/pages/src/client.test.ts index 1f8d869d..0a561c17 100644 --- a/projects/compass.web/packages/pages/src/client.test.ts +++ b/projects/compass.web/packages/pages/src/client.test.ts @@ -313,6 +313,7 @@ describe("the agent's conversations", () => { asked_at: '2026-12-02T10:00:00Z', retrieval: { queries: ['log'], passages: [], retrieval_ms: 3 }, answer: 'The weather [1].', + thought: 'The log names the weather.', status: 'done', done: { cited: [1], @@ -323,6 +324,11 @@ describe("the agent's conversations", () => { generated_tokens: 4, tokens_per_second: 5, finish_reason: 'stop', + context_tokens: 65536, + history_budget: 24000, + history_turns: 1, + history_bytes: 42, + dropped_turns: 2, }, failure: null, }; @@ -341,6 +347,7 @@ describe("the agent's conversations", () => { asked_at: '2026-12-02T10:01:00Z', retrieval: { queries: [], passages: [], retrieval_ms: 1 }, answer: '', + thought: '', status: 'cut', done: null, failure: null, @@ -412,10 +419,13 @@ describe("the agent's conversations", () => { asked.push({ url: String(input), init }); return Promise.resolve( new Response( - 'event: token\ndata: {"text":"The weather"}\n\n' + + 'event: thought\ndata: {"text":"The log names the weather."}\n\n' + + 'event: token\ndata: {"text":"The weather"}\n\n' + 'event: done\ndata: {"cited":[1],"dropped":[],"first_token_ms":1,' + '"total_ms":2,"prompt_tokens":3,"generated_tokens":4,' + - '"tokens_per_second":5,"finish_reason":"stop"}\n\n', + '"tokens_per_second":5,"finish_reason":"stop",' + + '"context_tokens":65536,"history_budget":24000,' + + '"history_turns":1,"history_bytes":42,"dropped_turns":0}\n\n', { status: 200 }, ), ); @@ -432,7 +442,7 @@ describe("the agent's conversations", () => { expect(asked[0]?.url).toBe('/v1/compass/agent/sessions/7/ask'); expect(asked[0]?.init?.method).toBe('POST'); expect(asked[0]?.init?.body).toBe('{"q":"and why?"}'); - expect(events).toEqual(['token', 'done']); + expect(events).toEqual(['thought', 'token', 'done']); }); it('surfaces a 404 for a conversation of another caller as the refusal it is', async () => { diff --git a/projects/compass.web/packages/pages/src/client.ts b/projects/compass.web/packages/pages/src/client.ts index 79356320..75b67d30 100644 --- a/projects/compass.web/packages/pages/src/client.ts +++ b/projects/compass.web/packages/pages/src/client.ts @@ -337,6 +337,7 @@ export const agentStatusSchema = z.object({ health: z.enum(AGENT_HEALTHS), detail: z.string(), start: z.string(), + context_tokens: count, }); export const passageSchema = z.object({ @@ -358,6 +359,9 @@ export const passagesEventSchema = z.object({ export const tokenEventSchema = z.object({ text: z.string() }); +/** The model's reasoning, as llama-server streams it before the answer. */ +export const thoughtEventSchema = z.object({ text: z.string() }); + export const doneEventSchema = z.object({ cited: z.array(z.number().int()), dropped: z.array(z.number().int()), @@ -367,6 +371,11 @@ export const doneEventSchema = z.object({ generated_tokens: count, tokens_per_second: z.number().nonnegative(), finish_reason: z.string(), + context_tokens: count, + history_budget: count, + history_turns: count, + history_bytes: count, + dropped_turns: count, }); export const failureEventSchema = z.object({ @@ -377,6 +386,7 @@ export const failureEventSchema = z.object({ /** An event of an answer, by the name its server-sent frame gives it. */ export const agentEventSchema = z.discriminatedUnion('event', [ z.object({ event: z.literal('passages'), data: passagesEventSchema }), + z.object({ event: z.literal('thought'), data: thoughtEventSchema }), z.object({ event: z.literal('token'), data: tokenEventSchema }), z.object({ event: z.literal('done'), data: doneEventSchema }), z.object({ event: z.literal('failure'), data: failureEventSchema }), @@ -427,6 +437,7 @@ export const agentTurnSchema = z.object({ asked_at: z.string(), retrieval: passagesEventSchema, answer: z.string(), + thought: z.string(), status: agentTurnStatusSchema, done: doneEventSchema.nullable(), failure: failureEventSchema.nullable(), diff --git a/projects/compass.web/packages/pages/src/conversation.tsx b/projects/compass.web/packages/pages/src/conversation.tsx index 229f8d6b..6a7c6795 100644 --- a/projects/compass.web/packages/pages/src/conversation.tsx +++ b/projects/compass.web/packages/pages/src/conversation.tsx @@ -73,6 +73,8 @@ interface ConversationValue { readonly missing: boolean; readonly ask: (environment: string, question: string) => void; readonly open: (environment: string, session: number | null) => void; + /** Makes and opens an empty conversation. */ + readonly create: (environment: string) => Promise; /** Deletes the open conversation and starts a new, empty one. */ readonly remove: () => Promise; } @@ -194,6 +196,7 @@ export function ConversationProvider({ asked: Date.now(), retrieval: null, text: '', + thought: '', end: null, }, }); @@ -227,6 +230,7 @@ export function ConversationProvider({ asked: Date.now(), retrieval: null, text: '', + thought: '', end: null, }, }); @@ -270,6 +274,17 @@ export function ConversationProvider({ [client, httpBase, queries], ); + const create = useCallback( + async (environment: string) => { + const made = await client.createAgentSession(environment); + open(environment, made.session); + await queries.invalidateQueries({ + queryKey: agentSessionsKey(httpBase, environment), + }); + }, + [client, httpBase, open, queries], + ); + const remove = useCallback(async () => { const { environment, session } = current.current; if (environment === null || session === null) { @@ -300,9 +315,20 @@ export function ConversationProvider({ missing, ask, open, + create, remove, }), - [opened.environment, opened.session, sessions.data, turns, missing, ask, open, remove], + [ + opened.environment, + opened.session, + sessions.data, + turns, + missing, + ask, + open, + create, + remove, + ], ); return {children}; } diff --git a/projects/compass.web/packages/pages/src/i18n/en.ts b/projects/compass.web/packages/pages/src/i18n/en.ts index cff34a96..8010b899 100644 --- a/projects/compass.web/packages/pages/src/i18n/en.ts +++ b/projects/compass.web/packages/pages/src/i18n/en.ts @@ -458,8 +458,10 @@ export const en: Catalogue = { ask: 'Ask', close: 'Close the compass agent', sessions: { + title: 'Conversations', label: 'Conversation', none: 'No conversation', + empty: 'No conversations yet.', create: 'New conversation', untitled: 'Untitled conversation', delete: 'Delete conversation', @@ -468,6 +470,27 @@ export const en: Catalogue = { 'This conversation is not available to you in this view. Choose another, or start a new one.', failed: 'compass.http did not answer the conversation: {reason}', }, + context: { + title: 'Context', + window: '{tokens} token window', + none: 'The first answer shows what it uses.', + last: 'Last answer used {used} tokens; {left} left.', + lastDetail: '{prompt} prompt and {generated} generated, reasoning included.', + history: { + one: 'History kept {count} turn, {used} of {budget} bytes.', + other: 'History kept {count} turns, {used} of {budget} bytes.', + }, + dropped: { + one: '{count} earlier turn was not sent; the window keeps the newest eight within the byte budget.', + other: '{count} earlier turns were not sent; the window keeps the newest eight within the byte budget.', + }, + measure: + 'Counts are llama-server’s own for the last answered turn, against the model’s window. The history window is the compaction: older turns are dropped, not summarised.', + }, + thinkingStatus: 'Thinking · {seconds} s', + thinking: 'Thinking…', + thought: 'Thought for {seconds} s', + thoughts: 'Thoughts', statusReading: "Reading the agent's status…", statusFailed: "compass.http did not answer the agent's status: {reason}", statusUnreadable: diff --git a/projects/compass.web/packages/pages/src/i18n/fr.ts b/projects/compass.web/packages/pages/src/i18n/fr.ts index 2e928ba7..04ccb575 100644 --- a/projects/compass.web/packages/pages/src/i18n/fr.ts +++ b/projects/compass.web/packages/pages/src/i18n/fr.ts @@ -469,8 +469,10 @@ const fr: Catalogue = { ask: 'Demander', close: "Fermer l'agent de compass", sessions: { + title: 'Conversations', label: 'Conversation', none: 'Aucune conversation', + empty: 'Aucune conversation pour l’instant.', create: 'Nouvelle conversation', untitled: 'Conversation sans titre', delete: 'Supprimer la conversation', @@ -479,6 +481,27 @@ const fr: Catalogue = { 'Cette conversation ne vous est pas accessible dans cette vue. Choisissez-en une autre ou commencez-en une nouvelle.', failed: "compass.http n'a pas répondu pour la conversation : {reason}", }, + context: { + title: 'Contexte', + window: 'fenêtre de {tokens} tokens', + none: 'La première réponse montrera ce qu’elle utilise.', + last: 'La dernière réponse a utilisé {used} tokens ; {left} restants.', + lastDetail: '{prompt} de prompt et {generated} générés, raisonnement compris.', + history: { + one: 'L’historique a gardé {count} échange, {used} sur {budget} octets.', + other: 'L’historique a gardé {count} échanges, {used} sur {budget} octets.', + }, + dropped: { + one: '{count} échange antérieur n’a pas été envoyé ; la fenêtre garde les huit plus récents dans le budget d’octets.', + other: '{count} échanges antérieurs n’ont pas été envoyés ; la fenêtre garde les huit plus récents dans le budget d’octets.', + }, + measure: + 'Les comptes sont ceux de llama-server pour la dernière réponse, comparés à la fenêtre du modèle. La fenêtre d’historique est la compaction : les échanges plus anciens sont abandonnés, pas résumés.', + }, + thinkingStatus: 'Réflexion · {seconds} s', + thinking: 'Réflexion…', + thought: 'Réflexion de {seconds} s', + thoughts: 'Réflexions', statusReading: "Lecture de l'état de l'agent…", statusFailed: "compass.http n'a pas répondu avec l'état de l'agent : {reason}", statusUnreadable: diff --git a/projects/compass.web/packages/pages/src/i18n/pt.ts b/projects/compass.web/packages/pages/src/i18n/pt.ts index e29fd912..e35a5f55 100644 --- a/projects/compass.web/packages/pages/src/i18n/pt.ts +++ b/projects/compass.web/packages/pages/src/i18n/pt.ts @@ -465,8 +465,10 @@ const pt: Catalogue = { ask: 'Perguntar', close: 'Fechar o agente do compass', sessions: { + title: 'Conversas', label: 'Conversa', none: 'Nenhuma conversa', + empty: 'Ainda não há conversas.', create: 'Nova conversa', untitled: 'Conversa sem título', delete: 'Eliminar conversa', @@ -475,6 +477,27 @@ const pt: Catalogue = { 'Esta conversa não está disponível para si nesta vista. Escolha outra ou comece uma nova.', failed: 'O compass.http não respondeu sobre a conversa: {reason}', }, + context: { + title: 'Contexto', + window: 'janela de {tokens} tokens', + none: 'A primeira resposta mostra o que utiliza.', + last: 'A última resposta usou {used} tokens; {left} restantes.', + lastDetail: '{prompt} de prompt e {generated} gerados, incluindo o raciocínio.', + history: { + one: 'O histórico guardou {count} turno, {used} de {budget} bytes.', + other: 'O histórico guardou {count} turnos, {used} de {budget} bytes.', + }, + dropped: { + one: '{count} turno anterior não foi enviado; a janela guarda os oito mais recentes dentro do orçamento de bytes.', + other: '{count} turnos anteriores não foram enviados; a janela guarda os oito mais recentes dentro do orçamento de bytes.', + }, + measure: + 'As contagens são as do llama-server para a última resposta, face à janela do modelo. A janela de histórico é a compactação: os turnos mais antigos são descartados, não resumidos.', + }, + thinkingStatus: 'A pensar · {seconds} s', + thinking: 'A pensar…', + thought: 'Pensou durante {seconds} s', + thoughts: 'Raciocínio', statusReading: 'A ler o estado do agente…', statusFailed: 'O compass.http não respondeu com o estado do agente: {reason}', statusUnreadable: diff --git a/projects/compass.web/packages/web/e2e/agent.spec.ts b/projects/compass.web/packages/web/e2e/agent.spec.ts index 03e5c263..817917e1 100644 --- a/projects/compass.web/packages/web/e2e/agent.spec.ts +++ b/projects/compass.web/packages/web/e2e/agent.spec.ts @@ -44,6 +44,32 @@ test('the Agent screen names the model and says llama-server is ready', async ({ await expect(panel.getByTestId('agent-health-detail')).toHaveCount(0); }); +test('the sessions panel makes, switches and deletes conversations', async ({ page }) => { + const environment = await environmentOf(page); + await page.goto(`/${environment}/agent`); + const panel = page.getByTestId('agent-sessions'); + await expect(panel.getByTestId('agent-sessions-empty')).toBeVisible(); + + await panel.getByTestId('agent-session-new').click(); + await expect(page).toHaveURL(new RegExp(`/${environment}/agent\\?session=\\d+$`)); + const rows = panel.getByTestId('agent-session'); + await expect(rows).toHaveCount(1); + await expect(rows.first()).toHaveAttribute('data-selected', ''); + + await panel.getByTestId('agent-session-new').click(); + await expect(rows).toHaveCount(2); + await expect(rows.first()).toHaveAttribute('data-selected', ''); + + await rows.last().click(); + await expect(rows.last()).toHaveAttribute('data-selected', ''); + await expect(rows.first()).not.toHaveAttribute('data-selected'); + + page.on('dialog', (dialog) => void dialog.accept()); + await panel.getByTestId('agent-session-delete').click(); + await expect(page).toHaveURL(`/${environment}/agent`); + await expect(rows).toHaveCount(1); +}); + test('an answer streams with its citations, and a citation opens the document at its heading', async ({ page, request, @@ -60,6 +86,21 @@ test('an answer streams with its citations, and a citation opens the document at await expect(turn.getByTestId('agent-status')).toContainText('Answered in'); await expect(page).toHaveURL(new RegExp(`/${environment}/agent\\?session=\\d+$`)); + const thinking = turn.getByTestId('agent-thinking'); + await expect(thinking).toBeVisible(); + await expect(thinking.locator('summary')).toContainText(/Thought for .* s/); + await expect(thinking).not.toHaveAttribute('open'); + await thinking.locator('summary').click(); + await expect(thinking.getByTestId('agent-thought')).toContainText( + 'I look for the lighthouse keeper.', + ); + + const context = page.getByTestId('agent-context'); + await expect(context.getByTestId('agent-context-window')).toContainText('token window'); + await expect(context.getByTestId('agent-context-last')).toContainText('Last answer used'); + await expect(context.getByTestId('agent-context-detail')).toContainText('reasoning included'); + await expect(context.getByTestId('agent-context-history')).toContainText('History kept'); + const asked = await (await request.get(`${STUB}/__last`)).json(); expect(JSON.stringify(asked)).toContain("the lighthouse keeper's log records the weather"); @@ -124,6 +165,9 @@ test('a reload restores the conversation, and deleting it removes it', async ({ ); await expect(restored.getByTestId('agent-source')).toHaveCount(1); await expect(restored.getByTestId('agent-times')).toContainText('first token after'); + await expect(restored.getByTestId('agent-thinking').locator('summary')).toContainText( + /Thought for .* s/, + ); page.on('dialog', (dialog) => void dialog.accept()); await page.getByRole('button', { name: 'Delete conversation' }).click(); diff --git a/projects/compass.web/packages/web/e2e/llama_stub.mjs b/projects/compass.web/packages/web/e2e/llama_stub.mjs index fddd9495..4877ed0e 100644 --- a/projects/compass.web/packages/web/e2e/llama_stub.mjs +++ b/projects/compass.web/packages/web/e2e/llama_stub.mjs @@ -29,6 +29,7 @@ const CITING = [ ' the oil burnt and the hours the lamp was lit [1].', ' It also keeps the tides [7].', ]; +const THINKING = ['I look for', ' the lighthouse keeper.']; const NO_MATCH = [ 'No compass document matched', ' the question, so I cannot answer it', @@ -85,11 +86,22 @@ async function complete(request, response) { }); const send = (chunk) => response.write(`data: ${JSON.stringify(chunk)}\n\n`); await wait(firstTokenMs); + for (const piece of THINKING) { + send({ + choices: [{ index: 0, delta: { reasoning_content: piece }, finish_reason: null }], + }); + await wait(betweenMs); + } for (const piece of pieces) { send({ choices: [{ index: 0, delta: { content: piece }, finish_reason: null }] }); await wait(betweenMs); } send({ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], timings }); + send({ + choices: [], + usage: { prompt_tokens: 668, completion_tokens: 12, total_tokens: 680 }, + timings, + }); response.end('data: [DONE]\n\n'); } From 9cf9f3d68a2186918d3391ce0e7731d9314e26fe Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 13:33:51 +0000 Subject: [PATCH 18/24] [agile] Record the sessions panel, the thinking and the compaction decision The task now carries the panel and thinking acceptance, the 4,096-token cap, the context indicator's exact measures, the very basic compaction the product owner asked for, and the model-written summary designed and deferred. The measurements hold the final test counts and the real Chromium pass against Qwen3.5-9B. Co-Authored-By: Claude Code --- .../build_the_compass_web_front_end/story.org | 7 +- ..._store_and_restore_agent_conversations.org | 152 +++++++++++++++--- 2 files changed, 135 insertions(+), 24 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org index 6aba7d6f..1a2d05c3 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org @@ -69,7 +69,10 @@ its own documentation screens in its favour. (orphans, dead ends, broken links). - *Agent.* A compass agent panel beside any page, answering from the documents with a local model on llama.cpp, streaming its answer and citing - documents that open in compass.web. + documents that open in compass.web. Its conversations are server-owned and + reachable from a sessions panel, its thinking is shown collapsed, and the + panel says what the last answer used of the model's context and what the + history window left out. - *Environments.* Every page names the environment it shows, and the picker lists every environment the service holds. - *HTTP in C++ only.* Every endpoint compass.web calls is compass.http, @@ -111,7 +114,7 @@ its own documentation screens in its favour. | [[id:D6F014EB-CB9F-44D6-B14A-9544B2691943][Serve compass behind ORE Studio's gateway]] | DONE | 2026-12-01 | 2026-12-01 | Run compass.http behind ores.http as its gateway and compass.web inside ores.web on ores.web's session, while compass on its own keeps running with no sign-in, and hand ORE Studio the forwarder and view mapping its side needs. | | [[id:44146C3F-FE10-4832-9311-7C2A87D17CDC][Open compass.web from ores.web]] | DONE | 2026-12-01 | 2026-12-01 | Make compass.web reachable from ores.web: first an external menu entry, then compass.web's pages as a package ores.web adds as a dependency and mounts, reading compass through ores.http, so ORE Studio can decommission its own documentation screens. | | [[id:131CF0B6-CF93-40A0-A6AC-4635F4A3CE8A][Publish the developer link]] | STARTED | 2026-12-01 | | Run compass.web for the team at a stable address, link it from compass's developer pages, and ship its built files with compass's releases. | -| [[id:CE6EDA24-65B9-4D57-96F8-640DDE04324B][Store and restore the agent's conversations]] | STARTED | 2026-12-02 | | Make the agent's conversations server-owned: two retained tables in a new =agent= schema, a session ask that writes the question before it streams and settles the answer off the io thread, done-only history and follow-up retrieval in the prompt, and a browser that opens, restores and deletes a conversation by its id. | +| [[id:CE6EDA24-65B9-4D57-96F8-640DDE04324B][Store and restore the agent's conversations]] | STARTED | 2026-12-02 | | Make the agent's conversations server-owned: two retained tables in a new =agent= schema, a session ask that writes the question before it streams and settles the answer off the io thread, done-only history and follow-up retrieval in the prompt, a Gemini-style sessions panel, the model's thinking shown collapsed, a context indicator from llama-server's own token counts, and a browser that opens, restores and deletes a conversation by its id. | | [[id:DF412233-B923-4151-A9B7-D896688F7C83][Offer the compass agent as an MCP tool]] | BACKLOG | | | Explore offering the compass agent as an MCP tool that runs the same loop as the panel's stream and returns the whole answer with its citations at once, and settle the timeouts a CPU model needs and whether an MCP caller with a model of its own needs it. | | [[id:D7A2C472-466E-42AB-AF5D-3D21FC46BBC2][Suggest searches and offer an AI mode]] | STARTED | 2026-12-01 | | Keep the landing page's box centered and its address unchanged while the person types, list the closest documents in a debounced combo box, and add an AI mode that takes the typed query to the agent screen. | diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index bd39a8de..5eb2989b 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -2,7 +2,7 @@ :ID: CE6EDA24-65B9-4D57-96F8-640DDE04324B :END: #+title: Task: Store and restore the agent's conversations -#+description: Make the compass agent's conversations server-owned: two retained tables in a new agent schema, a session ask that writes the question before it streams and settles the answer off the io thread, history and follow-up retrieval in the prompt, and a browser that opens, restores and deletes a conversation by its id. +#+description: Make the compass agent's conversations server-owned: two retained tables in a new agent schema, a session ask that writes the question before it streams and settles the answer off the io thread, history and follow-up retrieval in the prompt, a Gemini-style sessions panel, the model's thinking streamed and shown collapsed, a context indicator from llama-server's own token counts, and a browser that opens, restores and deletes a conversation by its id. #+type: task #+level: s1 #+filetags: :build_the_compass_web_front_end:sprint_01:v0: @@ -23,7 +23,10 @@ This page documents a [[id:31C868B9-306E-4282-BA8C-07E647021B34][task]] in the [ A conversation with the compass agent belongs to the service, not to the browser tab. A reload, a second tab and a later visit open the same transcript, and the follow-up question is answered with the conversation -before it as context, so "and why?" means something. +before it as context, so "and why?" means something. The screen keeps the +conversations in a right-hand panel, shows the model's thinking collapsed +as modern agent UIs do, and says what the last answer used of the model's +context window and what the history window left out. The product direction is server-owned sessions: a conversation belongs to the caller's environment, subject and view, and restoring it requires the @@ -35,7 +38,7 @@ same triple. Sign-off by the product owner is pending. |--------------+----------------------------------------| | State | STARTED | | Parent story | [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] | -| Now | Built and verified in six units, in #262, awaiting review and the product owner's sign-off. Nothing is merged. | +| Now | Built and verified in eight units, in #262, awaiting review and the product owner's sign-off. The last two units are the sessions panel, the model's thinking and the context indicator. Nothing is merged. | | Waiting on | The product owner's sign-off, and the answer to the open product calls below. | | Next | Review the pull request; then the product owner's calls on retention and audit. | | Last touched | 2026-12-02 | @@ -64,6 +67,21 @@ same triple. Sign-off by the product owner is pending. the transcript from the stored events (answers, citations, sources and timings), starts and deletes conversations, and polls an unfinished turn that another tab or a lost stream left =streaming=, bounded at 15 minutes. +- The Agent screen draws the conversations as a right-hand panel, as + Gemini's sidebar: a new-conversation control at the top, the caller's + conversations with the open one highlighted, and a delete for it. At phone + width the panel stacks above the transcript; the host's side panel keeps + the compact conversation bar. +- Thinking is on: the chat body sets =enable_thinking=true=, llama-server's + =reasoning_content= delta is parsed as =agent_thought_event=, and the turn + stores the reasoning with its answer. The panel shows it in a collapsed + =Thinking= element, a one-line summary while it thinks and after it + settles, which opens to the whole reasoning. The completion cap is 4,096 + tokens, reasoning included. +- The context indicator shows the model's 65,536-token window, the last + answered turn's prompt and generated tokens as llama-server counted them, + the bytes of history the prompt kept of the 24,000-byte budget, and how + many older done turns the window left out. - The gateway tests prove the view and subject isolation and the gateway's CSRF rule over the ask; the shell test drives the real page in Chromium. @@ -103,6 +121,31 @@ decisions: person, so =list_agent_sessions= and =get_agent_session= name the subject; the binding check learns the two tools, and every SQL statement filters by the triple. +- *Thinking is a stream, not a second answer.* The request turns + =enable_thinking= on and compass parses llama-server's =reasoning_content= + delta (and a build's bare =reasoning=) into =agent_thought_event=. The + reasoning is stored with the turn so a restore shows what the person saw, + but it never enters the model's history: only questions and answers are + premises. The completion cap rises from 400 to 4,096 tokens, because the + old cap would be spent on the reasoning and truncate the answer. +- *The sessions panel is the right-hand sidebar.* New conversation, the + caller's conversations, the open one highlighted, and its delete; the + compact bar stays for the host's side panel, and the panel stacks above + the transcript below =lg=. The address still carries =?session=. +- *The context indicator measures, it does not estimate.* The =done= event + carries =context_tokens= (the setting), =history_budget= (the + context-reserve byte budget), =history_turns=, =history_bytes= and + =dropped_turns= (the session's done exchanges the window left out). The + panel pairs them with llama-server's own =prompt_tokens= and + =generated_tokens= for that turn, so a person sees what the last answer + used and what the window left behind. +- *Compaction is the history window, deliberately.* The newest eight done + exchanges within the context-reserve byte budget are the compaction: + older exchanges are dropped whole, never cut mid-exchange, and the + indicator names how many were dropped. A model-written session summary is + designed in the Compaction decision section below and deferred; + =--context-shift= is not used because it truncates server-side without + compass or the person seeing what was lost. * Delivery order @@ -126,8 +169,18 @@ verifiable commit per unit: the address; =turnsOf= rebuilding the =Turn[]= from the stored events; StrictMode-safe restore; the bounded unfinished-turn poll; i18n; unit and Playwright tests. -6. This commit: the gateway view/subject isolation and CSRF tests, and the - task and story documents. +6. =f970a5ae= [web] The gateway view/subject isolation and CSRF tests, and + the task and story documents, with the panel opening on the screen's + environment. +7. [http] Thinking on and its event: =enable_thinking=true=, the + =reasoning_content= delta parsed as =agent_thought_event=, the reasoning + stored with the turn, the 4,096-token cap, and the =done= event's context + fields; the models, the generated protocol, the migration DDL and the + tests that pin them. +8. [web] The sessions panel, the collapsed =Thinking= element and the context + indicator, with their i18n, unit tests and Playwright tests. +9. [agile] This document: the slice's decisions, the compaction decision, and + the final verification. Four fixes came from the final passes. =c468f4cf= updated the codegen context test that pinned the streamed route's old output; it now expects @@ -139,6 +192,42 @@ pinned the ten messages in the CI struct check and taught the binding check panel open on the screen's environment, so the session list is the right one before the first question. +* Compaction decision + +The product owner asked for the very basic compaction in this slice. The +history window is that compaction: the newest eight done exchanges, within +the context-reserve byte budget, dropping whole exchanges oldest first. No +model-written summary is built, and the context indicator names how many +older done turns the window left out. + +The model-written summary is designed and deferred for four reasons: + +- *A second inference call on the ask path.* On the handler's worker it + would hold the request for seconds; as a prelude to the stream it emits + nothing while the model writes; off the path it needs a second writer + or queue with its own lifecycle. +- *Session state and a race.* It needs =agent_session.summary= and + =summary_ord=, the highest done turn folded in, plus a monotonic update so + two tabs cannot move a summary backwards. +- *A failure policy.* A summary that fails must not fail the question; the + prompt would fall back to the window it has and the next ask would retry. +- *Prompt-cache cost.* The summary changes the system prefix whenever a + turn ages out, weakening the cache reuse the append-only prompt has today. + +The design to build when it is wanted: when a done exchange falls out of +the window and its ord is above =summary_ord=, summarise the stored summary +plus that exchange with a non-streaming completion (thinking off, about 512 +tokens) before building the answer's chat body, in the same stream so no +worker blocks. Write it through the turn sink as +=save_agent_session_summary= with =WHERE summary_ord < $new=, prepend it to +the system prompt as a labelled summary, and on failure continue with the +old summary. The indicator already shows dropped turns, so the loss is +visible until then. + +=--context-shift= was rejected: it truncates server-side, can cut a +half-written exchange, and neither compass nor the person can say what was +lost. The window drops whole exchanges and the indicator counts them. + * Measurements Measured on 2026-12-02, from a release build @@ -146,17 +235,20 @@ Measured on 2026-12-02, from a release build | What | Result | |------+--------| -| =compass.db.tests "[migrations]"= | 144 assertions in 5 cases, green: migration 7 builds the catalog =schema.sql= builds | -| =compass.db.tests "agent_*"= | 42 assertions in 6 cases, green: both new row codecs round-trip and their schemas | +| =compass.db.tests "[migrations]"= | 144 assertions in 5 cases, green: migration 7 builds the catalog =schema.sql= builds, with the =thought= column | +| =compass.db.tests "agent_*"= | 44 assertions in 6 cases, green: both row codecs round-trip and their schemas, the turn's =thought= included | +| =compass.db.tests= (full) | 1288 assertions in 174 cases, green | | =compass.model.tests "[masd]"= | 106 assertions in 15 cases, green: the streamed POST parses, the streamed PUT and the named response are refused | -| =compass.http.tests= | 385 cases, 9674 assertions, green: the session lifecycle, isolation, writer, prompt and sink, plus regenerated counts 21 read routes and 31 write/tool routes | -| =@compass/pages= vitest | 241 tests in 11 files, green; =@compass/web= 3 tests | -| =shell_test.sh= (real Chromium) | 40 Playwright tests, green, including session create, restore, history in the llama body, delete and an abandoned stream restored as stopped | +| =compass.http.tests= | 388 cases, 9804 assertions, green: thinking and its sink, the context fields, the session lifecycle, isolation, writer, prompt and sink, plus regenerated counts 21 read routes and 31 write/tool routes | +| =@compass/pages= vitest | 246 tests in 11 files, green; =@compass/web= 3 tests | +| =shell_test.sh= (real Chromium) | 41 Playwright tests, green, including the sessions panel, the thinking element, the context indicator, session create, restore, history in the llama body, delete and an abandoned stream restored as stopped | | =gateway_test.sh= | 49 Playwright tests, green: a team session is invisible to the knowledge view and another subject; the knowledge view's transcript names no sprint page; the ask needs the gateway's =X-Ores-Request= and matching =Origin=; delete is 204 twice for its owner and 404 for another | -| History budget | 65,536-token context, 400 max answer tokens and about 2,000 bytes of system and current user leave the 24,000-byte ceiling binding: 24,000 bytes of history | -| Startup command | =llama-server … --ctx-size 65536 …= | -| CI model checks | =service_model_struct_check.py= and =service_model_binding_check.py= pass: the ten new messages are pinned, =agent_turn_status= is known, and the two subject-scoped reads are named | -| Final-head rerun | =compass.db.tests= migrations 144 assertions in 5 cases and codecs 42 in 6; =compass.model.tests= 106 in 15; =compass.codegen.tests= 1957 in 185; =compass.cli.tests= 2754 in 266; =compass.http.tests= 9674 in 385; pages vitest 241; shell test 40; gateway test 49; both model scripts exit 0 | +| History budget | 65,536-token context, 4,096 max answer tokens (reasoning included) and about 2,000 bytes of system and current user leave the 24,000-byte ceiling binding: 24,000 bytes of history | +| Completion cap | 4,096 tokens per answer, reasoning included; the old 400 would be spent thinking and truncate the answer | +| Startup command | =llama-server --model … --ctx-size 65536 … --reasoning auto …= | +| Real model pass | Qwen3.5-9B at =127.0.0.1:8081=: a real Chromium session on a throwaway cluster answered "How do I run compass serve?" after a 43 s thought, with 668 prompt and 2,338 generated tokens (reasoning included), so 3,006 used of 65,536 and 62,530 left; the Thinking element was collapsed, opened to the whole reasoning, and the panel made, restored and deleted conversations at 390 px with no horizontal overflow | +| CI model checks | =service_model_struct_check.py= and =service_model_binding_check.py= pass: 105 messages are pinned, =agent_thought_event= included, =agent_turn_status= is known, and the two subject-scoped reads are named | +| Final-head rerun | =compass.db.tests= migrations 144 assertions in 5 cases and codecs 44 in 6; =compass.model.tests= 106 in 15; =compass.http.tests= 9804 in 388; pages vitest 246; shell test 41; gateway test 49; both model scripts exit 0. Earlier heads also ran =compass.codegen.tests= 1957 in 185 and =compass.cli.tests= 2754 in 266. | * Open product calls @@ -187,12 +279,25 @@ Recorded, not decided, pending the product owner: - The migration is unreleased, so the retained-table test skips the new tables until a release includes them; that release pins migration 7's hash - and adds both tables to =released_retained=. + and adds both tables to =released_retained=. The =thought= column was added + to migration 7 in this slice, before any release, so it is not migration 8. - Prompt-cache reuse is a benefit, not a guarantee: the stored question is bare (the passages are not stored), so reuse stops at the previous exchange. - The writer's queue is bounded at 64 and drops with a count and a log line that names the turn, never the text. +- llama-server is run with =--reasoning auto=; its stream names the + reasoning delta =reasoning_content=. compass also reads a bare + =reasoning= delta, which some builds use. The reasoning is display only: + the history prompt keeps questions and answers, never thoughts. +- The completion cap is 4,096 tokens, counting the reasoning and the answer + together. The history budget reserves the same 4,096 tokens when it + computes the byte ceiling, so the byte budget is unchanged at 24,000. +- The context indicator's prompt and generated counts come from + llama-server's usage chunk; the request asks for it with + =stream_options.include_usage=. The timings' =prompt_n= is only what the + request evaluated after a cache reuse, so it is the fallback, not the + prompt's length. * Related captures @@ -205,12 +310,15 @@ Recorded, not decided, pending the product owner: * Result -Built in six units and four verification fixes on +Built in eight units and four verification fixes on =feature/agent-sessions=, each verified before the next, and pushed in #262, -which is not merged. Migration 7 builds -the catalog =schema.sql= builds; the parser and router gates admit the -streamed writing POST and refuse the shapes they should; the session -isolation, lifecycle, writer and prompt tests pass; the web's unit, browser -and gateway tests pass. The product owner's sign-off and the open product -calls are outstanding. +which is not merged. Migration 7 builds the catalog =schema.sql= builds; the +parser and router gates admit the streamed writing POST and refuse the shapes +they should; the session isolation, lifecycle, writer and prompt tests pass; +thinking streams as its own event and restores with the turn; the context +indicator reports llama-server's own counts and the turns the history window +left out; the sessions panel makes, restores and deletes conversations in a +real Chromium; the web's unit, shell and gateway tests pass. The compaction +is the history window, with the model-written summary designed and deferred. +The product owner's sign-off and the open product calls are outstanding. From 6067a3780b32edb72c233ca962d3469cb4451c90 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 13:34:44 +0000 Subject: [PATCH 19/24] [agile] Name the ten units and their commits The delivery order now names the reasoning column, thinking, the panel and the documents by commit, and the status and result count the ten units. Co-Authored-By: Claude Code --- ..._store_and_restore_agent_conversations.org | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index 5eb2989b..9230bba9 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -38,7 +38,7 @@ same triple. Sign-off by the product owner is pending. |--------------+----------------------------------------| | State | STARTED | | Parent story | [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] | -| Now | Built and verified in eight units, in #262, awaiting review and the product owner's sign-off. The last two units are the sessions panel, the model's thinking and the context indicator. Nothing is merged. | +| Now | Built and verified in ten units, in #262, awaiting review and the product owner's sign-off. The last four units are the turn's reasoning column, thinking and its context fields, the sessions panel, and these documents. Nothing is merged. | | Waiting on | The product owner's sign-off, and the answer to the open product calls below. | | Next | Review the pull request; then the product owner's calls on retention and audit. | | Last touched | 2026-12-02 | @@ -172,15 +172,17 @@ verifiable commit per unit: 6. =f970a5ae= [web] The gateway view/subject isolation and CSRF tests, and the task and story documents, with the panel opening on the screen's environment. -7. [http] Thinking on and its event: =enable_thinking=true=, the +7. =7e874de2= [db] The turn's =thought= column: the entity model, the + generated row codec, the schema, and migration 7 with the column verbatim. +8. =da5eb477= [http] Thinking on and its event: =enable_thinking=true=, the =reasoning_content= delta parsed as =agent_thought_event=, the reasoning - stored with the turn, the 4,096-token cap, and the =done= event's context - fields; the models, the generated protocol, the migration DDL and the - tests that pin them. -8. [web] The sessions panel, the collapsed =Thinking= element and the context - indicator, with their i18n, unit tests and Playwright tests. -9. [agile] This document: the slice's decisions, the compaction decision, and - the final verification. + stored with the turn, the 4,096-token cap, the =stream_options= usage + request, and the =done= event's context fields; the models, the generated + protocol, and the tests that pin them. +9. =9b3a23fd= [web] The sessions panel, the collapsed =Thinking= element and + the context indicator, with their i18n, unit tests and Playwright tests. +10. =15427cb0= [agile] This document: the slice's decisions, the compaction + decision, and the final verification. Four fixes came from the final passes. =c468f4cf= updated the codegen context test that pinned the streamed route's old output; it now expects @@ -310,7 +312,7 @@ Recorded, not decided, pending the product owner: * Result -Built in eight units and four verification fixes on +Built in ten units and four verification fixes on =feature/agent-sessions=, each verified before the next, and pushed in #262, which is not merged. Migration 7 builds the catalog =schema.sql= builds; the parser and router gates admit the streamed writing POST and refuse the shapes From f4a080d3073460c8650f2c1cf967aec4eab46f71 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 15:42:19 +0000 Subject: [PATCH 20/24] [db] Keep the development conversation across the thought column A database that applied the earlier shape of migration 7, before the turn kept its thought, gains the column from migration 8 and keeps its conversations. The add is IF NOT EXISTS, so a fresh database, which builds the column in migration 7, changes nothing. The web reads an answer stored before the context fields as zeros, so it restores and shows no context meter for it. Co-Authored-By: Claude Code --- ..._store_and_restore_agent_conversations.org | 23 ++++++++++----- projects/compass.db/src/ops/migrations.cpp | 9 ++++++ .../packages/pages/src/client.test.ts | 28 +++++++++++++++++++ .../compass.web/packages/pages/src/client.ts | 12 ++++---- 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org index 9230bba9..14c1e9ed 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/task_store_and_restore_agent_conversations.org @@ -38,7 +38,7 @@ same triple. Sign-off by the product owner is pending. |--------------+----------------------------------------| | State | STARTED | | Parent story | [[id:D8019709-7EF9-43E0-AC64-85DB34A078BE][Build the compass web front end]] | -| Now | Built and verified in ten units, in #262, awaiting review and the product owner's sign-off. The last four units are the turn's reasoning column, thinking and its context fields, the sessions panel, and these documents. Nothing is merged. | +| Now | Built and verified in ten units, in #262, awaiting review and the product owner's sign-off. The last four units are the turn's reasoning column, thinking and its context fields, the sessions panel, and these documents. Migration 8 lets a development database that applied the earlier shape of migration 7 keep its conversation. Nothing is merged. | | Waiting on | The product owner's sign-off, and the answer to the open product calls below. | | Next | Review the pull request; then the product owner's calls on retention and audit. | | Last touched | 2026-12-02 | @@ -237,7 +237,7 @@ Measured on 2026-12-02, from a release build | What | Result | |------+--------| -| =compass.db.tests "[migrations]"= | 144 assertions in 5 cases, green: migration 7 builds the catalog =schema.sql= builds, with the =thought= column | +| =compass.db.tests "[migrations]"= | 144 assertions in 5 cases, green: migrations 7 and 8 build the catalog =schema.sql= builds; 8 adds the =thought= column only where the earlier shape of 7 ran | | =compass.db.tests "agent_*"= | 44 assertions in 6 cases, green: both row codecs round-trip and their schemas, the turn's =thought= included | | =compass.db.tests= (full) | 1288 assertions in 174 cases, green | | =compass.model.tests "[masd]"= | 106 assertions in 15 cases, green: the streamed POST parses, the streamed PUT and the named response are refused | @@ -279,10 +279,16 @@ Recorded, not decided, pending the product owner: * Notes -- The migration is unreleased, so the retained-table test skips the new - tables until a release includes them; that release pins migration 7's hash - and adds both tables to =released_retained=. The =thought= column was added - to migration 7 in this slice, before any release, so it is not migration 8. +- The migrations are unreleased, so the retained-table test skips the new + tables until a release includes them; that release pins migration 7's and + migration 8's hashes and adds both tables to =released_retained=. +- Migration 7 builds the =thought= column for a fresh database, and migration + 8 adds it only where an earlier shape of migration 7 was already applied, + as a development database was. =ADD COLUMN IF NOT EXISTS= makes it a no-op + on every fresh database, and the migrated catalog still equals =schema.sql='s. +- An answer stored before the context fields existed restores with zeros in + them and shows no context meter; the model gives each field a default of 0, + and the web schema reads a missing field the same way. - Prompt-cache reuse is a benefit, not a guarantee: the stored question is bare (the passages are not stored), so reuse stops at the previous exchange. @@ -314,7 +320,10 @@ Recorded, not decided, pending the product owner: Built in ten units and four verification fixes on =feature/agent-sessions=, each verified before the next, and pushed in #262, -which is not merged. Migration 7 builds the catalog =schema.sql= builds; the +which is not merged. Migrations 7 and 8 build the catalog =schema.sql= builds; +migration 8 moved the development database from 7 to 8 without losing its +conversation, which the sessions panel then restored in Chromium, its old +answer reading zero for the context fields and showing no thinking block; the parser and router gates admit the streamed writing POST and refuse the shapes they should; the session isolation, lifecycle, writer and prompt tests pass; thinking streams as its own event and restores with the turn; the context diff --git a/projects/compass.db/src/ops/migrations.cpp b/projects/compass.db/src/ops/migrations.cpp index 9ca5ee3b..60b3ddc5 100644 --- a/projects/compass.db/src/ops/migrations.cpp +++ b/projects/compass.db/src/ops/migrations.cpp @@ -363,6 +363,13 @@ CREATE TABLE agent.agent_turn ( CREATE INDEX agent_turn_streaming ON agent.agent_turn (session_id) WHERE status = 'streaming'; )sql"; +// A database that applied migration 7 before it kept the model's reasoning +// gains the column; a fresh one has it already, so this changes nothing +// there. The conversations already recorded stay as they are. +constexpr std::string_view agent_sessions_thought = R"sql( +ALTER TABLE agent.agent_turn ADD COLUMN IF NOT EXISTS thought text NOT NULL DEFAULT ''; +)sql"; + constexpr std::array all{ migration{1, "the corpus, test and activity schemas", create_schemas}, migration{2, "the document state and sprint for search", search_columns}, @@ -371,6 +378,8 @@ constexpr std::array all{ migration{5, "the clearing of a step's outcome", clear_step_result}, migration{6, "the layout of the link graph", link_graph_layout}, migration{7, "the agent's conversations and their turns", agent_sessions}, + migration{8, "the agent turn's thought, for a database that applied the " + "earlier shape of migration 7", agent_sessions_thought}, }; } diff --git a/projects/compass.web/packages/pages/src/client.test.ts b/projects/compass.web/packages/pages/src/client.test.ts index 0a561c17..41010719 100644 --- a/projects/compass.web/packages/pages/src/client.test.ts +++ b/projects/compass.web/packages/pages/src/client.test.ts @@ -413,6 +413,34 @@ describe("the agent's conversations", () => { expect(session.turns[1]?.done).toBeNull(); }); + it('restores an answer stored before answers carried the context', async () => { + const old = { + ...storedSession, + turns: [ + { + ...storedTurn, + done: { + cited: [1], + dropped: [], + first_token_ms: 10, + total_ms: 20, + prompt_tokens: 30, + generated_tokens: 4, + tokens_per_second: 5, + finish_reason: 'stop', + }, + }, + ], + }; + const client = createClient( + { httpBase: '/', onDenied: () => undefined }, + answering(200, old), + ); + const session = await client.getAgentSession('compass', 7); + expect(session.turns[0]?.done?.context_tokens).toBe(0); + expect(session.turns[0]?.done?.dropped_turns).toBe(0); + }); + it('asks in a conversation with a POST whose body holds the question', async () => { const asked: { url: string; init: RequestInit | undefined }[] = []; const client = createClient({ httpBase: '/', onDenied: () => undefined }, (input, init) => { diff --git a/projects/compass.web/packages/pages/src/client.ts b/projects/compass.web/packages/pages/src/client.ts index 75b67d30..4d6eb039 100644 --- a/projects/compass.web/packages/pages/src/client.ts +++ b/projects/compass.web/packages/pages/src/client.ts @@ -371,11 +371,13 @@ export const doneEventSchema = z.object({ generated_tokens: count, tokens_per_second: z.number().nonnegative(), finish_reason: z.string(), - context_tokens: count, - history_budget: count, - history_turns: count, - history_bytes: count, - dropped_turns: count, + // A turn stored before compass measured the context has no context + // fields; they read as zero and the panel shows no meter for it. + context_tokens: count.default(0), + history_budget: count.default(0), + history_turns: count.default(0), + history_bytes: count.default(0), + dropped_turns: count.default(0), }); export const failureEventSchema = z.object({ From 6dee1a0e08620c6837b63ae69646ae8a1f39cfa3 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 17:31:45 +0000 Subject: [PATCH 21/24] [web] Preview each document's first lines in the list document_summary carries an excerpt: the first non-empty section of the document's body, clipped to 320 characters with id-link markup reduced to its label. The documents screen draws it under the title, clamped to two lines, so a page of the list says what each document is about without opening it. The generated protocol carries the field; the document and backlink reads follow the shifted column. Co-Authored-By: Claude Code --- .../messages/document_queries_protocol.hpp | 2 ++ .../compass.http.document_queries.org | 8 +++++++ projects/compass.http/src/query/reads.cpp | 24 +++++++++++-------- .../packages/pages/src/DocumentScreen.tsx | 1 + .../packages/pages/src/DocumentsScreen.tsx | 3 +++ .../compass.web/packages/pages/src/client.ts | 1 + .../packages/pages/src/document.test.tsx | 2 ++ .../packages/pages/src/sprint.test.tsx | 1 + 8 files changed, 32 insertions(+), 10 deletions(-) diff --git a/projects/compass.http/include/compass.http/messages/document_queries_protocol.hpp b/projects/compass.http/include/compass.http/messages/document_queries_protocol.hpp index aaa234fb..4cf9f34b 100644 --- a/projects/compass.http/include/compass.http/messages/document_queries_protocol.hpp +++ b/projects/compass.http/include/compass.http/messages/document_queries_protocol.hpp @@ -330,6 +330,7 @@ struct document_summary { std::string path; std::vector tags; std::string updated; + std::string excerpt; friend bool operator==(const document_summary&, const document_summary&) = default; }; @@ -347,6 +348,7 @@ struct document_summary { ::compass::db::codec::field{"path", &document_summary::path}, ::compass::db::codec::field{"tags", &document_summary::tags, true}, ::compass::db::codec::field{"updated", &document_summary::updated}, + ::compass::db::codec::field{"excerpt", &document_summary::excerpt}, }; } diff --git a/projects/compass.http/modeling/compass.http.document_queries.org b/projects/compass.http/modeling/compass.http.document_queries.org index 9f7133ff..7240b7ed 100644 --- a/projects/compass.http/modeling/compass.http.document_queries.org +++ b/projects/compass.http/modeling/compass.http.document_queries.org @@ -484,6 +484,14 @@ The document's path in the environment. The document's =#+updated:=. +*** excerpt +:PROPERTIES: +:cpp_type: std::string +:END: + +The first lines of the document's body, clipped for a list. Empty when the +document has no body text. + ** list_documents_request :PROPERTIES: :tool: list_documents diff --git a/projects/compass.http/src/query/reads.cpp b/projects/compass.http/src/query/reads.cpp index c3f90e95..c8e3b8ef 100644 --- a/projects/compass.http/src/query/reads.cpp +++ b/projects/compass.http/src/query/reads.cpp @@ -48,7 +48,10 @@ using db::query::statement; constexpr std::string_view summary_columns = "coalesce(d.org_id, ''), coalesce(d.title, ''), coalesce(d.type, ''), " "coalesce(d.description, ''), p.path, array_to_string(d.tags, E'\\x1f'), " - "coalesce(d.updated, '')"; + "coalesce(d.updated, ''), " + "coalesce(left(btrim(regexp_replace((SELECT s.text FROM corpus.section s " + "WHERE s.hash = d.hash AND s.text <> '' ORDER BY s.ord LIMIT 1), " + "'\\[\\[[^]]*\\]\\[([^]]*)\\]\\]', '\\1', 'g')), 320), '')"; std::vector split_units(std::string_view joined) { std::vector out; @@ -73,6 +76,7 @@ messages::document_summary summary_at(const result& r, std::size_t row, std::siz s.path = r.value(row, first + 4); s.tags = split_units(r.value(row, first + 5)); s.updated = r.value(row, first + 6); + s.excerpt = r.value(row, first + 7); return s; } @@ -467,8 +471,8 @@ std::optional read_document(db::io::connection& c, return std::nullopt; document_source out; out.summary = summary_at(found, 0, 0); - out.source = found.value(0, 7); - out.hash = found.value(0, 8); + out.source = found.value(0, 8); + out.hash = found.value(0, 9); out.synced_at = e.synced_at; out.environment_id = e.id; @@ -611,7 +615,7 @@ std::optional backlinks(db::io::connection& c, statement holders; std::unordered_set hashes; for (std::size_t row = 0; row < rows.rows(); ++row) - hashes.emplace(rows.value(row, 9)); + hashes.emplace(rows.value(row, 10)); std::string in; for (const auto& hash : hashes) in += (in.empty() ? "decode(" : ", decode(") + holders.bind(hash) + ", 'hex')"; @@ -639,22 +643,22 @@ std::optional backlinks(db::io::connection& c, for (std::size_t row = 0; row < rows.rows(); ++row) { messages::backlink b; b.document = summary_at(rows, row, 0); - b.anchor = rows.value(row, 7); - b.text = rows.value(row, 8); - const std::string hash(rows.value(row, 9)); + b.anchor = rows.value(row, 8); + b.text = rows.value(row, 9); + const std::string hash(rows.value(row, 10)); if (hash != parsed) { parsed = hash; source = sources[hash]; tables = {}; compass::ingest::org::parse(source, tables); } - const auto heading = to_number(rows.value(row, 11)); + const auto heading = to_number(rows.value(row, 12)); if (heading >= 0) b.headings = heading_path(outlines[hash], static_cast(heading)); const auto t = ot::view(tables); - const auto ord = to_number(rows.value(row, 10)); + const auto ord = to_number(rows.value(row, 11)); if (ord < t.links.size() && - t.links.paths[ot::link_id{ord}].of(source) == rows.value(row, 12)) + t.links.paths[ot::link_id{ord}].of(source) == rows.value(row, 13)) b.excerpt = excerpt_of(source, t, link_range(t, ot::link_id{ord})); out.backlinks.push_back(std::move(b)); } diff --git a/projects/compass.web/packages/pages/src/DocumentScreen.tsx b/projects/compass.web/packages/pages/src/DocumentScreen.tsx index 71bb25d2..578be282 100644 --- a/projects/compass.web/packages/pages/src/DocumentScreen.tsx +++ b/projects/compass.web/packages/pages/src/DocumentScreen.tsx @@ -715,6 +715,7 @@ export function OrgFragment({ path: '', tags: [], updated: '', + excerpt: '', }, body: org, anchors: [], diff --git a/projects/compass.web/packages/pages/src/DocumentsScreen.tsx b/projects/compass.web/packages/pages/src/DocumentsScreen.tsx index 35bbd80e..f6bdd8d1 100644 --- a/projects/compass.web/packages/pages/src/DocumentsScreen.tsx +++ b/projects/compass.web/packages/pages/src/DocumentsScreen.tsx @@ -135,6 +135,9 @@ export function DocumentsScreen({ environment }: { readonly environment: string {d.title === '' ? d.path : d.title} )} + {d.excerpt === '' ? null : ( +

    {d.excerpt}

    + )} ))} diff --git a/projects/compass.web/packages/pages/src/client.ts b/projects/compass.web/packages/pages/src/client.ts index 4d6eb039..ec8b75c2 100644 --- a/projects/compass.web/packages/pages/src/client.ts +++ b/projects/compass.web/packages/pages/src/client.ts @@ -93,6 +93,7 @@ export const documentSummarySchema = z.object({ path: z.string(), tags: z.array(z.string()), updated: z.string(), + excerpt: z.string(), }); /** The document a link opens, as compass.http resolved it under the caller's view. */ diff --git a/projects/compass.web/packages/pages/src/document.test.tsx b/projects/compass.web/packages/pages/src/document.test.tsx index a9150ebe..3c330a0a 100644 --- a/projects/compass.web/packages/pages/src/document.test.tsx +++ b/projects/compass.web/packages/pages/src/document.test.tsx @@ -54,6 +54,7 @@ const story: DocumentResponse = { path: 'doc/agile/story_keep_the_light.org', tags: ['lamp'], updated: '2026-11-30', + excerpt: 'The lamp is lit at dusk, and the keeper writes it down.', }, body: [ ':PROPERTIES:', @@ -322,6 +323,7 @@ describe('the documents screen', () => { ); expect(html).toContain('52 documents, by path'); expect(html).toMatch(/href="\/compass\/docs\/STORY-1"[^>]*>Story: Keep the light<\/a>/); + expect(html).toContain('The lamp is lit at dusk, and the keeper writes it down.'); expect(html).not.toMatch(/href="[^"]*no_id/); expect(html).toContain('Page 2 of 2'); }); diff --git a/projects/compass.web/packages/pages/src/sprint.test.tsx b/projects/compass.web/packages/pages/src/sprint.test.tsx index 838fab6f..49464f3c 100644 --- a/projects/compass.web/packages/pages/src/sprint.test.tsx +++ b/projects/compass.web/packages/pages/src/sprint.test.tsx @@ -186,6 +186,7 @@ function page(id: string, type: string, title: string): DocumentResponse { type, description: '', path: `doc/${id}.org`, + excerpt: '', tags: [], updated: '2026-11-30', }, From c29b49a196f7dfc372966d1dc9b34a67bb58e84e Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 22:58:11 +0000 Subject: [PATCH 22/24] [docs] Describe what compass.web can do A knowledge page states the six screens and what each offers: search with facets and snippets, the documents list with each document's first lines, the sprint board, charts and views, the step-by-step test runner, the WebGL link graph, and the agent with its server-owned conversations, collapsed thinking and context indicator. It also covers environments, the view isolation behind the gateway, and how compass serve delivers the app. The entry page links it. Co-Authored-By: Claude Code --- doc/compass.org | 1 + .../compass/compass_web_features.org | 117 ++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 doc/knowledge/compass/compass_web_features.org diff --git a/doc/compass.org b/doc/compass.org index 6acf36d4..38a87127 100644 --- a/doc/compass.org +++ b/doc/compass.org @@ -38,6 +38,7 @@ projects/ 2. [[id:8A9A460F-8024-4890-B091-C0D02FD84218][System model]] --- layers and components. 3. [[id:8A0E6F32-C4BC-4667-88E8-7F80CA25437C][Component architecture]] --- layout rules. 4. [[id:2ABEC8F1-4A0B-4E79-8BFC-D1AF9B340A23][Version 0]] --- what we are working on now. +5. [[id:DC058C8E-79D4-4AA4-A131-CA5AA435EFB4][Compass web features]] --- what compass.web can do. * Upstream ORE Studio lives at =~/Development/OreStudio=. Its =doc/compass.org=, diff --git a/doc/knowledge/compass/compass_web_features.org b/doc/knowledge/compass/compass_web_features.org new file mode 100644 index 00000000..a489807f --- /dev/null +++ b/doc/knowledge/compass/compass_web_features.org @@ -0,0 +1,117 @@ +:PROPERTIES: +:ID: DC058C8E-79D4-4AA4-A131-CA5AA435EFB4 +:END: +#+title: Compass web features +#+description: What compass.web can do: search, documents, the sprint and its testing, the graph, and the agent, per environment. +#+type: knowledge +#+level: cross +#+filetags: :compass:web:features:knowledge: +#+created: 2026-12-02 +#+updated: 2026-12-02 + +compass.web is the browser front end of [[id:B69989F6-19E1-430D-AC6D-B2416E4C433F][compass]]. For one synced +environment of the repository it searches the documents, reads them, shows +the sprint and its testing, draws the document link graph, and answers +questions with a local model. It reads only compass.http, compass's C++ +server, and =compass serve= serves it on its own or inside ORE Studio's web +through the gateway. Every page names the environment it shows: one window +onto one environment, with no page mixing two. + +* Detail + +** Search + +Search runs as you type over the environment's documents and their sections. +Each result names the kind of page it is — knowledge, or the history of the +work — with the document's title and path and a snippet holding the matched +terms. Facets narrow the results by type, tags, state, sprint, level and +audience. Opening a result opens the document at the heading that matched. + +** Documents + +The Documents screen lists every document of the environment by path, a page +at a time, filtered by type. Each entry shows its type, path and title, and +the first lines of its body, so a page of the list can be skimmed without +opening anything. The title opens the document by its =:ID:=. + +The document view renders the org in the browser; the server never sends +HTML. Headings carry stable anchors, and an =id:= link opens the linked +document at the anchored heading. A link the caller's view does not hold is +marked unresolved rather than followed. The view also lists the document's +images, the documents it links to, and the documents that link to it, each +backlink with the heading path the link sits under. Documents are read-only. + +** The sprint + +The Sprint screen draws the environment's present or an earlier sprint as a +kanban board: its stories and their tasks by state, with each story's task +counts, scenarios and open notes. It also opens the backlog and the story and +task views, where a work item's state, branch, pull request, blocked-on +reason and test scenarios are shown. + +The sprint charts show velocity, as stories done in each sprint of the +environment; a burn-up of tasks done on each day against the sprint's scope; +tasks done per day, with days after today outlined; and every task of the +sprint by state. Where the story tables and the task pages disagree on a +task, the charts name the disagreement and leave the task out rather than +invent a value. + +** Testing + +The Testing screen lists what the sprint needs tested: its scenarios, the +task each verifies, and the last run. A scenario runs step by step in the +browser, and the runner records each step's outcome and notes and takes +screenshots pasted or dropped into the page, all through compass.http. The +recorded campaigns are exported back into their stories' folders with +=compass test export=. + +** The graph + +The Graph screen draws the environment's =:ID:= links in WebGL. Documents are +coloured by type and sized by inbound links, or uniformly; search highlights +the matches; clicking a document centres a local graph of one or more hops +around it. Overlays mark the orphans, the dead ends, and the documents with +an =id:= link that no document of the environment holds. + +** The agent + +The Agent screen asks questions about the environment's documents and +answers them with a local llama.cpp model, streamed as it writes. The answer +cites the passages it used with numbered references that open the document at +the cited heading; the passages it searched for and handed the model are +listed under the answer, with the query. When the passages do not answer the +question, the agent says so rather than answer from its own knowledge. + +The agent's conversations are server-owned. A conversation belongs to the +caller's environment, subject and view; the sessions panel creates, lists, +restores and deletes them, and a reload brings back the transcript. A +restored turn brings back its passages, answer, citations, timings and +thinking. + +While the model thinks, the panel says so; once the answer starts, the +reasoning folds into a collapsed =Thought for N s= element that opens to the +whole thought. The context indicator reports the last answer's prompt and +generated tokens, reasoning included, against the model's context window, the +bytes of earlier exchanges the prompt kept of its budget, and how many older +done turns the history window left out. The history is the compaction: the +newest eight done exchanges within a byte budget, dropped whole and oldest +first, so what the model no longer sees is counted rather than hidden. + +** Environments and views + +Every address names an environment, and the picker lists every environment +the service holds, with the time of its last sync and its document count. All +six screens read only that environment. The server filters every read by the +caller's environment, subject and view: run alone, compass has no sign-in and +local callers use the team view; behind ORE Studio's gateway, the caller's +session supplies the subject and view, and a knowledge view sees only what +its definition admits. + +** Running it + +=compass serve= serves compass.web at the root, beside compass's HTTP, MCP +and OpenAPI routes. The same build can be mounted in ORE Studio's web as a +package on the host's session. The interface speaks English, Portuguese and +French, follows the browser's preferred language, and has light and dark +themes. The address of a developer's instance is in the +[[id:5B271351-399A-4BD7-A096-E5DF1EDAD8F5][Developer Guide]]. From 8a4091478a5cdf2742407c39a4b62181c0de1653 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 23:56:05 +0000 Subject: [PATCH 23/24] [web] Ask AI mode's question in a conversation, not statelessly Merging the search suggestions beside the sessions leaves the Agent screen with two ways in: the address's ?q= and its ?session=. The question now opens a conversation and asks in it, so a reload keeps it, and the tests say so. The panel keeps the question effect and the sessions panel's address, and the initial question is asked once. Co-Authored-By: Claude Code --- .../packages/pages/src/agent.test.tsx | 51 +++++++++++++++---- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/projects/compass.web/packages/pages/src/agent.test.tsx b/projects/compass.web/packages/pages/src/agent.test.tsx index 60e71684..d5376056 100644 --- a/projects/compass.web/packages/pages/src/agent.test.tsx +++ b/projects/compass.web/packages/pages/src/agent.test.tsx @@ -531,14 +531,44 @@ describe('the agent initial question', () => { `event: token\ndata: ${JSON.stringify({ text: 'The keeper' })}\n\n` + `event: done\ndata: ${JSON.stringify({ ...done, cited: [], dropped: [] })}\n\n`; - const fakeFetch: typeof fetch = (input) => { + const asks: { readonly url: string; readonly body: string }[] = []; + + // The panel opens a conversation and asks the question in it, so AI mode's + // question is stored like any other. The status route answers ready; the + // sessions routes list nothing and make one; the ask streams one token + // and a done event, so the panel settles. + const fakeFetch: typeof fetch = (input, init) => { const url = String(input); if (url.endsWith('/agent')) { return Promise.resolve(new Response(JSON.stringify(status))); } - asked.push(url); + if (url.includes('/agent/sessions?')) { + asked.push(url); + return Promise.resolve(new Response(JSON.stringify({ sessions: [] }))); + } + if (url.endsWith('/agent/sessions')) { + asked.push(url); + return Promise.resolve( + new Response(JSON.stringify({ session: 1, created_at: '2026-12-02T10:00:00Z' })), + ); + } + if (url.endsWith('/ask')) { + asks.push({ url, body: String(init?.body ?? '') }); + return Promise.resolve( + new Response(answerWire, { headers: { 'Content-Type': 'text/event-stream' } }), + ); + } return Promise.resolve( - new Response(answerWire, { headers: { 'Content-Type': 'text/event-stream' } }), + new Response( + JSON.stringify({ + session: 1, + environment: 'compass', + title: '', + created_at: '2026-12-02T10:00:00Z', + updated_at: '2026-12-02T10:00:00Z', + turns: [], + }), + ), ); }; @@ -592,27 +622,31 @@ describe('the agent initial question', () => { afterEach(() => { asked.length = 0; + asks.length = 0; vi.unstubAllGlobals(); }); - it('asks the question the address names, and asks it once', async () => { + it('asks the question the address names, once, in a conversation it opens', async () => { vi.stubGlobal('fetch', fakeFetch); const mounted = await mount('/?q=What+does+the+log+say%3F'); - expect(asked).toEqual(['/v1/compass/agent?q=What+does+the+log+say%3F']); + expect(asked).toContain('/v1/compass/agent/sessions'); + expect(asks.map((a) => a.url)).toEqual(['/v1/compass/agent/sessions/1/ask']); + expect(JSON.parse(asks[0]?.body ?? '{}')).toEqual({ q: 'What does the log say?' }); expect(mounted.container.textContent).toContain('What does the log say?'); expect(mounted.container.textContent).toContain('The keeper'); await act(async () => { await mounted.router.navigate('/?q=Another+question'); }); - expect(asked).toHaveLength(1); + expect(asks).toHaveLength(1); await unmount(mounted); }); it('asks nothing when the address names no question', async () => { vi.stubGlobal('fetch', fakeFetch); const mounted = await mount('/agent'); - expect(asked).toEqual([]); + expect(asks).toEqual([]); + expect(asked).not.toContain('/v1/compass/agent/sessions'); expect(mounted.container.textContent).toContain(enFlat['agent.home']); await unmount(mounted); }); @@ -620,8 +654,7 @@ describe('the agent initial question', () => { it('cuts the question to the 500 characters compass.http takes', async () => { vi.stubGlobal('fetch', fakeFetch); const mounted = await mount(`/?q=${'a'.repeat(501)}`); - const question = new URL(asked[0] ?? '', 'http://test').searchParams.get('q'); - expect(question).toBe('a'.repeat(500)); + expect(JSON.parse(asks[0]?.body ?? '{}')).toEqual({ q: 'a'.repeat(500) }); await unmount(mounted); }); }); From b2f078cc0f8c3e066e84fa84638bf5d5943cbaa4 Mon Sep 17 00:00:00 2001 From: Marco Craveiro Date: Wed, 2 Dec 2026 23:57:15 +0000 Subject: [PATCH 24/24] [agile] State the sessions work once and mark search merged The rebase that put this branch on the merged search suggestions kept one sentence per stacked commit, so the status row said the same thing three times. It says it once now, and search reads as merged. Co-Authored-By: Claude Code --- .../v0/sprint_01/build_the_compass_web_front_end/story.org | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org index 1a2d05c3..03bd0830 100644 --- a/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org +++ b/doc/agile/versions/v0/sprint_01/build_the_compass_web_front_end/story.org @@ -39,9 +39,9 @@ its own documentation screens in its favour. |---------------+----------------------------------------| | State | STARTED | | Parent sprint | [[id:850C1BC8-FE02-4EE0-A5D6-6085DC34CE27][Sprint 1]] | -| Now | Captured with its tasks. Rename, the OpenAPI document and the inventory are done. Prototype the shell and the document view (#234), Prototype the link graph in WebGL (#236), Prototype the agent panel on llama.cpp (#237) and Prototype the sprint and testing views (#239) are signed off. Stand up compass.web on the ores.web stack (#241) is signed off: compass serve serves compass.web. Search the documents in the browser (#242) is signed off with decision 10's ranking. Read a document in the browser (#243) is signed off and merged. Retire the HTML document route (#244) is signed off and merged. Show the sprint board, its stories and its tasks (#246) is signed off and merged. Draw the sprint charts (#247) is signed off and merged. Run test scenarios with screenshots in the browser (#248) is signed off and merged. Draw the link graph in WebGL (#249) is signed off and merged. Talk to the compass agent in the browser (#252) is signed off and merged. Serve compass behind ORE Studio's gateway (#254) is signed off and merged. Open compass.web from ores.web (#256) is signed off and merged. Publish the developer link (#257) merged the packaging and install work; the team address remains the product owner's. Suggest searches and offer an AI mode (#259) is STARTED: the landing page keeps its box centered while typing, lists the closest documents in a combo box, and hands the typed query to the agent from AI mode. The agent's retrieval dropped compass itself; the fix is in review. The agent's model server runs as a tracked systemd user unit on the GPU with Qwen3.5-9B; verified, waiting on the product owner's sign-off. Store and restore the agent's conversations is STARTED: built and verified in six units on =feature/agent-sessions=, in a pull request awaiting review and the product owner's sign-off. | -| Waiting on | The product owner's team address for compass.web, and the sign-off of the agent's server-owned conversations. | -| Next | Review #262 and sign it off; publish the developer link once the address is decided. | +| Now | Captured with its tasks. Rename, the OpenAPI document and the inventory are done. Prototype the shell and the document view (#234), Prototype the link graph in WebGL (#236), Prototype the agent panel on llama.cpp (#237) and Prototype the sprint and testing views (#239) are signed off. Stand up compass.web on the ores.web stack (#241) is signed off: compass serve serves compass.web. Search the documents in the browser (#242) is signed off with decision 10's ranking. Read a document in the browser (#243) is signed off and merged. Retire the HTML document route (#244) is signed off and merged. Show the sprint board, its stories and its tasks (#246) is signed off and merged. Draw the sprint charts (#247) is signed off and merged. Run test scenarios with screenshots in the browser (#248) is signed off and merged. Draw the link graph in WebGL (#249) is signed off and merged. Talk to the compass agent in the browser (#252) is signed off and merged. Serve compass behind ORE Studio's gateway (#254) is signed off and merged. Open compass.web from ores.web (#256) is signed off and merged. Publish the developer link (#257) merged the packaging and install work; the team address remains the product owner's. Suggest searches and offer an AI mode (#259) is signed off and merged: the landing page keeps its box centered while typing, lists the closest documents in a combo box, and hands the typed query to the agent from AI mode. The agent's retrieval dropped compass itself; fixed and merged. The agent's model server runs as a tracked systemd user unit on the GPU with Qwen3.5-9B; verified and merged. Store and restore the agent's conversations is signed off and merged: built and verified in ten units on =feature/agent-sessions=, in #262. The last slice adds the Gemini-style sessions panel, the model's thinking shown collapsed, and a context indicator from llama-server's own token counts. | +| Waiting on | The product owner's team address for compass.web. | +| Next | Publish the developer link once the address is decided. | | Last touched | 2026-12-02 | * Acceptance