Per-session workspace folder + structural identity reminder

- At the first interaction the session name locks and a personal folder is created under the workspace root (default ~/.strata-ctl/<slug>, configurable via workspace_root); slug is filesystem-safe and unique. Stored in sessions.folder (idempotent migration).

- build_request always prepends a structural identity reminder ('Il tuo nome è X. La tua cartella personale è Y.') before the session SP — not an editable setting; gives the agent awareness of its workspace. router_with_store takes the workspace root. 114 tests green; verified live (folder created, name locked).
This commit is contained in:
adm committed 2026-11-25 15:48:39 +01:00
1 parent 0568b92e06
commit c199953927
6 files changed
+148 -14

No files matched your search

+16 -1
View File
@@ -29,22 +29,36 @@ pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
AppState { AppState {
service, service,
store: None, store: None,
workspace_root: default_workspace_root(),
}, },
auth, auth,
) )
} }
/// Build the router with the session store + web GUI enabled, plus auth. /// Build the router with the session store + web GUI enabled, plus auth.
pub fn router_with_store(service: ChatService, store: Arc<dyn Store>, auth: AuthConfig) -> Router { /// `workspace_root` is the parent of the per-session personal folders.
pub fn router_with_store(
service: ChatService,
store: Arc<dyn Store>,
auth: AuthConfig,
workspace_root: std::path::PathBuf,
) -> Router {
build_router( build_router(
AppState { AppState {
service, service,
store: Some(store), store: Some(store),
workspace_root,
}, },
auth, auth,
) )
} }
/// Default parent of the per-session workspace folders: `~/.strata-ctl`.
fn default_workspace_root() -> std::path::PathBuf {
let home = std::env::var("HOME").unwrap_or_default();
std::path::PathBuf::from(home).join(".strata-ctl")
}
fn build_router(state: AppState, auth: AuthConfig) -> Router { fn build_router(state: AppState, auth: AuthConfig) -> Router {
let mut r = Router::new() let mut r = Router::new()
.route("/health", get(health)) .route("/health", get(health))
@@ -160,6 +174,7 @@ async fn auth_middleware(
pub(crate) struct AppState { pub(crate) struct AppState {
pub(crate) service: ChatService, pub(crate) service: ChatService,
pub(crate) store: Option<Arc<dyn Store>>, pub(crate) store: Option<Arc<dyn Store>>,
pub(crate) workspace_root: std::path::PathBuf,
} }
/// An OpenAI error with the HTTP status the code implies. /// An OpenAI error with the HTTP status the code implies.
+72 -11
View File
@@ -211,6 +211,13 @@ fn text_message(role: Role, text: String) -> ChatMessage {
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt. /// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest { fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
let mut messages = Vec::new(); let mut messages = Vec::new();
// Structural identity reminder: always present, not an editable setting. It
// tells the agent its name and personal workspace folder.
let mut identity = format!("Il tuo nome è {}.", sess.title);
if let Some(folder) = &sess.folder {
identity.push_str(&format!(" La tua cartella personale è {folder}."));
}
messages.push(text_message(Role::System, identity));
if let Some(sp) = &sess.settings.system_prompt { if let Some(sp) = &sess.settings.system_prompt {
messages.push(text_message(Role::System, sp.clone())); messages.push(text_message(Role::System, sp.clone()));
} }
@@ -309,7 +316,7 @@ pub(crate) async fn session_chat(
None => return Error::internal("no store configured").into_response(), None => return Error::internal("no store configured").into_response(),
}; };
let sess = match with_store(&st, { let mut sess = match with_store(&st, {
let id = id.clone(); let id = id.clone();
move |s| s.get_session(&id) move |s| s.get_session(&id)
}) })
@@ -329,6 +336,33 @@ pub(crate) async fn session_chat(
Err(e) => return e.into_response(), Err(e) => return e.into_response(),
}; };
// The first interaction locks the name and creates the session's personal
// workspace folder (its identity). Done before building the prompt so the
// identity reminder can reference the folder.
if history.is_empty() {
let root = st.workspace_root.clone();
let title = sess.title.clone();
let idc = id.clone();
if let Ok(folder) = with_store(&st, move |s| {
s.set_name_locked(&idc, true)?;
let slug = name::slug(&title);
let mut candidate = root.join(&slug);
let mut n = 2;
while candidate.exists() {
candidate = root.join(format!("{slug}-{n}"));
n += 1;
}
std::fs::create_dir_all(&candidate)?;
let path = candidate.to_string_lossy().into_owned();
s.set_folder(&idc, &path)?;
Ok(path)
})
.await
{
sess.folder = Some(folder);
}
}
let mut req = build_request(&sess, &history, &body); let mut req = build_request(&sess, &history, &body);
// Persist the user turn before generating. // Persist the user turn before generating.
@@ -355,16 +389,6 @@ pub(crate) async fn session_chat(
return e.into_response(); return e.into_response();
} }
// The first interaction locks the session name: it becomes the agent's
// immutable identity (and names its personal folder, created next increment).
if history.is_empty() {
let _ = with_store(&st, {
let id = id.clone();
move |s| s.set_name_locked(&id, true)
})
.await;
}
// Agent mode: drive the model↔shell_exec loop, streaming progress events. // Agent mode: drive the model↔shell_exec loop, streaming progress events.
if body.agent { if body.agent {
req.tools = Some(agent::agent_tools()); req.tools = Some(agent::agent_tools());
@@ -509,3 +533,40 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
}) })
.await; .await;
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_request_prepends_identity_reminder_then_sp() {
let sess = Session {
id: "s".into(),
title: "Pippo".into(),
model: "m".into(),
settings: SessionSettings {
system_prompt: Some("sii breve".into()),
..Default::default()
},
name_locked: true,
folder: Some("/tmp/pippo".into()),
created_at: 0,
updated_at: 0,
};
let body = SessionChat {
content: "ciao".into(),
stream: false,
agent: false,
max_tokens: None,
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body);
// Identity reminder first (name + folder), then the session SP, then user.
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
assert_eq!(req.messages[1].text().unwrap(), "sii breve");
assert!(matches!(req.messages.last().unwrap().role, Role::User));
}
}
+14
View File
@@ -84,6 +84,10 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub system_prompt: Option<String>, pub system_prompt: Option<String>,
/// Parent of the per-session personal workspace folders (default `~/.strata-ctl`).
#[serde(default)]
pub workspace_root: Option<String>,
/// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds.
/// Optional: both default to 600s when absent. /// Optional: both default to 600s when absent.
#[serde(default)] #[serde(default)]
@@ -224,6 +228,16 @@ impl Config {
} }
} }
/// Effective workspace root: config > `~/.strata-ctl`. Each session's
/// personal folder is created under this root at its first interaction.
pub fn workspace_root(&self) -> PathBuf {
if let Some(p) = &self.workspace_root {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join(".strata-ctl")
}
/// The top-level keys present in the file that we are not acting on — /// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible. /// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> { pub fn ignored_keys(&self) -> Vec<&str> {
+1 -1
View File
@@ -194,7 +194,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
if matches!(store.get_defaults(), Ok(None)) { if matches!(store.get_defaults(), Ok(None)) {
let _ = store.set_defaults(&cfg.default_settings()); let _ = store.set_defaults(&cfg.default_settings());
} }
let app = router_with_store(svc, store, auth); let app = router_with_store(svc, store, auth, cfg.workspace_root());
let host = cfg.bind_host(cli_host); let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port); let port = cfg.bind_port(cli_port);
if !is_loopback_host(&host) && cfg.api_key.is_none() { if !is_loopback_host(&host) && cfg.api_key.is_none() {
+18
View File
@@ -80,6 +80,8 @@ pub struct Session {
/// Once the first message is sent the name becomes immutable (it is the /// Once the first message is sent the name becomes immutable (it is the
/// agent's identity and names its personal folder). /// agent's identity and names its personal folder).
pub name_locked: bool, pub name_locked: bool,
/// Personal workspace folder, created at the first interaction (None until then).
pub folder: Option<String>,
pub created_at: i64, pub created_at: i64,
pub updated_at: i64, pub updated_at: i64,
} }
@@ -131,6 +133,7 @@ pub trait Store: Send + Sync {
fn rename_session(&self, id: &str, title: &str) -> Result<()>; fn rename_session(&self, id: &str, title: &str) -> Result<()>;
fn update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()>; fn update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()>;
fn set_name_locked(&self, id: &str, locked: bool) -> Result<()>; fn set_name_locked(&self, id: &str, locked: bool) -> Result<()>;
fn set_folder(&self, id: &str, folder: &str) -> Result<()>;
fn delete_session(&self, id: &str) -> Result<()>; fn delete_session(&self, id: &str) -> Result<()>;
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>; fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>; fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
@@ -166,6 +169,7 @@ CREATE TABLE IF NOT EXISTS sessions (
system_prompt TEXT, system_prompt TEXT,
settings_json TEXT, settings_json TEXT,
name_locked INTEGER NOT NULL DEFAULT 0, name_locked INTEGER NOT NULL DEFAULT 0,
folder TEXT,
created_at INTEGER NOT NULL, created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL updated_at INTEGER NOT NULL
); );
@@ -257,6 +261,9 @@ fn migrate(conn: &Connection) -> Result<()> {
"ALTER TABLE sessions ADD COLUMN name_locked INTEGER NOT NULL DEFAULT 0;", "ALTER TABLE sessions ADD COLUMN name_locked INTEGER NOT NULL DEFAULT 0;",
)?; )?;
} }
if !has_col("sessions", "folder")? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN folder TEXT;")?;
}
Ok(()) Ok(())
} }
@@ -278,6 +285,7 @@ fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
model: row.get("model")?, model: row.get("model")?,
settings, settings,
name_locked: row.get::<_, i64>("name_locked")? != 0, name_locked: row.get::<_, i64>("name_locked")? != 0,
folder: row.get("folder")?,
created_at: row.get("created_at")?, created_at: row.get("created_at")?,
updated_at: row.get("updated_at")?, updated_at: row.get("updated_at")?,
}) })
@@ -305,6 +313,7 @@ impl Store for SqliteStore {
model: model.to_string(), model: model.to_string(),
settings: settings.clone(), settings: settings.clone(),
name_locked: false, name_locked: false,
folder: None,
created_at: now, created_at: now,
updated_at: now, updated_at: now,
}) })
@@ -353,6 +362,15 @@ impl Store for SqliteStore {
Ok(()) Ok(())
} }
fn set_folder(&self, id: &str, folder: &str) -> Result<()> {
let conn = self.lock();
conn.execute(
"UPDATE sessions SET folder = ?2 WHERE id = ?1",
params![id, folder],
)?;
Ok(())
}
fn delete_session(&self, id: &str) -> Result<()> { fn delete_session(&self, id: &str) -> Result<()> {
let conn = self.lock(); let conn = self.lock();
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?; conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
+27 -1
View File
@@ -70,7 +70,12 @@ async fn build_app() -> (axum::Router, Arc<SqliteStore>) {
); );
let svc = ChatService::new(engine, Arc::new(ByteFormatter)); let svc = ChatService::new(engine, Arc::new(ByteFormatter));
let store = Arc::new(SqliteStore::open_in_memory().unwrap()); let store = Arc::new(SqliteStore::open_in_memory().unwrap());
let app = router_with_store(svc, store.clone(), AuthConfig::default()); let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!("strata-ctl-test-{nanos}"));
let app = router_with_store(svc, store.clone(), AuthConfig::default(), root);
(app, store) (app, store)
} }
@@ -300,6 +305,27 @@ async fn agent_mode_streams_events_and_persists() {
assert_eq!(msgs.last().unwrap().content, "efghi"); assert_eq!(msgs.last().unwrap().content, "efghi");
} }
#[tokio::test]
async fn first_interaction_creates_personal_folder() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
assert!(store.get_session(&id).unwrap().unwrap().folder.is_none());
req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "ciao"})),
)
.await;
let s = store.get_session(&id).unwrap().unwrap();
let folder = s
.folder
.expect("personal folder created at first interaction");
assert!(std::path::Path::new(&folder).is_dir());
assert!(s.name_locked);
let _ = std::fs::remove_dir_all(&folder);
}
#[tokio::test] #[tokio::test]
async fn name_is_generated_editable_then_locked() { async fn name_is_generated_editable_then_locked() {
let (app, store) = build_app().await; let (app, store) = build_app().await;