diff --git a/crates/rhema-claw/README.md b/crates/rhema-claw/README.md index 62aa826..61d9048 100644 --- a/crates/rhema-claw/README.md +++ b/crates/rhema-claw/README.md @@ -332,6 +332,10 @@ identity's when the token has one, and the forge's own `/user` answer when it does not; a credential the forge will not name leaves the gate open, with a warning in the log, rather than silently muting a watch. +A dispatch posts only when the turn calls `forge_comment`: a turn that +ends without it sends nothing, final message included. The tool is bound +to the thread, takes the comment body, and allows one comment per turn. + Acting with a stored account is `identity_exec`: it runs one shell command in the session workspace with the secret injected — `ACCOUNT_SECRET` plus the service's own `GITHUB_TOKEN`/`GITEA_TOKEN`/ diff --git a/crates/rhema-claw/SYSTEM.md b/crates/rhema-claw/SYSTEM.md index e6ad32b..94a1d79 100644 --- a/crates/rhema-claw/SYSTEM.md +++ b/crates/rhema-claw/SYSTEM.md @@ -2,10 +2,11 @@ You are the resident agent on this machine. This session's key is {{ session }}. 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. +You answer forge threads: review requests, assignments, and mentions on +the repositories you watch. Nothing is posted to the thread +automatically, and your final message stays in this session. Call +`forge_comment` once with the exact comment when the thread needs an +answer; send nothing when it does not. {% 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. diff --git a/crates/rhema-claw/src/bootstrap.rs b/crates/rhema-claw/src/bootstrap.rs index cb34952..67eabf9 100644 --- a/crates/rhema-claw/src/bootstrap.rs +++ b/crates/rhema-claw/src/bootstrap.rs @@ -491,7 +491,7 @@ mod tests { "a forge thread is nobody's first conversation: {prompt}" ); assert!( - prompt.contains("the comment posted to the thread"), + prompt.contains("Nothing is posted to the thread"), "the forge branch of the reply contract: {prompt}" ); assert!( diff --git a/crates/rhema-claw/src/forge_reply.rs b/crates/rhema-claw/src/forge_reply.rs new file mode 100644 index 0000000..18b8802 --- /dev/null +++ b/crates/rhema-claw/src/forge_reply.rs @@ -0,0 +1,135 @@ +//! The forge turn's outbound tool: `forge_comment`. +//! +//! A forge turn publishes nothing on its own. The final assistant message +//! stays in the session, and the thread hears from the daemon only when +//! the model calls this tool. The tool is bound to one thread at dispatch +//! time, so the model supplies the text and nothing else: it cannot post +//! to another repository, thread, or kind. +//! +//! One comment per turn is the agreed shape. The guard resets only when +//! the post itself failed, so a network error can be retried but a +//! successful comment cannot be posted twice by a model that calls the +//! tool again. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use async_trait::async_trait; +use rhema_core::{ReplaySafety, ToolSpec}; +use rhema_forge_integration::{Forge, ForgeThreadKind, RepoRef}; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::toolkit::{Tool, ToolError}; + +/// The tool's name, shared by its spec and the prompt's prose. +pub(crate) const NAME: &str = "forge_comment"; + +/// The thread this dispatch answers and the client that can post to it. +pub(crate) struct Target { + pub(crate) forge: Arc, + pub(crate) repo: RepoRef, + pub(crate) kind: ForgeThreadKind, + pub(crate) number: u64, +} + +impl Target { + /// The tool bound to this target. `thread` is the dispatch key, used + /// only in results and errors. + pub(crate) fn tool(&self, thread: &str) -> ForgeComment { + ForgeComment { + forge: self.forge.clone(), + repo: self.repo.clone(), + kind: self.kind, + number: self.number, + thread: thread.to_owned(), + posted: AtomicBool::new(false), + } + } +} + +/// The model-facing spec. The prompt lists it beside the shell tools, so +/// its wording is the contract the model reads. +pub(crate) fn spec() -> ToolSpec { + ToolSpec::new( + NAME, + "Post a comment on the forge thread this turn is answering. \ + Nothing is posted automatically, so this is the only way to reach \ + the thread. Call it once, after the investigation, with the exact \ + Markdown the thread's participants should read. If the new \ + activity needs no answer, do not call it; the turn can end with no \ + message.", + json!({ + "type": "object", + "properties": { + "body": { + "type": "string", + "description": "The comment text, Markdown, as it should appear on the thread." + } + }, + "required": ["body"], + "additionalProperties": false + }), + ) +} + +/// The tool: one thread, one comment. +pub(crate) struct ForgeComment { + forge: Arc, + repo: RepoRef, + kind: ForgeThreadKind, + number: u64, + thread: String, + posted: AtomicBool, +} + +#[derive(Deserialize)] +struct Args { + body: String, +} + +#[async_trait] +impl Tool for ForgeComment { + fn spec(&self) -> ToolSpec { + spec() + } + + fn replay_safety(&self) -> ReplaySafety { + // A replayed call could post a second comment. A committed call + // that lost its result stays interrupted. + ReplaySafety::Unsafe + } + + async fn invoke(&self, args: Value) -> Result { + let Args { body } = serde_json::from_value(args) + .map_err(|err| ToolError::new(format!("bad arguments: {err}")))?; + let body = body.trim(); + if body.is_empty() { + return Err(ToolError::new("`body` is empty; nothing was posted")); + } + if self.posted.swap(true, Ordering::SeqCst) { + return Err(ToolError::new(format!( + "a comment was already posted on {} this turn; one comment per turn", + self.thread + ))); + } + match self + .forge + .comment(&self.repo, self.kind, self.number, body) + .await + { + Ok(()) => Ok(json!({ + "posted": true, + "thread": self.thread, + }) + .to_string()), + Err(err) => { + self.posted.store(false, Ordering::SeqCst); + Err(ToolError::new(format!( + "comment on {} failed: {err}", + self.thread + ))) + } + } + } +} diff --git a/crates/rhema-claw/src/handler.rs b/crates/rhema-claw/src/handler.rs index e5e8200..1f98ef1 100644 --- a/crates/rhema-claw/src/handler.rs +++ b/crates/rhema-claw/src/handler.rs @@ -1,12 +1,14 @@ //! The handler: one dispatch of a forge thread becomes one coding-agent -//! turn, and the turn's final text becomes the thread's comment reply. +//! turn. Nothing is posted automatically; the agent reaches the thread by +//! calling the `forge_comment` tool, and a turn with no call sends no +//! message. //! //! The deterministic part stays ahead of the model (spec §1, §8): the //! watch's forge client is looked up by key, the snapshot is fetched, the //! inbox is drained and decoded, the allowlist is resolved — v1 is //! permissive, the spec's starting point, pending a real //! profile-to-permissions mapping — and only then does the agent run. -//! One turn per dispatch; the final assistant text posts verbatim. +//! One turn per dispatch; a comment is posted only when the agent asks. //! //! Session continuity rides the dispatcher, not the filesystem: the //! agent's session JSON is stashed into `ctx.session.core.driver_state` @@ -96,7 +98,7 @@ pub struct ClawHandler { sandbox: Option>, /// The abort registry the sessions' abort route signals: a live /// turn cut at its await stashes what it committed and ends the - /// dispatch as superseded, its comment never posted (see + /// dispatch as superseded; no later comment posts (see /// [`crate::abort`]). Private by default — a handler nobody shared /// a registry with never receives a signal — and shared through /// [`ClawHandler::with_abort`]. @@ -290,9 +292,9 @@ impl ClawHandler { .clone() } - /// One dispatch, failed with a reason on any step. The session stash - /// lands before the comment posts, so a failed post still leaves the - /// conversation resumable. + /// One dispatch, failed with a reason on any step. The commit hook + /// has already stored what the turn committed, so a turn that fails + /// after a comment still leaves the conversation resumable. async fn dispatch(&self, ctx: &mut SessionContext) -> Result { // Owned: the key names the run through every step, while `ctx` // itself goes mutable for the inbox drain. @@ -327,8 +329,8 @@ impl ClawHandler { .map_err(|err| format!("snapshot of {key} failed: {err}"))?; let role = dominant_role(&news); - // The permission check is load-bearing: this handler's one tool - // is the agent's shell, so a policy without it is a run that + // The permission check is load-bearing: every dispatch needs the + // shell to investigate, so a policy without it is a run that // could only flail — fail it loudly instead. let permissions = allowlist(); if !permissions.allows("bash") { @@ -338,7 +340,13 @@ impl ClawHandler { } let workspace = self.workspace_for(&key, &repo, number)?; - let mut agent = self.resume(ctx, &workspace, &key)?; + let target = crate::forge_reply::Target { + forge: forge.clone(), + repo: repo.clone(), + kind: thread_kind, + number, + }; + let mut agent = self.resume(ctx, &workspace, &key, &target)?; // Commit-before-execute: the intent is in the store before the // first tool runs; a lease that cannot be committed under fails // the step before any side effect. @@ -358,8 +366,10 @@ impl ClawHandler { } _ = abort.wait() => None, }; - let output = match turned { - Some(output) => output?, + match turned { + Some(output) => { + output?; + } None => { // Cut, not failed: the thread gets no half-answer, and // the session keeps whatever the turn committed. @@ -369,16 +379,11 @@ impl ClawHandler { } }; - // Stash before posting: the turn's work survives a failed comment. + // Stash after the turn: a comment already posted and the turn's + // work both survive a later failure. ctx.session.core.driver_state = serde_json::to_value(agent.session()) .map_err(|err| format!("session for {key} does not serialize: {err}"))?; - let reply = final_text(&output.message) - .ok_or_else(|| format!("the model returned no text to post for {key}"))?; - forge - .comment(&repo, thread_kind, number, &reply) - .await - .map_err(|err| format!("comment on {key} failed: {err}"))?; Ok(Outcome::Handled) } @@ -412,9 +417,10 @@ impl ClawHandler { ctx: &SessionContext, workspace: &Path, key: &str, + target: &crate::forge_reply::Target, ) -> Result { let (provider, model) = self.backends.current(); - let config = self.agent_config(provider, &model, workspace, key)?; + let config = self.agent_config(provider, &model, workspace, key, target)?; let agent = match &ctx.session.core.driver_state { // A never-dispatched key carries no stash: start clean. serde_json::Value::Null => HostAgent::new(config), @@ -440,6 +446,7 @@ impl ClawHandler { model: &str, workspace: &Path, key: &str, + target: &crate::forge_reply::Target, ) -> Result { let display = match &self.sandbox { Some(sandbox) => sandbox.workspace_for(workspace), @@ -479,6 +486,7 @@ impl ClawHandler { if config.transcript.is_some() { specs.push(rhema_transcript::Zoom::spec()); } + specs.push(crate::forge_reply::spec()); if let Some(catalog) = &self.subagents { specs.extend(catalog.specs(&display)); } @@ -511,6 +519,16 @@ impl ClawHandler { .as_ref() .map(|catalog| catalog.disabled().clone()) .unwrap_or_default(); + // The thread tool rides the config's extension slot. Subagents + // overlay it rather than replace it, so the agent keeps the one + // way it can reach the thread. + let mut registry = crate::toolkit::ToolRegistry::new(); + registry.register(Arc::new(target.tool(key))); + let reply = registry.resolver_for(&allowlist()); + config.extra_resolver = Some(match config.extra_resolver.take() { + Some(existing) => Arc::new(rhema_core::Overlay::new(existing, reply)), + None => reply, + }); if let Some(catalog) = &self.subagents { config.environment = self .bootstrap @@ -765,14 +783,14 @@ fn task_text(role: Role) -> &'static str { Role::Reviewer => { "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 — \ +edge cases, fit with the surrounding code. Make the comment 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 => { "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, \ +you change. Make the comment 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." } @@ -781,8 +799,9 @@ concrete plan for the rest." /// 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. +/// and the posting contract. The comment is a tool call, never the final +/// assistant message; everything else is orientation for the +/// investigation. fn build_prompt( key: &str, snapshot: &Snapshot, @@ -850,11 +869,14 @@ fn build_prompt( prompt.push_str(&format!( "\nThe workspace is at {}: investigate there with your shell tools (read\n\ code, run tests, reproduce reports) whenever the text alone does not\n\ - settle it. Your FINAL reply — the message you end the turn on, with\n\ - no tool calls after it — is posted to the thread verbatim: make it\n\ - the exact comment text for the thread's participants, with no\n\ - meta-commentary about this prompt.\n", + settle it. Nothing is posted to the thread automatically, and your\n\ + final message stays in this session. If the new activity needs an\n\ + answer, call `{}` once with the exact comment text for the thread's\n\ + participants, with no meta-commentary about this prompt. If it needs\n\ + no answer, send nothing and end the turn with a short private note\n\ + about what you found.\n", workspace.display(), + crate::forge_reply::NAME, )); prompt } @@ -902,9 +924,10 @@ pub(crate) fn final_text(message: &Message) -> Option { (!trimmed.is_empty()).then(|| trimmed.to_owned()) } -/// The turn's stderr log: tool traffic only. The reply is not streamed — -/// it is posted to the thread, and a daemon log line per tool call is the -/// observability a resident run gets. +/// The turn's stderr log: tool traffic only. The turn is not streamed — +/// a comment is posted by the `forge_comment` tool when the agent asks — +/// and a daemon log line per tool call is the observability a resident run +/// gets. struct TurnSink; impl EventSink for TurnSink { @@ -936,7 +959,59 @@ fn first_line(content: &str) -> String { mod tests { use super::*; use rhema_core::ModelProvider; - use rhema_forge_integration::{ForgeThreadKind, NotificationReason, resource_key}; + use rhema_forge_integration::{ + ForgePage, ForgeThreadKind, NotificationReason, Timestamp, resource_key, + }; + + /// A client no test dispatch posts through. The prompt tests only + /// need the target's shape; the wiremock tests exercise the post. + struct NoopForge; + + #[async_trait] + impl Forge for NoopForge { + async fn poll( + &self, + _repo: &RepoRef, + _since: Option<&Timestamp>, + ) -> Result { + Err(ForgeError::Network("unused in prompt tests".to_owned())) + } + + async fn comment( + &self, + _repo: &RepoRef, + _kind: ForgeThreadKind, + _number: u64, + _body: &str, + ) -> Result<(), ForgeError> { + Err(ForgeError::Network("unused in prompt tests".to_owned())) + } + + async fn snapshot( + &self, + _repo: &RepoRef, + _kind: ForgeThreadKind, + _number: u64, + ) -> Result { + Err(ForgeError::Network("unused in prompt tests".to_owned())) + } + + async fn notifications( + &self, + _since: Option<&Timestamp>, + ) -> Result { + Err(ForgeError::Network("unused in prompt tests".to_owned())) + } + } + + fn target() -> crate::forge_reply::Target { + crate::forge_reply::Target { + forge: Arc::new(NoopForge), + repo: RepoRef::new("acme", "widgets"), + kind: ForgeThreadKind::Issue, + number: 7, + } + } fn snapshot() -> Snapshot { serde_json::from_value(serde_json::json!({ @@ -993,9 +1068,13 @@ mod tests { "events: {prompt}" ); assert!( - prompt.contains("posted to the thread verbatim"), + prompt.contains("Nothing is posted to the thread"), "contract: {prompt}" ); + assert!( + prompt.contains("call `forge_comment` once"), + "the one way to post: {prompt}" + ); } /// A plain comment that names nobody is the thread's own traffic: the @@ -1427,7 +1506,8 @@ mod tests { provider.clone(), "m", Path::new("/tmp/w"), - "github:issue:acme/widgets#7" + "github:issue:acme/widgets#7", + &target(), ) .expect("renders") .transcript @@ -1438,7 +1518,8 @@ mod tests { provider, "m", Path::new("/tmp/w"), - "github:issue:acme/widgets#7" + "github:issue:acme/widgets#7", + &target(), ) .expect("renders") .transcript @@ -1482,6 +1563,7 @@ mod tests { "m", Path::new("/tmp/w"), "github:issue:acme/widgets#7", + &target(), ) .expect("renders"); let prompt = config.system.expect("the forge prompt is verbatim"); @@ -1490,7 +1572,7 @@ mod tests { "the soul rides the forge prompt: {prompt}" ); assert!( - prompt.contains("the comment posted to the thread"), + prompt.contains("Nothing is posted to the thread"), "the forge branch of the reply contract: {prompt}" ); assert!( @@ -1505,6 +1587,10 @@ mod tests { prompt.contains("- bash |"), "the shell tool is documented: {prompt}" ); + assert!( + prompt.contains("- forge_comment |"), + "the thread tool is documented: {prompt}" + ); assert!( prompt.contains("zoom"), "the transcript view's tool is documented when the view is on: {prompt}" @@ -1546,6 +1632,7 @@ mod tests { "m", Path::new("/tmp/w"), "github:issue:acme/widgets#7", + &target(), ) .expect("renders"); let prompt = config.system.expect("the forge prompt is verbatim"); diff --git a/crates/rhema-claw/src/lib.rs b/crates/rhema-claw/src/lib.rs index 5bb823d..80c408d 100644 --- a/crates/rhema-claw/src/lib.rs +++ b/crates/rhema-claw/src/lib.rs @@ -10,8 +10,8 @@ //! open interactive surface never resolves keys (§6.2) — one resident //! key is one owned session, forever. Two dispatchers share one SQLite //! store: the forge dispatcher turns watch activity into [`ClawHandler`] -//! runs (one turn per dispatch, the final text posted back as the -//! thread's comment); the resident dispatcher — keys prefixed +//! runs (one turn per dispatch, a comment only when the agent calls +//! `forge_comment`); the resident dispatcher — keys prefixed //! `interactive:`, `task:`, `phone:`, or `calendar:`, the contract //! [`interactive`] documents — turns chat messages, `/v1/ingest` //! events, due tasks, and due calendar reminders into @@ -59,8 +59,8 @@ //! boot pass all iterate it //! - [`forge`] — the sources: one detectable stream per forge kind //! - [`task_source`] — the [`TaskScheduler`]: due tasks in, events out -//! - [`handler`] — the forge dispatch: snapshot, inbox, one turn, one -//! comment +//! - [`handler`] — the forge dispatch: snapshot, inbox, one turn, a +//! comment only when the agent asks for one //! - [`interactive`] — the resident dispatch: the key-prefix contract, //! inbox, one turn, one streamed reply, auto-notify //! - [`steer`] — the interrupt registry: a chat message into a live @@ -85,6 +85,7 @@ pub mod daemon; pub mod environment; pub mod extension; pub mod forge; +mod forge_reply; pub mod git_identity; pub mod handler; pub mod http; diff --git a/crates/rhema-claw/tests/continuity.rs b/crates/rhema-claw/tests/continuity.rs index 3065bd7..072f535 100644 --- a/crates/rhema-claw/tests/continuity.rs +++ b/crates/rhema-claw/tests/continuity.rs @@ -30,7 +30,9 @@ fn seed_watch(dir: &tempfile::TempDir, host: &str) { ) .expect("the cursor seeds"); } -use rhema_core::{Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage}; +use rhema_core::{ + Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, ToolCall, Usage, +}; use rhema_rsd::{KeyState, Outcome, ResourceKey, SqliteStore, Store}; use serde_json::{Value, json}; use wiremock::matchers::{body_partial_json, method, path}; @@ -77,6 +79,24 @@ fn reply(text: &str) -> ModelOutput { } } +/// A turn that calls the one outbound forge tool. +fn comment_turn(body: &str) -> ModelOutput { + ModelOutput { + message: Message { + role: Role::Assistant, + content: vec![Content::ToolCall(ToolCall { + id: "call_1".into(), + name: "forge_comment".into(), + args: json!({ "body": body }), + provider_data: Value::Null, + })], + annotations: Default::default(), + }, + stop_reason: StopReason::ToolUse, + usage: Usage::default(), + } +} + fn config(dir: &tempfile::TempDir) -> ClawConfig { ClawConfig { db: Some(dir.path().join("dispatch.db")), @@ -161,7 +181,10 @@ async fn the_second_dispatch_resumes_the_first_conversation() { // a fresh watcher, the same db. let first = run_once( &config, - mock_registry(Arc::new(MockProvider::new([reply("on it")]))), + mock_registry(Arc::new(MockProvider::new([ + comment_turn("on it"), + reply("noted"), + ]))), ) .await .expect("the first pass runs"); @@ -173,7 +196,10 @@ async fn the_second_dispatch_resumes_the_first_conversation() { // decoded into one prompt for one resumed run. let second = run_once( &config, - mock_registry(Arc::new(MockProvider::new([reply("still on it")]))), + mock_registry(Arc::new(MockProvider::new([ + comment_turn("still on it"), + reply("noted again"), + ]))), ) .await .expect("the second pass runs"); @@ -230,7 +256,7 @@ async fn the_second_dispatch_resumes_the_first_conversation() { .collect(); assert_eq!( replies, - ["on it", "still on it"], + ["noted", "noted again"], "the conversation resumed" ); } diff --git a/crates/rhema-claw/tests/e2e.rs b/crates/rhema-claw/tests/e2e.rs index 5a0283c..8cbd256 100644 --- a/crates/rhema-claw/tests/e2e.rs +++ b/crates/rhema-claw/tests/e2e.rs @@ -1,12 +1,12 @@ //! Offline end-to-end: one `--once` pass over a wiremock GitHub — the -//! feed is polled, the MockProvider's reply lands as the thread's -//! comment, and the dispatch state persists in the SQLite db. Zero -//! network. +//! feed is polled, the MockProvider calls `forge_comment`, that call +//! lands as the thread's comment, and the dispatch state persists in the +//! SQLite db. Zero network. use std::sync::Arc; use rhema_claw::{ClawConfig, run_once}; -use rhema_core::{Message, MockProvider, ModelOutput, Role, StopReason, Usage}; +use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, StopReason, ToolCall, Usage}; use rhema_rsd::{ Dispatcher, DispatcherConfig, KeyState, Outcome, ResourceKey, SqliteStore, SystemClock, }; @@ -31,7 +31,7 @@ fn issue_row(updated_at: &str) -> Value { }) } -/// The scripted assistant turn: one text reply, nothing else. +/// A text turn: the final message, which is never posted on a forge. fn reply(text: &str) -> ModelOutput { ModelOutput { message: Message::text(Role::Assistant, text), @@ -40,6 +40,24 @@ fn reply(text: &str) -> ModelOutput { } } +/// A turn that calls the one outbound forge tool. +fn comment_turn(body: &str) -> ModelOutput { + ModelOutput { + message: Message { + role: Role::Assistant, + content: vec![Content::ToolCall(ToolCall { + id: "call_1".into(), + name: "forge_comment".into(), + args: json!({ "body": body }), + provider_data: Value::Null, + })], + annotations: Default::default(), + }, + stop_reason: StopReason::ToolUse, + usage: Usage::default(), + } +} + /// The test's claw config: everything under one tempdir, the watch aimed /// at the mock server. The provider never resolves through it — the /// daemon library takes the built provider, and the test builds a mock. @@ -114,8 +132,8 @@ async fn one_pass_polls_reasons_and_posts() { .respond_with(ResponseTemplate::new(200).set_body_json(issue_row("2026-10-02T10:00:00Z"))) .mount(&server) .await; - // The reply, counted: the assertion is that it posts exactly once - // with the mock's text. + // The comment, counted: the assertion is that the tool posts exactly + // once with the mock's text. let comment = Mock::given(method("POST")) .and(path("/repos/acme/widgets/issues/7/comments")) .and(body_partial_json(json!({ "body": "on it" }))) @@ -127,7 +145,7 @@ async fn one_pass_polls_reasons_and_posts() { let dir = tempfile::tempdir().expect("tempdir"); let config = config(&dir); seed_watch(&dir, &server.uri()); - let provider = Arc::new(MockProvider::new([reply("on it")])); + let provider = Arc::new(MockProvider::new([comment_turn("on it"), reply("done")])); let report = run_once(&config, mock_registry(provider)) .await .expect("the pass runs"); @@ -150,6 +168,47 @@ async fn one_pass_polls_reasons_and_posts() { assert_eq!(status.last_outcome, Some(Outcome::Handled)); } +/// The default: a turn that ends with text and never calls +/// `forge_comment` sends nothing. The final assistant message is not a +/// fallback comment. +#[tokio::test] +async fn a_turn_without_a_comment_tool_posts_nothing() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/repos/acme/widgets/issues")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!([issue_row("2026-10-02T10:00:00Z")])), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/repos/acme/widgets/issues/comments")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!([]))) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/repos/acme/widgets/issues/7")) + .respond_with(ResponseTemplate::new(200).set_body_json(issue_row("2026-10-02T10:00:00Z"))) + .mount(&server) + .await; + let comment = Mock::given(method("POST")) + .and(path("/repos/acme/widgets/issues/7/comments")) + .respond_with(ResponseTemplate::new(201).set_body_json(json!({ "id": 43 }))) + .expect(0) + .mount_as_scoped(&server) + .await; + + let dir = tempfile::tempdir().expect("tempdir"); + let config = config(&dir); + seed_watch(&dir, &server.uri()); + let provider = Arc::new(MockProvider::new([reply("nothing to add")])); + let report = run_once(&config, mock_registry(provider)) + .await + .expect("the pass runs"); + assert_eq!(report.outcomes, vec![Outcome::Handled]); + drop(comment); +} + /// A registry whose only backend is the scripted mock — the shape every /// integration test runs on. fn mock_registry(provider: Arc) -> Arc { diff --git a/crates/rhema-claw/tests/mention.rs b/crates/rhema-claw/tests/mention.rs index 1394f00..223c402 100644 --- a/crates/rhema-claw/tests/mention.rs +++ b/crates/rhema-claw/tests/mention.rs @@ -1,11 +1,12 @@ //! The mention gate, end to end: a comment that names the daemon runs a -//! turn and posts a reply; a comment that names nobody is drained and -//! ignored — no snapshot, no model call, no comment. Zero network. +//! turn that may post through `forge_comment`; a comment that names nobody +//! is drained and ignored — no snapshot, no model call, no comment. Zero +//! network. use std::sync::Arc; use rhema_claw::{ClawConfig, run_once}; -use rhema_core::{Message, MockProvider, ModelOutput, Role, StopReason, Usage}; +use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, StopReason, ToolCall, Usage}; use rhema_rsd::Outcome; use serde_json::{Value, json}; use wiremock::matchers::{body_partial_json, method, path}; @@ -50,6 +51,24 @@ fn reply(text: &str) -> ModelOutput { } } +/// A turn that calls the one outbound forge tool. +fn comment_turn(body: &str) -> ModelOutput { + ModelOutput { + message: Message { + role: Role::Assistant, + content: vec![Content::ToolCall(ToolCall { + id: "call_1".into(), + name: "forge_comment".into(), + args: json!({ "body": body }), + provider_data: Value::Null, + })], + annotations: Default::default(), + }, + stop_reason: StopReason::ToolUse, + usage: Usage::default(), + } +} + fn config(dir: &tempfile::TempDir) -> ClawConfig { ClawConfig { db: Some(dir.path().join("dispatch.db")), @@ -145,7 +164,10 @@ async fn a_comment_that_names_the_daemon_runs_a_turn() { seed_watch(&dir, &server.uri()); let report = run_once( &config(&dir), - mock_registry(Arc::new(MockProvider::new([reply("on it")]))), + mock_registry(Arc::new(MockProvider::new([ + comment_turn("on it"), + reply("done"), + ]))), ) .await .expect("the pass runs");