backend.cpp¶
src/storage/backend.cpp
@file backend.cpp @brief SqliteStorageBackend implementation.
Owners: @tvanfossen
bind_delegation_insert
static void entropic::bind_delegation_insert(sqlite3_stmt *s, const DelegationRecord &rec)
Bind a Delegation record onto the delegations-INSERT statement's 11 placeholders.
src/storage/backend.cpp:581
Source · 19 lines
static void bind_delegation_insert(sqlite3_stmt* s,
const DelegationRecord& rec) {
sqlite3_bind_text(s, 1, rec.id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, rec.parent_conversation_id.c_str(),
-1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 3, rec.child_conversation_id.c_str(),
-1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 4, rec.delegating_tier.c_str(),
-1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 5, rec.target_tier.c_str(),
-1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 6, rec.task.c_str(), -1, SQLITE_TRANSIENT);
bind_opt_int(s, 7, rec.max_turns);
sqlite3_bind_text(s, 8, rec.status.c_str(), -1, SQLITE_TRANSIENT);
bind_opt_text(s, 9, rec.result_summary);
sqlite3_bind_text(s, 10, rec.created_at.c_str(),
-1, SQLITE_TRANSIENT);
bind_opt_text(s, 11, rec.completed_at);
}Activity · 11 steps
Requirements
bind_message_insert
void entropic::anonymous_namespace{backend.cpp}::bind_message_insert(sqlite3_stmt *s, const std::string &conversation_id, const std::string &now, const MessageRow &r)Bind a MessageRow to the messages INSERT statement.
src/storage/backend.cpp:301
Source · 13 lines
void bind_message_insert(sqlite3_stmt* s, const std::string& conversation_id,
const std::string& now, const MessageRow& r) {
sqlite3_bind_text(s, 1, r.id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 3, r.role.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 4, r.content.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 5, r.tool_calls.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 6, r.tool_results.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int64(s, 7, r.token_count);
sqlite3_bind_text(s, 8, now.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 9, r.is_compacted ? 1 : 0);
bind_opt_text(s, 10, r.tier);
}Activity · 10 steps
Requirements
build_message_row
MessageRow entropic::anonymous_namespace{backend.cpp}::build_message_row(const json &m)Build a MessageRow from one message JSON object.
src/storage/backend.cpp:276
Source · 15 lines
MessageRow build_message_row(const json& m) {
MessageRow r;
r.id = generate_uuid();
r.role = m.value("role", "");
r.content = m.value("content", "");
r.tool_calls = m.contains("tool_calls") ? m["tool_calls"].dump() : "[]";
r.tool_results =
m.contains("tool_results") ? m["tool_results"].dump() : "[]";
r.token_count = m.value("token_count", 0);
r.is_compacted = m.value("is_compacted", false);
if (m.contains("identity_tier") && !m["identity_tier"].is_null()) {
r.tier = m["identity_tier"].get<std::string>();
}
return r;
}Activity · 11 steps
Requirements
close
void entropic::SqliteStorageBackend::close()
Close storage and database connection.
src/storage/backend.cpp:208
Source · 3 lines
void SqliteStorageBackend::close() {
db_.close();
}Activity · 1 steps
Requirements
complete_delegation
bool entropic::SqliteStorageBackend::complete_delegation(const std::string &delegation_id, const std::string &status, const std::optional< std::string > &result_summary=std::nullopt)
Mark a delegation as completed or failed.
src/storage/backend.cpp:712
Called by SCENARIO, SCENARIO, entropic_storage_complete_delegation, si_complete_delegation
Tested by 1 tests
test_complete_delegation
Calls bind_opt_text, execute, utc_timestamp
Source · 16 lines
bool SqliteStorageBackend::complete_delegation(
const std::string& delegation_id,
const std::string& status,
const std::optional<std::string>& result_summary) {
auto now = utc_timestamp();
return db_.execute(
"UPDATE delegations "
"SET status = ?, result_summary = ?, completed_at = ? "
"WHERE id = ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, status.c_str(), -1, SQLITE_TRANSIENT);
bind_opt_text(s, 2, result_summary);
sqlite3_bind_text(s, 3, now.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 4, delegation_id.c_str(), -1, SQLITE_TRANSIENT);
});
}Activity · 2 steps
Requirements
conversation_row_to_json
json entropic::anonymous_namespace{backend.cpp}::conversation_row_to_json(sqlite3_stmt *s)Map a conversations row to its JSON object.
src/storage/backend.cpp:375
Source · 11 lines
json conversation_row_to_json(sqlite3_stmt* s) {
json o;
o["id"] = col_text(s, 0);
o["title"] = col_text(s, 1);
o["created_at"] = col_text(s, 2);
o["updated_at"] = col_text(s, 3);
o["project_path"] = col_opt_text(s, 4).value_or("");
o["model_id"] = col_opt_text(s, 5).value_or("");
o["metadata"] = json::parse(col_text(s, 6), nullptr, false);
return o;
}Activity · 9 steps
Requirements
create_conversation
std::string entropic::SqliteStorageBackend::create_conversation(const std::string &title="New Conversation", const std::optional< std::string > &project_path=std::nullopt, const std::optional< std::string > &model_id=std::nullopt)
Create a new conversation.
src/storage/backend.cpp:223
Called by SCENARIO, SCENARIO, SCENARIO, create_delegation, entropic_storage_create_conversation, si_create_conversation
Calls bind_opt_text, execute, make_conversation
Source · 31 lines
std::string SqliteStorageBackend::create_conversation(
const std::string& title,
const std::optional<std::string>& project_path,
const std::optional<std::string>& model_id) {
auto rec = make_conversation(title, project_path, model_id);
const bool ok = db_.execute(
"INSERT INTO conversations "
"(id, title, created_at, updated_at, project_path, model_id, metadata) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, rec.id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, rec.title.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 3, rec.created_at.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 4, rec.updated_at.c_str(), -1, SQLITE_TRANSIENT);
bind_opt_text(s, 5, rec.project_path);
bind_opt_text(s, 6, rec.model_id);
sqlite3_bind_text(s, 7, rec.metadata.c_str(), -1, SQLITE_TRANSIENT);
});
// gh: fail loud. Returning the generated id after a failed INSERT told the
// caller a conversation existed when it did not — every later reference to
// that id then failed for a reason with no connection to the real cause.
if (!ok) {
logger->error("Failed to create conversation '{}' — INSERT did not "
"land, returning empty id", rec.id);
return std::string{};
}
logger->info("Created conversation: {}", rec.id);
return rec.id;
}Activity · 7 steps
Requirements
create_delegation
bool entropic::SqliteStorageBackend::create_delegation(const std::string &parent_conversation_id, const std::string &delegating_tier, const std::string &target_tier, const std::string &task, int max_turns, std::string &delegation_id, std::string &child_conversation_id)
Create a delegation record with a child conversation.
src/storage/backend.cpp:650
Called by SCENARIO, SCENARIO, entropic_storage_create_delegation, si_create_delegation
Tested by 1 tests
test_create_delegation
Calls bind_delegation_insert, create_conversation, execute, guard_parent_conversation, make_delegation
Source · 52 lines
bool SqliteStorageBackend::create_delegation(
const std::string& parent_conversation_id,
const std::string& delegating_tier,
const std::string& target_tier,
const std::string& task,
int max_turns,
std::string& delegation_id,
std::string& child_conversation_id) {
if (!guard_parent_conversation(parent_conversation_id,
delegating_tier, target_tier,
delegation_id,
child_conversation_id)) {
return false;
}
auto child_title = "Delegation: " + target_tier + " — " +
task.substr(0, 60);
child_conversation_id = create_conversation(
child_title, std::nullopt, target_tier);
auto rec = make_delegation(
parent_conversation_id, child_conversation_id,
delegating_tier, target_tier, task);
if (max_turns > 0) rec.max_turns = max_turns;
rec.status = "running";
bool ok = db_.execute(
"INSERT INTO delegations "
"(id, parent_conversation_id, child_conversation_id, "
"delegating_tier, target_tier, task, max_turns, "
"status, result_summary, created_at, completed_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[&](sqlite3_stmt* s) { bind_delegation_insert(s, rec); });
delegation_id = rec.id;
// gh#48 defense-in-depth (v2.1.12): log success only when the
// INSERT actually succeeded. Pre-v2.1.12 this fired
// unconditionally and masked the FK failure logged one line up
// by `database.cpp`'s `execute()` from anyone scanning for
// "Created delegation" in the session log.
if (ok) {
logger->info("Created delegation {}: {} -> {}",
rec.id, delegating_tier, target_tier);
} else {
logger->error("Failed to insert delegation {} ({} -> {}): "
"parent_conversation_id='{}' — check the SQL "
"execute error logged immediately above",
rec.id, delegating_tier, target_tier,
parent_conversation_id);
}
return ok;
}Activity · 15 steps
Requirements
delegation_row_to_json
json entropic::anonymous_namespace{backend.cpp}::delegation_row_to_json(sqlite3_stmt *s)Map a full delegations row to its JSON object.
src/storage/backend.cpp:738
Called by get_delegation_by_id, get_delegations
Calls col_nullable_int, col_opt_text, col_text, sanitize_storage_utf8
Source · 15 lines
json delegation_row_to_json(sqlite3_stmt* s) {
json entry;
entry["id"] = col_text(s, 0);
entry["parent_conversation_id"] = col_text(s, 1);
entry["child_conversation_id"] = col_text(s, 2);
entry["delegating_tier"] = col_text(s, 3);
entry["target_tier"] = col_text(s, 4);
entry["task"] = sanitize_storage_utf8(col_text(s, 5));
entry["max_turns"] = col_nullable_int(s, 6);
entry["status"] = col_text(s, 7);
entry["result_summary"] = sanitize_storage_utf8(col_opt_text(s, 8).value_or(""));
entry["created_at"] = col_text(s, 9);
entry["completed_at"] = col_opt_text(s, 10).value_or("");
return entry;
}Activity · 13 steps
Requirements
delegation_summary_to_json
json entropic::anonymous_namespace{backend.cpp}::delegation_summary_to_json(sqlite3_stmt *s)Map a delegations row to a search-result summary object.
src/storage/backend.cpp:765
Source · 13 lines
json delegation_summary_to_json(sqlite3_stmt* s) {
json entry;
entry["id"] = col_text(s, 0);
entry["parent_conversation_id"] = col_text(s, 1);
entry["child_conversation_id"] = col_text(s, 2);
entry["delegating_tier"] = col_text(s, 3);
entry["target_tier"] = col_text(s, 4);
entry["task"] = sanitize_storage_utf8(col_text(s, 5));
entry["status"] = col_text(s, 7);
entry["result_summary"] = sanitize_storage_utf8(col_opt_text(s, 8).value_or(""));
entry["completed_at"] = col_opt_text(s, 10).value_or("");
return entry;
}Activity · 11 steps
Requirements
delete_conversation
bool entropic::SqliteStorageBackend::delete_conversation(const std::string &conversation_id)
Delete a conversation and all associated records.
src/storage/backend.cpp:495
Source · 10 lines
bool SqliteStorageBackend::delete_conversation(
const std::string& conversation_id) {
bool ok = db_.execute(
"DELETE FROM conversations WHERE id = ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
});
if (ok) logger->info("Deleted conversation: {}", conversation_id);
return ok;
}Activity · 4 steps
Requirements
generate_uuid
std::string entropic::generate_uuid()
Generate a UUID v4 string.
src/storage/backend.cpp:981
Called by action_envelope_to_call, build_message_row, make_conversation, make_delegation, regex_recovered_tool_call, save_snapshot, tool_call_from_json
Calls none
Source · 22 lines
std::string generate_uuid() {
static thread_local std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<uint32_t> dist(0, 15);
std::uniform_int_distribution<uint32_t> dist2(8, 11);
const char hex[] = "0123456789abcdef";
std::string uuid(36, '-');
// 8-4-4-4-12 format
static constexpr int positions[] = {
0,1,2,3,4,5,6,7, 9,10,11,12, 14,15,16,17,
19,20,21,22, 24,25,26,27,28,29,30,31,32,33,34,35
};
for (int pos : positions) {
uuid[pos] = hex[dist(gen)];
}
uuid[14] = '4'; // version 4
uuid[19] = hex[dist2(gen)]; // variant 1
return uuid;
}Activity · 11 steps
Requirements
get_delegation_by_id
bool entropic::SqliteStorageBackend::get_delegation_by_id(const std::string &delegation_id, std::string &result_json)
Look up a single delegation record by id (gh#32, v2.1.6).
src/storage/backend.cpp:818
Called by SCENARIO, si_load_delegation_with_messages
Calls delegation_row_to_json, fetch_all
Source · 21 lines
bool SqliteStorageBackend::get_delegation_by_id(
const std::string& delegation_id,
std::string& result_json) {
bool found = false;
json entry;
db_.fetch_all(
"SELECT * FROM delegations WHERE id = ? LIMIT 1",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, delegation_id.c_str(), -1,
SQLITE_TRANSIENT);
},
[&](sqlite3_stmt* s) {
found = true;
entry = delegation_row_to_json(s);
});
if (!found) {
return false;
}
result_json = entry.dump();
return true;
}Activity · 7 steps
Requirements
get_delegations
bool entropic::SqliteStorageBackend::get_delegations(const std::string &conversation_id, std::string &result_json)
Get delegations for a parent conversation.
src/storage/backend.cpp:790
Called by SCENARIO, SCENARIO, entropic_storage_get_delegations
Calls delegation_row_to_json, fetch_all
Source · 18 lines
bool SqliteStorageBackend::get_delegations(
const std::string& conversation_id,
std::string& result_json) {
json arr = json::array();
db_.fetch_all(
"SELECT * FROM delegations "
"WHERE parent_conversation_id = ? "
"ORDER BY created_at ASC",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
},
[&](sqlite3_stmt* s) {
arr.push_back(delegation_row_to_json(s));
});
result_json = arr.dump();
return true;
}Activity · 4 steps
Requirements
get_stats
bool entropic::SqliteStorageBackend::get_stats(std::string &result_json)
Get storage statistics.
src/storage/backend.cpp:948
Source · 24 lines
bool SqliteStorageBackend::get_stats(std::string& result_json) {
int64_t total_convs = 0;
int64_t total_msgs = 0;
int64_t total_tokens = 0;
db_.fetch_one("SELECT COUNT(*) FROM conversations",
nullptr,
[&](sqlite3_stmt* s) { total_convs = sqlite3_column_int64(s, 0); });
db_.fetch_one("SELECT COUNT(*) FROM messages",
nullptr,
[&](sqlite3_stmt* s) { total_msgs = sqlite3_column_int64(s, 0); });
db_.fetch_one("SELECT COALESCE(SUM(token_count), 0) FROM messages",
nullptr,
[&](sqlite3_stmt* s) { total_tokens = sqlite3_column_int64(s, 0); });
json stats;
stats["total_conversations"] = total_convs;
stats["total_messages"] = total_msgs;
stats["total_tokens"] = total_tokens;
result_json = stats.dump();
return true;
}Activity · 12 steps
Requirements
guard_parent_conversation
static bool entropic::guard_parent_conversation(const std::string &parent_conversation_id, const std::string &delegating_tier, const std::string &target_tier, std::string &delegation_id, std::string &child_conversation_id)
Reject an empty parent_conversation_id with a clear error and reset the out params (gh#48 defense-in-depth).
src/storage/backend.cpp:620
Source · 16 lines
static bool guard_parent_conversation(
const std::string& parent_conversation_id,
const std::string& delegating_tier,
const std::string& target_tier,
std::string& delegation_id,
std::string& child_conversation_id) {
if (!parent_conversation_id.empty()) { return true; }
logger->error("create_delegation refused: parent_conversation_id "
"is empty (delegating_tier={}, target_tier={}). "
"Root conversation must be created before "
"delegating (gh#48).",
delegating_tier, target_tier);
delegation_id.clear();
child_conversation_id.clear();
return false;
}Activity · 6 steps
Requirements
initialize
bool entropic::SqliteStorageBackend::initialize()
Initialize storage (open database, run migrations).
src/storage/backend.cpp:199
Called by StorageHarness, TempStorage, entropic_storage_initialize, entropic_storage_open, init_persistence
Calls initialize
Source · 3 lines
bool SqliteStorageBackend::initialize() {
return db_.initialize();
}Activity · 1 steps
Requirements
latest_delegation_for_target
bool entropic::SqliteStorageBackend::latest_delegation_for_target(const std::string &target_tier, std::string &delegation_id)
Search delegations across all conversations (gh#32, v2.1.6).
src/storage/backend.cpp:849
Source · 20 lines
bool SqliteStorageBackend::latest_delegation_for_target(
const std::string& target_tier, std::string& delegation_id) {
bool found = false;
db_.fetch_all(
"SELECT id FROM delegations "
"WHERE target_tier = ? AND status = 'completed' "
"ORDER BY completed_at DESC LIMIT 1",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, target_tier.c_str(), -1,
SQLITE_TRANSIENT);
},
[&](sqlite3_stmt* s) {
const auto* text = sqlite3_column_text(s, 0);
if (text != nullptr) {
delegation_id = reinterpret_cast<const char*>(text);
found = true;
}
});
return found;
}Activity · 3 steps
Requirements
list_conversations
bool entropic::SqliteStorageBackend::list_conversations(int limit, int offset, std::string &result_json)
List conversations with pagination.
src/storage/backend.cpp:458
Called by SCENARIO, entropic_storage_list_conversations
Calls col_opt_text, col_text, fetch_all
Source · 28 lines
bool SqliteStorageBackend::list_conversations(
int limit, int offset, std::string& result_json) {
json arr = json::array();
db_.fetch_all(
"SELECT c.id, c.title, c.updated_at, c.project_path, "
"COUNT(m.id) as message_count "
"FROM conversations c "
"LEFT JOIN messages m ON c.id = m.conversation_id "
"GROUP BY c.id "
"ORDER BY c.updated_at DESC "
"LIMIT ? OFFSET ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_int(s, 1, limit);
sqlite3_bind_int(s, 2, offset);
},
[&](sqlite3_stmt* s) {
json entry;
entry["id"] = col_text(s, 0);
entry["title"] = col_text(s, 1);
entry["updated_at"] = col_text(s, 2);
entry["project_path"] = col_opt_text(s, 3).value_or("");
entry["message_count"] = sqlite3_column_int(s, 4);
arr.push_back(std::move(entry));
});
result_json = arr.dump();
return true;
}Activity · 4 steps
Requirements
load_conversation
bool entropic::SqliteStorageBackend::load_conversation(const std::string &conversation_id, std::string &result_json)
Load a conversation with messages.
src/storage/backend.cpp:418
Called by SCENARIO, entropic_storage_load_conversation, si_load_delegation_with_messages
Calls conversation_row_to_json, fetch_all, fetch_one, message_row_to_json
Source · 30 lines
bool SqliteStorageBackend::load_conversation(
const std::string& conversation_id,
std::string& result_json) {
json conv_obj;
bool found = db_.fetch_one(
"SELECT * FROM conversations WHERE id = ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
},
[&](sqlite3_stmt* s) { conv_obj = conversation_row_to_json(s); });
if (!found) return false;
json messages = json::array();
db_.fetch_all(
"SELECT * FROM messages WHERE conversation_id = ? "
"ORDER BY created_at ASC",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
},
[&](sqlite3_stmt* s) {
messages.push_back(message_row_to_json(s));
});
json result;
result["conversation"] = std::move(conv_obj);
result["messages"] = std::move(messages);
result_json = result.dump();
return true;
}Activity · 11 steps
Requirements
make_conversation
ConversationRecord entropic::make_conversation(const std::string &title="New Conversation", const std::optional< std::string > &project_path=std::nullopt, const std::optional< std::string > &model_id=std::nullopt)
Create a new ConversationRecord with generated UUID and timestamps.
src/storage/backend.cpp:1030
Source · 7 lines
ConversationRecord make_conversation(
const std::string& title,
const std::optional<std::string>& project_path,
const std::optional<std::string>& model_id) {
auto now = utc_timestamp();
return {generate_uuid(), title, now, now, project_path, model_id, "{}"};
}Activity · 2 steps
Requirements
make_delegation
DelegationRecord entropic::make_delegation(const std::string &parent_conversation_id, const std::string &child_conversation_id, const std::string &delegating_tier, const std::string &target_tier, const std::string &task)
Create a new DelegationRecord with generated UUID and timestamp.
src/storage/backend.cpp:1050
Source · 11 lines
DelegationRecord make_delegation(
const std::string& parent_conversation_id,
const std::string& child_conversation_id,
const std::string& delegating_tier,
const std::string& target_tier,
const std::string& task) {
return {generate_uuid(), parent_conversation_id,
child_conversation_id, delegating_tier, target_tier,
task, std::nullopt, "pending", std::nullopt,
utc_timestamp(), std::nullopt};
}Activity · 1 steps
Requirements
message_row_to_json
json entropic::anonymous_namespace{backend.cpp}::message_row_to_json(sqlite3_stmt *s)Map a messages row to its JSON object.
src/storage/backend.cpp:394
Source · 13 lines
json message_row_to_json(sqlite3_stmt* s) {
json m;
m["id"] = col_text(s, 0);
m["role"] = col_text(s, 2);
m["content"] = col_text(s, 3);
m["tool_calls"] = json::parse(col_text(s, 4), nullptr, false);
m["tool_results"] = json::parse(col_text(s, 5), nullptr, false);
m["token_count"] = sqlite3_column_int64(s, 6);
m["created_at"] = col_text(s, 7);
m["is_compacted"] = sqlite3_column_int(s, 8) != 0;
m["identity_tier"] = col_opt_text(s, 9).value_or("");
return m;
}Activity · 11 steps
Requirements
sanitize_storage_utf8
std::string entropic::anonymous_namespace{backend.cpp}::sanitize_storage_utf8(const std::string &s)Replace invalid UTF-8 byte sequences with U+FFFD (gh#112/gh#113).
src/storage/backend.cpp:84
Source · 18 lines
std::string sanitize_storage_utf8(const std::string& s) {
static constexpr const char* kRepl = "\xEF\xBF\xBD";
const auto* p = reinterpret_cast<const uint8_t*>(s.data());
const auto* end = p + s.size();
std::string out;
out.reserve(s.size());
while (p < end) {
size_t len = su8_seq_len(p, end);
if (len > 0) {
out.append(reinterpret_cast<const char*>(p), len);
p += len;
} else {
out.append(kRepl, 3);
++p;
}
}
return out;
}Activity · 14 steps
Requirements
save_messages
bool entropic::SqliteStorageBackend::save_messages(const std::string &conversation_id, const std::string &messages_json)
Save messages to a conversation.
src/storage/backend.cpp:325
Called by SCENARIO, entropic_storage_save_conversation, si_save_conversation
Calls bind_message_insert, build_message_row, execute, utc_timestamp
Source · 40 lines
bool SqliteStorageBackend::save_messages(
const std::string& conversation_id,
const std::string& messages_json) {
auto now = utc_timestamp();
db_.execute(
"UPDATE conversations SET updated_at = ? WHERE id = ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, now.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
});
auto msgs = json::parse(messages_json, nullptr, false);
if (!msgs.is_array()) {
logger->error("save_messages: invalid JSON array");
return false;
}
static constexpr const char* kInsertSql =
"INSERT INTO messages "
"(id, conversation_id, role, content, tool_calls, tool_results, "
"token_count, created_at, is_compacted, identity_tier) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
// gh: every row result was previously discarded and the function returned
// true unconditionally, so a caller could not tell a persisted turn from a
// lost one. Insert all rows, then report whether all of them landed.
bool all_ok = true;
for (const auto& m : msgs) {
auto row = build_message_row(m);
all_ok &= db_.execute(kInsertSql, [&](sqlite3_stmt* s) {
bind_message_insert(s, conversation_id, now, row);
});
}
if (!all_ok) {
logger->error("save_messages: one or more rows failed to insert for "
"conversation '{}' ({} message(s) attempted)",
conversation_id, msgs.size());
}
return all_ok;
}Activity · 14 steps
Requirements
save_snapshot
bool entropic::SqliteStorageBackend::save_snapshot(const std::string &conversation_id, const std::string &messages_json)
Save a pre-compaction snapshot of full conversation history.
src/storage/backend.cpp:915
Called by SCENARIO, entropic_storage_save_snapshot, si_save_snapshot
Tested by 1 tests
test_save_snapshot
Calls execute, generate_uuid, utc_timestamp
Source · 23 lines
bool SqliteStorageBackend::save_snapshot(
const std::string& conversation_id,
const std::string& messages_json) {
auto snap_id = generate_uuid();
auto now = utc_timestamp();
// Count messages
auto msgs = json::parse(messages_json, nullptr, false);
int msg_count = msgs.is_array() ? static_cast<int>(msgs.size()) : 0;
return db_.execute(
"INSERT INTO compaction_snapshots "
"(id, conversation_id, messages_json, message_count, "
"token_count_estimate, created_at) "
"VALUES (?, ?, ?, ?, NULL, ?)",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, snap_id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 3, messages_json.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 4, msg_count);
sqlite3_bind_text(s, 5, now.c_str(), -1, SQLITE_TRANSIENT);
});
}Activity · 5 steps
Requirements
search_conversations
bool entropic::SqliteStorageBackend::search_conversations(const std::string &query, int limit, std::string &result_json)
Full-text search across conversations.
src/storage/backend.cpp:536
Source · 29 lines
bool SqliteStorageBackend::search_conversations(
const std::string& query, int limit,
std::string& result_json) {
json arr = json::array();
db_.fetch_all(
"SELECT DISTINCT c.id, c.title, c.updated_at, "
"snippet(messages_fts, 0, '>>>', '<<<', '...', 32) as snippet "
"FROM messages_fts "
"JOIN messages m ON messages_fts.rowid = m.rowid "
"JOIN conversations c ON m.conversation_id = c.id "
"WHERE messages_fts MATCH ? "
"ORDER BY rank "
"LIMIT ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, query.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 2, limit);
},
[&](sqlite3_stmt* s) {
json entry;
entry["id"] = col_text(s, 0);
entry["title"] = col_text(s, 1);
entry["updated_at"] = col_text(s, 2);
entry["snippet"] = col_text(s, 3);
arr.push_back(std::move(entry));
});
result_json = arr.dump();
return true;
}Activity · 4 steps
Requirements
search_delegations
bool entropic::SqliteStorageBackend::search_delegations(const std::string &query, int max_results, std::string &result_json)
Substring-match delegations across all conversations.
src/storage/backend.cpp:885
Called by SCENARIO, sp_search_delegations
Source · 19 lines
bool SqliteStorageBackend::search_delegations(
const std::string& query, int max_results,
std::string& result_json) {
json arr = json::array();
std::string like = "%" + query + "%";
db_.fetch_all(
"SELECT * FROM delegations "
"WHERE result_summary LIKE ? AND status = 'completed' "
"ORDER BY completed_at DESC LIMIT ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, like.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(s, 2, max_results);
},
[&](sqlite3_stmt* s) {
arr.push_back(delegation_summary_to_json(s));
});
result_json = arr.dump();
return true;
}Activity · 5 steps
Requirements
su8_seq_len
size_t entropic::anonymous_namespace{backend.cpp}::su8_seq_len(const uint8_t *p, const uint8_t *end)Length of the valid sequence at p; 0 if malformed.
src/storage/backend.cpp:69
Source · 7 lines
size_t su8_seq_len(const uint8_t* p, const uint8_t* end) {
int n = su8_follow(*p);
bool ok = (n >= 0)
&& (n == 0 || (p + n < end && su8_first_cont_ok(*p, p[1])));
for (int i = 2; ok && i <= n; ++i) { ok = su8_is_cont(p[i]); }
return ok ? static_cast<size_t>(n + 1) : 0;
}Activity · 5 steps
Requirements
update_title
bool entropic::SqliteStorageBackend::update_title(const std::string &conversation_id, const std::string &title)
Update a conversation's title.
src/storage/backend.cpp:514
Source · 10 lines
bool SqliteStorageBackend::update_title(
const std::string& conversation_id,
const std::string& title) {
return db_.execute(
"UPDATE conversations SET title = ? WHERE id = ?",
[&](sqlite3_stmt* s) {
sqlite3_bind_text(s, 1, title.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(s, 2, conversation_id.c_str(), -1, SQLITE_TRANSIENT);
});
}Activity · 1 steps
Requirements
utc_timestamp
std::string entropic::utc_timestamp()
Get current UTC time as ISO 8601 string.
src/storage/backend.cpp:1010
Called by complete_delegation, make_conversation, make_delegation, save_messages, save_snapshot
Calls none
Source · 10 lines
std::string utc_timestamp() {
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
struct tm utc{};
gmtime_r(&time, &utc);
char buf[32];
std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &utc);
return buf;
}