Skip to main content

trusty_code/task/
protocol.rs

1//! `task.run` JSON-RPC method (#2056, vision spec §4.3): start a
2//! session-driven task execution.
3//!
4//! Why: this is the API surface the M1 control-plane cut line needs — a
5//! caller creates (or targets an existing) session and asks the daemon to
6//! actually EXECUTE a task against it, asynchronously, streaming progress via
7//! the #2054/#2055 `session.attach` path. Kept as its own JSON-RPC method
8//! (rather than overloading `session.send`) because `session.send`'s
9//! existing #2054/#2055 contract — record an observable `SessionInput` event
10//! — is already tested and shipped; `task.run` is the deliberate, explicit
11//! "start executing" entry point the issue names.
12//! What: [`register`] wires `task.run` onto a [`Router`], sharing the SAME
13//! `Arc<SessionRegistry>` every `session.*` method uses. Params match the
14//! vision spec §4.3 example almost verbatim: `task_description`,
15//! `agent_name` (top-level/PM agent, default `"pm"`), `context` (accepted for
16//! forward-compatibility; not yet injected into the prompt — project
17//! `CLAUDE.md` context already flows through `run_task`'s existing
18//! machinery, and free-form per-call `context` injection is a smaller
19//! follow-up, not core to this cut line), `model_override` (pins the
20//! delegated ENGINEER's model for this run), and an ADDITIONAL optional
21//! `session_id` for "sessionful" execution against an already-`session.create`d
22//! session (the spec's "single-shot or sessionful" phrasing).
23//! Test: `task::protocol::tests::*`; the full flow end-to-end (a real
24//! subprocess) in `tests/task_e2e.rs`.
25
26use std::path::PathBuf;
27use std::sync::Arc;
28
29use serde::Deserialize;
30use serde_json::{Value, json};
31
32use crate::jsonrpc::{ConnectionContext, Router, RpcError};
33use crate::session::SessionRegistry;
34
35use super::executor::{TaskRunParams, spawn_task_run};
36use super::mock_llm::build_llm_client;
37
38/// Register `task.run` onto `router`.
39///
40/// Why: the one place that wires the method, mirroring
41/// `session::protocol::register`'s role for `session.*`.
42/// What: closes over `registry`, `project`, and `agents_dir` — all shared,
43/// cheap to clone (`Arc`/`PathBuf`) per call.
44/// Test: `task::protocol::tests::register_wires_task_run`.
45pub fn register(
46    router: &mut Router,
47    registry: Arc<SessionRegistry>,
48    project: PathBuf,
49    agents_dir: PathBuf,
50) {
51    router.register("task.run", move |params: Value, _ctx: ConnectionContext| {
52        let registry = Arc::clone(&registry);
53        let project = project.clone();
54        let agents_dir = agents_dir.clone();
55        async move { task_run(registry, params, project, agents_dir).await }
56    });
57}
58
59/// `task.run` request params (vision spec §4.3).
60#[derive(Deserialize)]
61struct TaskRunRequestParams {
62    task_description: String,
63    #[serde(default)]
64    agent_name: Option<String>,
65    /// Accepted for forward-compatibility; not yet injected into the
66    /// assembled prompt — see the module docs.
67    #[serde(default)]
68    #[allow(dead_code)]
69    context: Option<String>,
70    #[serde(default)]
71    model_override: Option<String>,
72    /// #2056 extension beyond the spec's literal example: when present,
73    /// runs against an EXISTING session (created via `session.create`)
74    /// instead of minting a fresh one — the spec's "sessionful" execution
75    /// mode.
76    #[serde(default)]
77    session_id: Option<String>,
78    /// #2059: per-call `HarnessMode` override (vision spec §5.9's tier-2
79    /// precedence source, above `.claude/settings.json` and below
80    /// `TRUSTY_CODE_MODE`). Leniently parsed by
81    /// `crate::mode::resolve_mode` — an unrecognised string here degrades
82    /// to "this source does not contribute", NOT a request error.
83    #[serde(default)]
84    mode: Option<String>,
85    /// #2207: per-call wall-clock deadline override, in seconds, applied to
86    /// BOTH the PM's own loop and the delegated engineer's loop. `None`
87    /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
88    /// (`TCODE_RUN_DEADLINE_SECONDS`) and default (1800s) tiers.
89    #[serde(default)]
90    deadline_secs: Option<u64>,
91}
92
93/// `task.run(task_description, agent_name?, context?, model_override?,
94/// session_id?, mode?, deadline_secs?) -> { session_id, status, mode }`.
95///
96/// Why: the single entry point that turns a request into a running
97/// background execution.
98/// What: validates `task_description` is non-empty
99/// (`-32003 invalid_argument`); resolves the target session — an existing
100/// one by `session_id` (propagating `session_not_found` if it doesn't
101/// exist) or a freshly `session.create`d one; resolves the effective
102/// `HarnessMode` via `crate::mode::resolve_mode` (#2059's three-tier
103/// precedence) and persists it onto the session (`SessionRegistry::set_mode`)
104/// so it is queryable afterward via `session.status`/`session.list`
105/// (`Session.mode`) and `session.get_transcript` (`TranscriptRecord.mode`);
106/// builds the shared LLM client (real or the #2056 offline mock, per
107/// `TCODE_MOCK_LLM`); and calls `spawn_task_run`, which reserves the
108/// execution slot synchronously (rejecting a second overlapping run) before
109/// handing off to the background task. Returns immediately — the caller
110/// `session.attach`es to observe progress, per the ticket's "must not block
111/// the request thread on the whole LLM run" requirement. The response's own
112/// `mode` field is the SAME resolved value, surfaced immediately rather than
113/// requiring a follow-up `session.status` call.
114/// Test: `task::protocol::tests::task_run_rejects_empty_task_description`,
115/// `task::protocol::tests::task_run_creates_session_when_none_given`,
116/// `task::protocol::tests::task_run_sessionful_reuses_existing_session`,
117/// `task::protocol::tests::task_run_unknown_session_id_errors`,
118/// `task::protocol::tests::task_run_resolves_and_reports_mode`.
119async fn task_run(
120    registry: Arc<SessionRegistry>,
121    params: Value,
122    project: PathBuf,
123    agents_dir: PathBuf,
124) -> Result<Value, RpcError> {
125    let p: TaskRunRequestParams = serde_json::from_value(params)
126        .map_err(|e| RpcError::invalid_params(format!("task.run: {e}")))?;
127    if p.task_description.trim().is_empty() {
128        return Err(RpcError::invalid_argument(
129            "task_description must not be empty",
130        ));
131    }
132    let agent_name = p.agent_name.unwrap_or_else(|| "pm".to_string());
133
134    let session_id = match &p.session_id {
135        Some(id) => {
136            registry.status(id)?; // propagate session_not_found verbatim
137            id.clone()
138        }
139        None => {
140            let session = registry.create(
141                p.task_description.clone(),
142                Some(agent_name.clone()),
143                Some(project.display().to_string()),
144            );
145            session.id
146        }
147    };
148
149    let mode = crate::mode::resolve_mode(p.mode.as_deref(), &project);
150    registry.set_mode(&session_id, mode)?;
151
152    let llm = build_llm_client()?;
153    let task_params = TaskRunParams {
154        session_id: session_id.clone(),
155        task: p.task_description,
156        agent_name,
157        project,
158        agents_dir,
159        model_override: p.model_override,
160        mode,
161        deadline_secs: p.deadline_secs,
162    };
163    spawn_task_run(registry, llm, task_params)?;
164
165    Ok(json!({ "session_id": session_id, "status": "running", "mode": mode.as_str() }))
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::jsonrpc::Request;
172    use tokio::sync::mpsc;
173
174    fn test_ctx() -> ConnectionContext {
175        let (tx, _rx) = mpsc::unbounded_channel();
176        ConnectionContext::new(tx)
177    }
178
179    fn agents_dir() -> tempfile::TempDir {
180        let tmp = tempfile::tempdir().expect("agents tempdir");
181        std::fs::write(
182            tmp.path().join("pm.toml"),
183            "[agent]\nname = \"pm\"\nmodel = \"openai/gpt-4o-mini\"\n[system_prompt]\ncontent = \"You are the PM.\"\n",
184        )
185        .expect("write pm.toml");
186        std::fs::write(
187            tmp.path().join("python-engineer.toml"),
188            "[agent]\nname = \"python-engineer\"\nmodel = \"deepseek/deepseek-chat\"\n[system_prompt]\ncontent = \"engineer\"\n",
189        )
190        .expect("write python-engineer.toml");
191        tmp
192    }
193
194    /// `register` must wire `task.run` so the router recognises it.
195    #[tokio::test]
196    async fn register_wires_task_run() {
197        let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
198        // SAFETY: test-only env mutation; serialized by `ENV_LOCK` above.
199        unsafe {
200            std::env::set_var(
201                super::super::mock_llm::MOCK_LLM_ENV,
202                super::super::mock_llm::MOCK_LLM_ECHO,
203            );
204        }
205        let registry = Arc::new(SessionRegistry::new());
206        let agents = agents_dir();
207        let project = tempfile::tempdir().expect("project tempdir");
208        let mut router = Router::new();
209        register(
210            &mut router,
211            registry,
212            project.path().to_path_buf(),
213            agents.path().to_path_buf(),
214        );
215
216        let req = Request {
217            jsonrpc: Some("2.0".to_string()),
218            id: Some(json!(1)),
219            method: "task.run".to_string(),
220            params: Some(json!({"task_description": "say hi"})),
221        };
222        let resp = router.dispatch(req, &test_ctx()).await;
223        unsafe {
224            std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
225        }
226        assert!(
227            resp.error.is_none(),
228            "task.run should succeed, got {:?}",
229            resp.error
230        );
231        assert_eq!(resp.result.unwrap()["status"], "running");
232    }
233
234    /// An empty `task_description` must map to `-32003 invalid_argument`.
235    #[tokio::test]
236    async fn task_run_rejects_empty_task_description() {
237        let registry = Arc::new(SessionRegistry::new());
238        let agents = agents_dir();
239        let project = tempfile::tempdir().expect("project tempdir");
240        let err = task_run(
241            registry,
242            json!({"task_description": "   "}),
243            project.path().to_path_buf(),
244            agents.path().to_path_buf(),
245        )
246        .await
247        .unwrap_err();
248        assert_eq!(err.code, -32003);
249    }
250
251    /// Omitting `session_id` must mint a fresh session.
252    #[tokio::test]
253    async fn task_run_creates_session_when_none_given() {
254        let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
255        unsafe {
256            std::env::set_var(
257                super::super::mock_llm::MOCK_LLM_ENV,
258                super::super::mock_llm::MOCK_LLM_ECHO,
259            );
260        }
261        let registry = Arc::new(SessionRegistry::new());
262        let agents = agents_dir();
263        let project = tempfile::tempdir().expect("project tempdir");
264
265        let result = task_run(
266            Arc::clone(&registry),
267            json!({"task_description": "say hi"}),
268            project.path().to_path_buf(),
269            agents.path().to_path_buf(),
270        )
271        .await;
272        unsafe {
273            std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
274        }
275        let value = result.expect("task.run should succeed");
276        let session_id = value["session_id"].as_str().expect("session_id string");
277        assert!(
278            registry.status(session_id).is_ok(),
279            "a new session must have been created"
280        );
281    }
282
283    /// `task.run` must resolve `HarnessMode` per §5.9's three-tier
284    /// precedence and report it BOTH in its own immediate response AND on
285    /// the session (queryable via `session.status`/`get_transcript`
286    /// afterward) — #2059.
287    ///
288    /// Why: this is the integration point proving the wiring
289    /// `crate::mode::resolve_mode`'s own unit tests cannot: that
290    /// `task::protocol::task_run` actually reads the `mode` request param,
291    /// the project's `.claude/settings.json`, and `TRUSTY_CODE_MODE`, in
292    /// that precedence, and persists the result via
293    /// `SessionRegistry::set_mode` before spawning the run.
294    /// What: covers default (nothing set), settings.json alone,
295    /// task-param-over-settings.json, and env-var-over-everything.
296    /// Test: this test.
297    #[tokio::test]
298    async fn task_run_resolves_and_reports_mode() {
299        let _mock_guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
300        let _mode_guard = crate::mode::MODE_ENV_LOCK.lock().await;
301        // SAFETY: test-only env mutation; serialized by both locks above.
302        unsafe {
303            std::env::set_var(
304                super::super::mock_llm::MOCK_LLM_ENV,
305                super::super::mock_llm::MOCK_LLM_ECHO,
306            );
307            std::env::remove_var(crate::mode::MODE_ENV_VAR);
308        }
309        let agents = agents_dir();
310
311        // 1. Nothing set anywhere -> default (daily-driver).
312        let project = tempfile::tempdir().expect("project tempdir");
313        let registry = Arc::new(SessionRegistry::new());
314        let value = task_run(
315            Arc::clone(&registry),
316            json!({"task_description": "say hi"}),
317            project.path().to_path_buf(),
318            agents.path().to_path_buf(),
319        )
320        .await
321        .expect("task.run should succeed");
322        assert_eq!(value["mode"], "daily-driver");
323        let session_id = value["session_id"].as_str().unwrap().to_string();
324        assert_eq!(
325            registry.status(&session_id).unwrap().mode,
326            Some(crate::mode::HarnessMode::DailyDriver)
327        );
328
329        // 2. `.claude/settings.json` alone sets parity.
330        let project2 = tempfile::tempdir().expect("project tempdir");
331        std::fs::create_dir_all(project2.path().join(".claude")).expect("mkdir");
332        std::fs::write(
333            project2.path().join(".claude").join("settings.json"),
334            r#"{"code_harness": {"mode": "parity"}}"#,
335        )
336        .expect("write settings.json");
337        let registry2 = Arc::new(SessionRegistry::new());
338        let value2 = task_run(
339            Arc::clone(&registry2),
340            json!({"task_description": "say hi"}),
341            project2.path().to_path_buf(),
342            agents.path().to_path_buf(),
343        )
344        .await
345        .expect("task.run should succeed");
346        assert_eq!(value2["mode"], "parity");
347
348        // 3. A `mode` request param overrides settings.json (still parity
349        //    from settings.json here, but requesting daily-driver must win).
350        let registry3 = Arc::new(SessionRegistry::new());
351        let value3 = task_run(
352            Arc::clone(&registry3),
353            json!({"task_description": "say hi", "mode": "daily-driver"}),
354            project2.path().to_path_buf(),
355            agents.path().to_path_buf(),
356        )
357        .await
358        .expect("task.run should succeed");
359        assert_eq!(
360            value3["mode"], "daily-driver",
361            "task.run's mode param must override settings.json"
362        );
363
364        // 4. TRUSTY_CODE_MODE overrides EVERYTHING, including a task param.
365        unsafe {
366            std::env::set_var(crate::mode::MODE_ENV_VAR, "parity");
367        }
368        let registry4 = Arc::new(SessionRegistry::new());
369        let value4 = task_run(
370            Arc::clone(&registry4),
371            json!({"task_description": "say hi", "mode": "daily-driver"}),
372            project2.path().to_path_buf(),
373            agents.path().to_path_buf(),
374        )
375        .await
376        .expect("task.run should succeed");
377        assert_eq!(
378            value4["mode"], "parity",
379            "TRUSTY_CODE_MODE must win over a task.run mode param"
380        );
381
382        unsafe {
383            std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
384            std::env::remove_var(crate::mode::MODE_ENV_VAR);
385        }
386    }
387
388    /// A `session_id` that does not exist must propagate `session_not_found`.
389    #[tokio::test]
390    async fn task_run_unknown_session_id_errors() {
391        let registry = Arc::new(SessionRegistry::new());
392        let agents = agents_dir();
393        let project = tempfile::tempdir().expect("project tempdir");
394
395        let err = task_run(
396            registry,
397            json!({"task_description": "say hi", "session_id": "does-not-exist"}),
398            project.path().to_path_buf(),
399            agents.path().to_path_buf(),
400        )
401        .await
402        .unwrap_err();
403        assert_eq!(err.code, -32007);
404    }
405
406    /// A `session_id` for an existing session must reuse it, not mint a new
407    /// one.
408    #[tokio::test]
409    async fn task_run_sessionful_reuses_existing_session() {
410        let _guard = super::super::mock_llm::MOCK_LLM_ENV_LOCK.lock().await;
411        unsafe {
412            std::env::set_var(
413                super::super::mock_llm::MOCK_LLM_ENV,
414                super::super::mock_llm::MOCK_LLM_ECHO,
415            );
416        }
417        let registry = Arc::new(SessionRegistry::new());
418        let existing = registry.create("say hi".to_string(), None, None);
419        let agents = agents_dir();
420        let project = tempfile::tempdir().expect("project tempdir");
421
422        let result = task_run(
423            Arc::clone(&registry),
424            json!({"task_description": "say hi", "session_id": existing.id}),
425            project.path().to_path_buf(),
426            agents.path().to_path_buf(),
427        )
428        .await;
429        unsafe {
430            std::env::remove_var(super::super::mock_llm::MOCK_LLM_ENV);
431        }
432        let value = result.expect("task.run should succeed");
433        assert_eq!(value["session_id"], existing.id);
434    }
435}