Add context compositor: named sections from SQLite + DIALOG region

The model context is now composed by a dedicated module (src/context.rs) from named sections wrapped in <NAME>...</NAME>. Static sections (SYSTEM_PROMPT, TOOL_USE) live in a new context_sections SQLite table (seeded once, editable/extensible without recompiling); SYSTEM_PROMPT injects identity/speaker-note/session-SP via placeholders. DIALOG wraps the real role messages (history + new turn) with opener/closer markers so the engine keeps turn structure. Provenance/time helpers moved into the compositor; build_request now only assembles sampling. +tests (140 green), clippy/fmt clean; live probe confirms the model sees the sections.
This commit is contained in:
adm committed 2026-11-25 21:40:31 +01:00
1 parent 77bfa72689
commit a4722b7379
4 files changed
+433 -238

No files matched your search

+82
View File
@@ -171,6 +171,22 @@ pub struct UploadMeta {
pub created_at: i64,
}
/// One named, ordered section of the model context whose STATIC template lives
/// in the store (editable without recompiling). Rendered wrapped in
/// `<name>…</name>`; placeholders ({identity}, {speaker_note}, {session_prompt})
/// are filled per request. The dynamic DIALOG region is not a stored section.
#[derive(Debug, Clone, Serialize)]
pub struct ContextSection {
pub name: String,
pub content: String,
pub position: i64,
}
/// Bootstrap templates for the static context sections (seeded once into SQLite;
/// the DB rows are the source of truth afterwards).
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
fn create_session(
@@ -192,6 +208,9 @@ pub trait Store: Send + Sync {
/// The global default settings template (None until seeded).
fn get_defaults(&self) -> Result<Option<SessionSettings>>;
fn set_defaults(&self, settings: &SessionSettings) -> Result<()>;
/// The static context sections, ordered (SYSTEM_PROMPT, TOOL_USE, ...).
fn context_sections(&self) -> Result<Vec<ContextSection>>;
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()>;
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
}
@@ -252,6 +271,11 @@ CREATE TABLE IF NOT EXISTS uploads (
size INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS context_sections (
name TEXT PRIMARY KEY,
content TEXT NOT NULL,
position INTEGER NOT NULL
);
";
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
@@ -284,6 +308,7 @@ impl SqliteStore {
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.execute_batch(SCHEMA)?;
migrate(&conn)?;
seed_context_sections(&conn)?;
Ok(Self {
conn: Mutex::new(conn),
})
@@ -329,6 +354,20 @@ fn migrate(conn: &Connection) -> Result<()> {
Ok(())
}
/// Seed the static context sections once (idempotent); afterwards the stored
/// rows are authoritative and editable.
fn seed_context_sections(conn: &Connection) -> Result<()> {
conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
params![SYSTEM_PROMPT_SECTION],
)?;
conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
params![TOOL_USE_SECTION],
)?;
Ok(())
}
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
let settings_json: Option<String> = row.get("settings_json")?;
let settings = match settings_json {
@@ -586,6 +625,30 @@ impl Store for SqliteStore {
Ok(())
}
fn context_sections(&self) -> Result<Vec<ContextSection>> {
let conn = self.lock();
let mut stmt = conn.prepare(
"SELECT name, content, position FROM context_sections ORDER BY position ASC, name ASC",
)?;
let rows = stmt.query_map([], |r| {
Ok(ContextSection {
name: r.get(0)?,
content: r.get(1)?,
position: r.get(2)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()> {
let conn = self.lock();
conn.execute(
"INSERT OR REPLACE INTO context_sections (name, content, position) VALUES (?1, ?2, ?3)",
params![name, content, position],
)?;
Ok(())
}
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
let conn = self.lock();
conn.execute(
@@ -770,6 +833,25 @@ mod tests {
assert!(s.get_session(&sess.id).unwrap().unwrap().name_locked);
}
#[test]
fn context_sections_seeded_editable_and_extensible() {
let s = store();
let secs = s.context_sections().unwrap();
assert_eq!(secs.len(), 2);
assert_eq!(secs[0].name, "SYSTEM_PROMPT");
assert_eq!(secs[1].name, "TOOL_USE");
// Edits persist and reorder by position; new sections can be added.
s.set_context_section("SYSTEM_PROMPT", "custom {identity}", 5)
.unwrap();
s.set_context_section("EXTRA", "x", 2).unwrap();
let secs = s.context_sections().unwrap();
assert_eq!(secs.len(), 3);
assert_eq!(secs[0].name, "TOOL_USE"); // position 1
assert_eq!(secs[1].name, "EXTRA"); // position 2
assert_eq!(secs[2].name, "SYSTEM_PROMPT"); // position 5
assert_eq!(secs[2].content, "custom {identity}");
}
#[test]
fn defaults_roundtrip_and_overlay() {
let s = store();