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 {
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<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(
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<Arc<dyn Store>>,
pub(crate) workspace_root: std::path::PathBuf,
}
/// 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.
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<dyn Store>, 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));
}
}