diff --git a/crates/rhema-claw/SYSTEM.md b/crates/rhema-claw/SYSTEM.md index 530cf66..0edc437 100644 --- a/crates/rhema-claw/SYSTEM.md +++ b/crates/rhema-claw/SYSTEM.md @@ -1,8 +1,15 @@ You are the resident agent on this machine. This session's key is {{ session }}. -You answer chat here. Your shell runs in the workspace at {{ workspace }}. -Keep replies concrete. Do the work with tools instead of narrating it. -Your final message, the one you end the turn on with no tool calls after -it, is the reply the user sees. +Your shell runs in the workspace at {{ workspace }}. +Keep replies concrete. Do the work with tools instead of narrating it. +{% if surface == 'forge' %} +You answer forge threads — review requests, assignments, and mentions on +the repositories you watch. Your final message, the one you end the turn +on with no tool calls after it, is the comment posted to the thread +verbatim. +{% else %} +You answer chat here. Your final message, the one you end the turn on +with no tool calls after it, is the reply the user sees. +{% endif %} ## Soul @@ -36,6 +43,27 @@ what it is for. The arguments are the JSON schema a call must satisfy. {{ vision }} {% endif %} +{% if mcp %} + +## MCP servers + +Available MCP servers: +{% for server in mcp %}- {{ server.name }} (server: {{ server.server }}): {{ server.description }} +{% endfor %} + +MCP servers are reachable through bash commands (**not** direct tool calls). +Usage: + + {{ mcp[0].name }} --help # a server's tools + {{ mcp[0].name }} --help # one tool's arguments + {{ mcp[0].name }} --schema # one tool's exact input JSON + {{ mcp[0].name }} --flag value # a call; --prop_json for nested values + {{ mcp[0].name }} --json - <<'EOF' ... EOF # nested payloads: heredoc, no quoting + mcp servers | mcp tools | mcp call + +{% endif %} + +{% if memory %} ## Memory You keep persistent memory across sessions. memory_save stores what is @@ -43,6 +71,7 @@ worth remembering: decisions, conventions, corrections, pointers. memory_search recalls it; search before asking the user for something they have likely said before. memory_forget removes a record on request. Never save secrets into memory. +{% endif %} {% if onboarding %} {{ onboarding }} diff --git a/crates/rhema-claw/src/bootstrap.rs b/crates/rhema-claw/src/bootstrap.rs index 47a7a95..2fe90f4 100644 --- a/crates/rhema-claw/src/bootstrap.rs +++ b/crates/rhema-claw/src/bootstrap.rs @@ -197,15 +197,32 @@ fn section(header: &str, content: Option<&str>, stub: &str) -> String { format!("{header}\n\n{}", content.unwrap_or(stub)) } +/// Which surface a dispatch answers on: the template's opening and +/// reply contract differ — a chat reply goes to the user, a forge +/// reply goes to the thread — and onboarding is a chat offer only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Surface { + /// The chat surfaces: interactive sessions, tasks, phone, reminders. + Chat, + /// A forge thread dispatch: a watch event answered on the forge. + Forge, +} + /// Renders the system prompt for one dispatch through the agent /// toolkit's Jinja renderer: `{{ workspace }}` and the three file /// sections from the live store, `tools` from the dispatch's own /// resolver specs, `{{ session }}` — the dispatching key, the address /// the model schedules its own wakes to — and `onboarding`, the offer -/// the template's `{% if %}` shows only while a file is unwritten. -/// Fallible on purpose — a store that cannot be read surfaces loudly -/// instead of rendering a prompt without it, and a template that -/// cannot render fails the dispatch before any model call. +/// the template's `{% if %}` shows only while a file is unwritten, and +/// only on a chat surface: a forge dispatch is nobody's first +/// conversation. `mcp` renders the wired servers' section, empty on a +/// surface with none; the memory section renders only when the roster +/// actually carries the memory tools, so a forge prompt never +/// documents tools it does not have. Fallible on purpose — a store +/// that cannot be read surfaces loudly instead of rendering a prompt +/// without it, and a template that cannot render fails the dispatch +/// before any model call. +#[expect(clippy::too_many_arguments, reason = "eight parts, each load-bearing")] pub fn render_system( template: &str, session: &str, @@ -213,15 +230,18 @@ pub fn render_system( bootstrap: &Bootstrap, tools: &[ToolSpec], vision: Option<&str>, + mcp: &[rhema_config::mcp::McpServerLine], + surface: Surface, ) -> Result { let soul = bootstrap.load(BootstrapKind::Soul)?; let user = bootstrap.load(BootstrapKind::User)?; let environment = bootstrap.load(BootstrapKind::Environment)?; - let onboarding = if soul.is_none() || user.is_none() { + let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) { ONBOARDING_MD } else { "" }; + let memory = tools.iter().any(|spec| spec.name == "memory_save"); let context = json!({ "session": session, "workspace": workspace.display().to_string(), @@ -231,6 +251,12 @@ pub fn render_system( "onboarding": onboarding, "tools": tools, "vision": vision, + "mcp": mcp, + "memory": memory, + "surface": match surface { + Surface::Chat => "chat", + Surface::Forge => "forge", + }, }); render_template(template, &context).map_err(|err| { let line = err @@ -427,6 +453,8 @@ mod tests { &bootstrap, &tools, None, + &[], + Surface::Chat, ) .expect("renders"); assert!(prompt.contains("## SOUL"), "{prompt}"); @@ -439,6 +467,110 @@ mod tests { assert!(prompt.contains("bootstrap_save"), "{prompt}"); } + #[test] + fn a_fresh_house_on_the_forge_surface_never_carries_the_onboarding() { + let (_dir, bootstrap) = store(); + let prompt = render_system( + DEFAULT_SYSTEM_MD, + "github:issue:acme/widgets#7", + Path::new("/ws"), + &bootstrap, + &[], + None, + &[], + Surface::Forge, + ) + .expect("renders"); + assert!( + !prompt.contains("## Onboarding"), + "a forge thread is nobody's first conversation: {prompt}" + ); + assert!( + prompt.contains("the comment posted to the thread"), + "the forge branch of the reply contract: {prompt}" + ); + assert!( + !prompt.contains("You answer chat here"), + "not the chat branch: {prompt}" + ); + assert_eq!(prompt.matches(PENDING).count(), 2, "{prompt}"); + } + + #[test] + fn the_memory_section_renders_only_when_the_roster_carries_the_tools() { + let (_dir, bootstrap) = store(); + let memory = [ToolSpec::new( + "memory_save", + "stores a record", + json!({"type": "object"}), + )]; + let with = render_system( + DEFAULT_SYSTEM_MD, + "interactive:web", + Path::new("/ws"), + &bootstrap, + &memory, + None, + &[], + Surface::Chat, + ) + .expect("renders"); + let without = render_system( + DEFAULT_SYSTEM_MD, + "github:issue:acme/widgets#7", + Path::new("/ws"), + &bootstrap, + &[], + None, + &[], + Surface::Forge, + ) + .expect("renders"); + assert!(with.contains("## Memory"), "{with}"); + assert!( + !without.contains("## Memory"), + "no memory tools, no memory section: {without}" + ); + } + + #[test] + fn the_wired_mcp_servers_render_their_section() { + let (_dir, bootstrap) = store(); + let mcp = [rhema_config::mcp::McpServerLine { + name: "acme-mcp".to_owned(), + server: "acme".to_owned(), + description: "the acme tools".to_owned(), + }]; + let prompt = render_system( + DEFAULT_SYSTEM_MD, + "github:issue:acme/widgets#7", + Path::new("/ws"), + &bootstrap, + &[], + None, + &mcp, + Surface::Forge, + ) + .expect("renders"); + assert!(prompt.contains("## MCP servers"), "{prompt}"); + assert!( + prompt.contains("- acme-mcp (server: acme): the acme tools"), + "{prompt}" + ); + let bare = render_system( + DEFAULT_SYSTEM_MD, + "interactive:web", + Path::new("/ws"), + &bootstrap, + &[], + None, + &[], + Surface::Chat, + ) + .expect("renders"); + assert!(!bare.contains("## MCP servers"), "{bare}"); + } + #[test] fn the_full_house_renders_each_file_and_drops_the_onboarding_section() { let (_dir, bootstrap) = store(); @@ -456,6 +588,8 @@ mod tests { &bootstrap, &[], None, + &[], + Surface::Chat, ) .expect("renders"); assert!( @@ -484,6 +618,8 @@ mod tests { &bootstrap, &[], None, + &[], + Surface::Chat, ) .expect("renders"); assert!(prompt.contains(content), "{prompt}"); @@ -516,6 +652,8 @@ mod tests { &bootstrap, &tools, None, + &[], + Surface::Chat, ) .expect("renders"); assert!(prompt.contains("- my_tool | {"), "{prompt}"); diff --git a/crates/rhema-claw/src/daemon.rs b/crates/rhema-claw/src/daemon.rs index 6d26186..8200cad 100644 --- a/crates/rhema-claw/src/daemon.rs +++ b/crates/rhema-claw/src/daemon.rs @@ -360,11 +360,17 @@ impl Daemon { .map(|url| format!(" ({url})")) .unwrap_or_default(), ); + // The bootstrap store, before both handlers: the chat renders + // its files per dispatch, and so does the forge one now — the + // persona is shared, the workspaces are not. The environment + // report lands in the store's directory at boot, below. + let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?); let forge_handler = ClawHandler::new( backends.clone(), workspace_root, watches.clone(), accounts.clone(), + bootstrap.clone(), config.transcript_enabled(), tool_env.clone(), ) @@ -400,7 +406,6 @@ impl Daemon { // `phone` tool queues behind a consent. let phone = Arc::new(crate::phone::PhoneStore::open(&db)?); let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?); - let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?); // The identity store shares the settings table and keeps its // images beside the database. let identity = Arc::new(crate::identity::IdentityStore::new( diff --git a/crates/rhema-claw/src/handler.rs b/crates/rhema-claw/src/handler.rs index c356643..1a15dc3 100644 --- a/crates/rhema-claw/src/handler.rs +++ b/crates/rhema-claw/src/handler.rs @@ -23,6 +23,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; +use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, Surface}; use crate::forge::{WatchCredential, record_client, resolve_watch_credential}; use crate::watch_store::ClawStore; use rhema_autonomous_agent::{Handler, SessionContext, async_trait}; @@ -56,7 +57,18 @@ fn allowlist() -> rhema_autonomous_agent::Allowlist { /// The coding agent over one watch: a provider, a model, a workspace /// root, and the watch table the dispatch keys resolve through — live, /// so a watch added at runtime is answerable without a restart. +/// +/// The agent is the resident's: every dispatch renders the same +/// bootstrap prompt the chat surfaces render — SOUL.md, USER.md, the +/// environment report — over the thread's workspace, so the claw that +/// answers a review or a mention is the character the user chats with, +/// not a nameless delegate. The tools stay the coding set (shell, +/// vision, MCP); the chat-only rosters (memory, notifications, the +/// key-scoped asks) do not ride a forge dispatch. pub struct ClawHandler { + /// The bootstrap store the persona renders from, per dispatch, so + /// a SOUL.md the chat wrote is live on the next forge answer. + bootstrap: Arc, /// The deployment's providers and the active pair, read per dispatch. backends: Arc, /// Whether the sessions run the bounded request view (the config's @@ -86,6 +98,7 @@ impl ClawHandler { workspace_root: impl Into, watches: Arc, accounts: Arc, + bootstrap: Arc, transcript: bool, tool_env: std::collections::BTreeMap, ) -> Self { @@ -95,6 +108,7 @@ impl ClawHandler { workspace_root: workspace_root.into(), watches, accounts, + bootstrap, tool_env, sandbox: None, clients: Mutex::new(HashMap::new()), @@ -344,7 +358,7 @@ impl ClawHandler { key: &str, ) -> Result { let (provider, model) = self.backends.current(); - let config = self.agent_config(provider, &model, workspace); + let config = self.agent_config(provider, &model, workspace, key)?; let agent = match &ctx.session.core.driver_state { // A never-dispatched key carries no stash: start clean. serde_json::Value::Null => HostAgent::new(config), @@ -357,17 +371,20 @@ impl ClawHandler { agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}")) } - /// The config one dispatch's agent runs on: the default coding - /// agent's, with the bounded request view when the config has it on - /// and a remote shell when the sandbox choice says so. - /// A forge thread answers for as long as the thread lives; without - /// the view its history would ride whole on every step. + /// The config one dispatch's agent runs on: the resident's own + /// prompt — the bootstrap template rendered per dispatch over the + /// thread's workspace, SOUL.md and USER.md live — with the bounded + /// request view when the config has it on and a remote shell when + /// the sandbox choice says so. A forge thread answers for as long + /// as the thread lives; without the view its history would ride + /// whole on every step. fn agent_config( &self, provider: Arc, model: &str, workspace: &Path, - ) -> HostAgentConfig { + key: &str, + ) -> Result { let display = match &self.sandbox { Some(sandbox) => sandbox.workspace_for(workspace), None => workspace.to_path_buf(), @@ -379,19 +396,47 @@ impl ClawHandler { .transcript .then(rhema_transcript::TranscriptSettings::default); config.shell_env = self.tool_env.clone(); + // The prompt names the workspace the model sees and documents + // exactly what the request advertises: the shell built-ins plus + // the transcript's zoom when the view is on — the same assembly + // the host agent does for its own default prompt. A verbatim + // prompt ignores the config's template sections, so the vision + // and MCP documentation render here from the same wired values; + // a remote sandbox wires neither. + let mut vision = None; + let mut mcp = Vec::new(); match &self.sandbox { Some(sandbox) if sandbox.is_remote() => { config.tools = Some(Arc::new(ShellTools::with_executor( - display, + display.clone(), sandbox.executor(workspace.to_path_buf()), ))); } _ => { crate::vision::apply(&mut config); crate::mcp::apply(&mut config); + vision = config.vision.clone(); + mcp = config.mcp_servers.clone(); } } - config + let mut specs = ShellTools::builtin_specs(); + if config.transcript.is_some() { + specs.push(rhema_transcript::Zoom::spec()); + } + config.system = Some( + crate::bootstrap::render_system( + DEFAULT_SYSTEM_MD, + key, + &display, + &self.bootstrap, + &specs, + vision.as_deref(), + &mcp, + Surface::Forge, + ) + .map_err(|err| format!("cannot render the forge system prompt for {key}: {err}"))?, + ); + Ok(config) } /// The per-thread workspace: one directory under the root, created on @@ -626,30 +671,31 @@ fn dominant_role(news: &[InboxNews]) -> Option { } } -/// The persona framing a dispatched role opens the prompt with. The key -/// stays the thread, so a role change across dispatches is the session's +/// The task framing a dispatched role opens the prompt with. Who is +/// answering lives in the system prompt — SOUL.md, the same file every +/// chat dispatch renders; this is only what the job is. The key stays +/// the thread, so a role change across dispatches is the session's /// continuity, not a new conversation. -fn persona_text(role: Role) -> &'static str { +fn task_text(role: Role) -> &'static str { match role { Role::Reviewer => { - "You are acting as this pull request's reviewer. Check the change \ -out in the workspace when you can, read the diff, and judge it: correctness, \ -tests, edge cases, fit with the surrounding code. Your final reply is the \ -review — findings first, ordered by severity, concrete and actionable; if \ -there is nothing to fix, say so plainly and say what you checked." + "This dispatch is a review request. Check the change out in the \ +workspace when you can, read the diff, and judge it: correctness, tests, \ +edge cases, fit with the surrounding code. Make the reply the review — \ +findings first, ordered by severity, concrete and actionable; if there is \ +nothing to fix, say so plainly and say what you checked." } Role::Implementer => { - "You are acting as this thread's implementer. Do the work the new \ -activity asks for: address the review feedback or the assigned issue by \ -changing the code in the workspace — build and test what you change. Your \ -final reply is a short report of what you changed and why, or, when the \ -whole change does not fit one turn, what landed now and the concrete plan \ -for the rest." + "This dispatch asks for work. Address the review feedback or the \ +assigned issue by changing the code in the workspace — build and test what \ +you change. Make the reply a short report of what you changed and why, or, \ +when the whole change does not fit one turn, what landed now and the \ +concrete plan for the rest." } } } -/// The agent's prompt for one dispatch: the persona framing (when the +/// The agent's prompt for one dispatch: the task framing (when the /// triage dispatched a role), the thread's standing state, the new news, /// and the posting contract. The final assistant message is the comment /// — everything else is orientation for the investigation. @@ -662,7 +708,7 @@ fn build_prompt( ) -> String { let mut prompt = String::new(); if let Some(role) = role { - prompt.push_str(persona_text(role)); + prompt.push_str(task_text(role)); prompt.push_str("\n\n"); } prompt.push_str(&format!( @@ -1084,8 +1130,12 @@ mod tests { Some(Role::Reviewer), ); assert!( - prompt.contains("acting as this pull request's reviewer"), - "persona: {prompt}" + prompt.contains("This dispatch is a review request"), + "task: {prompt}" + ); + assert!( + !prompt.contains("You are acting as"), + "who answers is the system prompt's to say, not the task text's: {prompt}" ); assert!( prompt.contains("notification (review_requested) on pull request #142"), @@ -1117,6 +1167,14 @@ mod tests { assert_eq!(final_text(&tool_only), None, "no text, no reply"); } + /// A throwaway bootstrap store: the persona renders from it, the + /// shape the daemon assembles over the configured directory. + fn bootstrap() -> (tempfile::TempDir, Arc) { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Bootstrap::new(dir.path().join("bootstrap")).expect("store opens"); + (dir, Arc::new(store)) + } + #[test] fn a_key_resolves_to_its_watch_entry_live_from_the_table() { let watches = Arc::new(ClawStore::in_memory().expect("store opens")); @@ -1133,11 +1191,13 @@ mod tests { ) .expect("constructs"), ); + let (_dir, bootstrap) = bootstrap(); let handler = ClawHandler::new( registry, "/tmp/w", watches, Arc::new(rhema_identity::VolatileIdentityStore::new()), + bootstrap, true, std::collections::BTreeMap::new(), ); @@ -1198,11 +1258,13 @@ mod tests { ) .expect("constructs"), ); + let (_dir, bootstrap) = bootstrap(); let handler = ClawHandler::new( registry, "/tmp/w", watches, accounts, + bootstrap, true, std::collections::BTreeMap::new(), ); @@ -1257,11 +1319,13 @@ mod tests { ); let accounts = Arc::new(rhema_identity::VolatileIdentityStore::new()); let provider = registry.current().0; + let (_dir, bootstrap) = bootstrap(); let on = ClawHandler::new( registry.clone(), "/tmp/w", watches.clone(), accounts.clone(), + bootstrap.clone(), true, std::collections::BTreeMap::new(), ); @@ -1270,18 +1334,144 @@ mod tests { "/tmp/w", watches, accounts, + bootstrap, false, std::collections::BTreeMap::new(), ); assert!( - on.agent_config(provider.clone(), "m", Path::new("/tmp/w")) - .transcript - .is_some() + on.agent_config( + provider.clone(), + "m", + Path::new("/tmp/w"), + "github:issue:acme/widgets#7" + ) + .expect("renders") + .transcript + .is_some() ); assert!( - off.agent_config(provider, "m", Path::new("/tmp/w")) - .transcript - .is_none() + off.agent_config( + provider, + "m", + Path::new("/tmp/w"), + "github:issue:acme/widgets#7" + ) + .expect("renders") + .transcript + .is_none() + ); + } + + #[test] + fn the_forge_dispatch_renders_the_residents_own_prompt() { + let watches = Arc::new(ClawStore::in_memory().expect("store opens")); + let registry = Arc::new( + crate::backends::BackendRegistry::new( + vec![crate::backends::Backend::headless( + "mock", + Arc::new(NoopProvider), + )], + None, + ) + .expect("constructs"), + ); + let (_dir, bootstrap) = bootstrap(); + bootstrap + .save( + crate::bootstrap::BootstrapKind::Soul, + "I am claw: terse, warm, relentless.", + ) + .expect("saves"); + let handler = ClawHandler::new( + registry, + "/tmp/w", + watches, + Arc::new(rhema_identity::VolatileIdentityStore::new()), + bootstrap, + true, + std::collections::BTreeMap::new(), + ); + let provider = handler.backends.current().0; + let config = handler + .agent_config( + provider, + "m", + Path::new("/tmp/w"), + "github:issue:acme/widgets#7", + ) + .expect("renders"); + let prompt = config.system.expect("the forge prompt is verbatim"); + assert!( + prompt.contains("I am claw: terse, warm, relentless."), + "the soul rides the forge prompt: {prompt}" + ); + assert!( + prompt.contains("the comment posted to the thread"), + "the forge branch of the reply contract: {prompt}" + ); + assert!( + !prompt.contains("You answer chat here"), + "not the chat branch: {prompt}" + ); + assert!( + prompt.contains("github:issue:acme/widgets#7"), + "the session key: {prompt}" + ); + assert!( + prompt.contains("- bash |"), + "the shell tool is documented: {prompt}" + ); + assert!( + prompt.contains("zoom"), + "the transcript view's tool is documented when the view is on: {prompt}" + ); + assert!( + !prompt.contains("## Memory"), + "no memory tools, no memory section: {prompt}" + ); + } + + #[test] + fn a_fresh_house_never_sends_a_forge_dispatch_onboarding() { + let watches = Arc::new(ClawStore::in_memory().expect("store opens")); + let registry = Arc::new( + crate::backends::BackendRegistry::new( + vec![crate::backends::Backend::headless( + "mock", + Arc::new(NoopProvider), + )], + None, + ) + .expect("constructs"), + ); + // No SOUL.md, no USER.md — the state where chat onboards. + let (_dir, bootstrap) = bootstrap(); + let handler = ClawHandler::new( + registry, + "/tmp/w", + watches, + Arc::new(rhema_identity::VolatileIdentityStore::new()), + bootstrap, + false, + std::collections::BTreeMap::new(), + ); + let provider = handler.backends.current().0; + let config = handler + .agent_config( + provider, + "m", + Path::new("/tmp/w"), + "github:issue:acme/widgets#7", + ) + .expect("renders"); + let prompt = config.system.expect("the forge prompt is verbatim"); + assert!( + !prompt.contains("## Onboarding"), + "a forge thread is nobody's first conversation: {prompt}" + ); + assert!( + prompt.contains("(pending onboarding)"), + "the stub says so honestly: {prompt}" ); } diff --git a/crates/rhema-claw/src/interactive.rs b/crates/rhema-claw/src/interactive.rs index 592d8c1..5959168 100644 --- a/crates/rhema-claw/src/interactive.rs +++ b/crates/rhema-claw/src/interactive.rs @@ -365,6 +365,8 @@ impl InteractiveHandler { &self.bootstrap, &resolver.specs(), vision, + &[], + crate::bootstrap::Surface::Chat, ) .map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?; Agent::builder() @@ -1390,6 +1392,8 @@ mod tests { &handler.bootstrap, &specs, None, + &[], + crate::bootstrap::Surface::Chat, ) .expect("renders"); assert!(