From c199953927d06002bcf84a9ae63ef839e35fa2ed Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 25 Nov 2026 15:48:39 +0100 Subject: [PATCH] Per-session workspace folder + structural identity reminder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - At the first interaction the session name locks and a personal folder is created under the workspace root (default ~/.strata-ctl/, 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). --- src/api/routes.rs | 17 ++++++++- src/api/sessions.rs | 83 +++++++++++++++++++++++++++++++++++++------ src/config.rs | 14 ++++++++ src/main.rs | 2 +- src/store.rs | 18 ++++++++++ tests/api_sessions.rs | 28 ++++++++++++++- 6 files changed, 148 insertions(+), 14 deletions(-) diff --git a/src/api/routes.rs b/src/api/routes.rs index c988eb4..4017362 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -29,22 +29,36 @@ pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router { AppState { service, store: None, + workspace_root: default_workspace_root(), }, auth, ) } /// Build the router with the session store + web GUI enabled, plus auth. -pub fn router_with_store(service: ChatService, store: Arc, auth: AuthConfig) -> Router { +/// `workspace_root` is the parent of the per-session personal folders. +pub fn router_with_store( + service: ChatService, + store: Arc, + auth: AuthConfig, + workspace_root: std::path::PathBuf, +) -> Router { build_router( AppState { service, store: Some(store), + workspace_root, }, 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 { let mut r = Router::new() .route("/health", get(health)) @@ -160,6 +174,7 @@ async fn auth_middleware( pub(crate) struct AppState { pub(crate) service: ChatService, pub(crate) store: Option>, + pub(crate) workspace_root: std::path::PathBuf, } /// An OpenAI error with the HTTP status the code implies. diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 5b4fb0a..554b25d 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -211,6 +211,13 @@ fn text_message(role: Role, text: String) -> ChatMessage { /// Prior `reasoning_content` is deliberately NOT replayed into the prompt. fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest { 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 { 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(), }; - let sess = match with_store(&st, { + let mut sess = match with_store(&st, { let id = id.clone(); move |s| s.get_session(&id) }) @@ -329,6 +336,33 @@ pub(crate) async fn session_chat( 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); // Persist the user turn before generating. @@ -355,16 +389,6 @@ pub(crate) async fn session_chat( 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. if body.agent { req.tools = Some(agent::agent_tools()); @@ -509,3 +533,40 @@ async fn persist_assistant(store: &Arc, sid: &str, a: &Accum, prompt_ }) .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)); + } +} diff --git a/src/config.rs b/src/config.rs index 346eed0..f3b0d14 100644 --- a/src/config.rs +++ b/src/config.rs @@ -84,6 +84,10 @@ pub struct Config { #[serde(default)] pub system_prompt: Option, + /// Parent of the per-session personal workspace folders (default `~/.strata-ctl`). + #[serde(default)] + pub workspace_root: Option, + /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Optional: both default to 600s when absent. #[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 — /// reported by `--check` so the shared-file contract stays visible. pub fn ignored_keys(&self) -> Vec<&str> { diff --git a/src/main.rs b/src/main.rs index 0257ec7..849c751 100644 --- a/src/main.rs +++ b/src/main.rs @@ -194,7 +194,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E if matches!(store.get_defaults(), Ok(None)) { 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 port = cfg.bind_port(cli_port); if !is_loopback_host(&host) && cfg.api_key.is_none() { diff --git a/src/store.rs b/src/store.rs index 9c47d87..4420b70 100644 --- a/src/store.rs +++ b/src/store.rs @@ -80,6 +80,8 @@ pub struct Session { /// Once the first message is sent the name becomes immutable (it is the /// agent's identity and names its personal folder). pub name_locked: bool, + /// Personal workspace folder, created at the first interaction (None until then). + pub folder: Option, pub created_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 update_settings(&self, id: &str, settings: &SessionSettings) -> 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 messages(&self, session_id: &str) -> Result>; fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result; @@ -166,6 +169,7 @@ CREATE TABLE IF NOT EXISTS sessions ( system_prompt TEXT, settings_json TEXT, name_locked INTEGER NOT NULL DEFAULT 0, + folder TEXT, created_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;", )?; } + if !has_col("sessions", "folder")? { + conn.execute_batch("ALTER TABLE sessions ADD COLUMN folder TEXT;")?; + } Ok(()) } @@ -278,6 +285,7 @@ fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result { model: row.get("model")?, settings, name_locked: row.get::<_, i64>("name_locked")? != 0, + folder: row.get("folder")?, created_at: row.get("created_at")?, updated_at: row.get("updated_at")?, }) @@ -305,6 +313,7 @@ impl Store for SqliteStore { model: model.to_string(), settings: settings.clone(), name_locked: false, + folder: None, created_at: now, updated_at: now, }) @@ -353,6 +362,15 @@ impl Store for SqliteStore { 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<()> { let conn = self.lock(); conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?; diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 2937827..0726e21 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -70,7 +70,12 @@ async fn build_app() -> (axum::Router, Arc) { ); let svc = ChatService::new(engine, Arc::new(ByteFormatter)); 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) } @@ -300,6 +305,27 @@ async fn agent_mode_streams_events_and_persists() { 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] async fn name_is_generated_editable_then_locked() { let (app, store) = build_app().await;