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::binding::ProjectBinding;
33use crate::jsonrpc::{ConnectionContext, Router, RpcError};
34use crate::session::SessionRegistry;
35use crate::workstreams::SharedWorkstreamStore;
36
37use super::executor::{TaskRunParams, spawn_task_run};
38use super::mock_llm::build_llm_client;
39
40/// Default top-level/PM agent name used when `task.run`'s `agent_name` param
41/// is omitted (#3437).
42///
43/// Why: #3437 — every GUI-initiated run omits `agent_name` (no agent-roster
44/// endpoint exists yet for the GUI to pick from), so [`task_run`]'s default
45/// MUST resolve against a real agent in every resolution tier (disk then
46/// embedded, see `agents::resolve_agent`) or 100% of daemon-default runs fail
47/// agent resolution before a single turn executes — exactly the failure mode
48/// #3437 traced. A shared `pub` const (referenced from both this call site
49/// and `assets::tests::default_task_run_agent_resolves_against_default_agents`)
50/// is the drift-guard: the literal here and the embedded roster entry it must
51/// resolve against can never independently rot out of sync the way two
52/// separately-typed `"pm"` string literals could.
53/// What: `"pm"` — must have a matching `EmbeddedAgent` entry in
54/// [`crate::assets::DEFAULT_AGENTS`] (see `assets/agents/pm.md`).
55/// Test: `task::protocol::tests::task_run_creates_session_when_none_given`
56/// (exercises the default through a real `task_run` call);
57/// `assets::tests::default_task_run_agent_resolves_against_default_agents`
58/// (pins that the literal resolves against the embedded roster).
59pub const DEFAULT_TASK_RUN_AGENT_NAME: &str = "pm";
60
61/// Register `task.run` onto `router`.
62///
63/// Why: the one place that wires the method, mirroring
64/// `session::protocol::register`'s role for `session.*`.
65/// What: closes over `registry`, `binding`, and `agents_dir` — all shared,
66/// cheap to clone (`Arc`/`PathBuf`) per call. `binding` replaces what was a
67/// REQUIRED `project: PathBuf`: a `PathBuf` cannot express "no project", so the
68/// projectless state the shell's entry screen renders was unreachable — the
69/// daemon could not be started, let alone run a task, without one. It is now a
70/// [`ProjectBinding`], whose `None` variant is that state.
71/// Test: `task::protocol::tests::register_wires_task_run`,
72/// `task::protocol::tests::register_wires_task_run_projectless`.
73/// (Issue #3298) `workstreams` is the daemon's shared workstream store —
74/// `task.run` resolves and persists a freshly-minted session's binding
75/// (explicit `workstream_id` param, or DOC-48 §4.2's ambient
76/// active-workstream default) through it, or enforces §4.1's immutability
77/// rule against an EXISTING session's persisted binding — see
78/// [`task_run`]'s docs.
79pub fn register(
80 router: &mut Router,
81 registry: Arc<SessionRegistry>,
82 binding: ProjectBinding,
83 agents_dir: PathBuf,
84 workstreams: SharedWorkstreamStore,
85) {
86 router.register("task.run", move |params: Value, _ctx: ConnectionContext| {
87 let registry = Arc::clone(®istry);
88 let binding = binding.clone();
89 let agents_dir = agents_dir.clone();
90 let workstreams = workstreams.clone();
91 async move { task_run(registry, params, binding, agents_dir, workstreams).await }
92 });
93}
94
95/// `task.run` request params (vision spec §4.3).
96#[derive(Deserialize)]
97struct TaskRunRequestParams {
98 task_description: String,
99 #[serde(default)]
100 agent_name: Option<String>,
101 /// Accepted for forward-compatibility; not yet injected into the
102 /// assembled prompt — see the module docs.
103 #[serde(default)]
104 #[allow(dead_code)]
105 context: Option<String>,
106 #[serde(default)]
107 model_override: Option<String>,
108 /// #2056 extension beyond the spec's literal example: when present,
109 /// runs against an EXISTING session (created via `session.create`)
110 /// instead of minting a fresh one — the spec's "sessionful" execution
111 /// mode.
112 #[serde(default)]
113 session_id: Option<String>,
114 /// #2059: per-call `HarnessMode` override (vision spec §5.9's tier-2
115 /// precedence source, above `.claude/settings.json` and below
116 /// `TRUSTY_CODE_MODE`). Leniently parsed by
117 /// `crate::mode::resolve_mode` — an unrecognised string here degrades
118 /// to "this source does not contribute", NOT a request error.
119 #[serde(default)]
120 mode: Option<String>,
121 /// #2207: per-call wall-clock deadline override, in seconds, applied to
122 /// BOTH the PM's own loop and the delegated engineer's loop. `None`
123 /// falls through to `crate::provider::resolve_deadline_secs`'s env-var
124 /// (`TCODE_RUN_DEADLINE_SECONDS`) and default (1800s) tiers.
125 #[serde(default)]
126 deadline_secs: Option<u64>,
127 /// #3178: per-call project override (DOC-39 §5.5, AC-16.2 convergence).
128 /// `None` preserves today's back-compat behaviour — the process-boot-time
129 /// `binding` `register` closed over. `Some(path)` is resolved through the
130 /// SAME [`ProjectBinding::resolve`] `session.create`'s `CreateParams.project`
131 /// uses (see `crate::session::protocol::create`'s docs), so a nonexistent
132 /// or non-directory path maps to `-32003 invalid_argument` identically on
133 /// both surfaces — this is the keystone convergence the issue names:
134 /// `task.run` and `session.create` can no longer disagree about what a
135 /// project is or how one is resolved.
136 ///
137 /// **Invariant when paired with `session_id` (reusing an existing
138 /// session):** a session's persisted `Session.binding` is authoritative —
139 /// `SessionRegistry` has no binding-update path (it is set once, in
140 /// `SessionRegistry::create`). `project` may only RESTATE that same root;
141 /// naming a DIFFERENT root is rejected with `-32003 invalid_argument`
142 /// rather than silently executing the run against a project
143 /// `session.status`/`session.list` would never agree it is bound to. See
144 /// [`task_run`]'s docs.
145 #[serde(default)]
146 project: Option<PathBuf>,
147 /// (Issue #3298, DOC-48 §4.1/§4.2) Explicit workstream to bind a
148 /// FRESHLY-MINTED session to (`session_id` absent), or to RESTATE an
149 /// existing reused session's own persisted binding — see
150 /// [`task_run`]'s docs on the immutability check this triggers on the
151 /// `session_id`-present path. `None` on the mint path falls back to
152 /// §4.2's ambient active-workstream default; `None` on the reuse path
153 /// never re-applies ambient targeting (a session's binding, once set, is
154 /// immutable — see `crate::workstreams::protocol::check_workstream_immutable`'s
155 /// docs).
156 #[serde(default)]
157 workstream_id: Option<String>,
158}
159
160/// `task.run(task_description, agent_name?, context?, model_override?,
161/// session_id?, mode?, deadline_secs?, project?, workstream_id?) -> {
162/// session_id, status, mode }`.
163///
164/// Why: the single entry point that turns a request into a running
165/// background execution.
166///
167/// **(Issue #3298, DOC-48 §4.1/§4.2) Workstream binding**, mirroring the
168/// `project`/binding reconciliation immediately below: on the mint path
169/// (`session_id` absent), resolves the EFFECTIVE workstream target —
170/// `workstream_id` explicit param wins, else the daemon's active workstream
171/// is the ambient default (§4.2), else the session stays projectless — and
172/// persists it via `crate::workstreams::protocol::resolve_validate_bind`
173/// (validated BEFORE the session is minted — see that helper's docs on the
174/// PR #3354 phantom-session fix)
175/// before this session is used further. On the reuse path (`session_id`
176/// present), the session's own persisted `workstream_id` is authoritative;
177/// `crate::workstreams::protocol::check_workstream_immutable` rejects a
178/// `workstream_id` param that would silently redirect a session
179/// `session.status`/`session.list` already reports as bound to a different
180/// (or no) workstream — same rule, same rationale as the `project` mismatch
181/// guard.
182/// What: validates `task_description` is non-empty
183/// (`-32003 invalid_argument`); resolves the EFFECTIVE binding for this call —
184/// `project: Some(path)` resolves via [`ProjectBinding::resolve`] (mapping a
185/// `BindingError` onto `-32003 invalid_argument`, exactly like
186/// `session.create`); `project: None` keeps the process-boot-time `binding`
187/// `register` closed over, so an existing caller that never sends `project`
188/// observes no change (#3178 back-compat). Then resolves the target session —
189/// an existing one by `session_id` (propagating `session_not_found` if it
190/// doesn't exist) or a freshly `session.create`d one bound to the effective
191/// binding; resolves the effective `HarnessMode` via `crate::mode::resolve_mode`
192/// (#2059's three-tier precedence, rooted at the effective binding) and
193/// persists it onto the session (`SessionRegistry::set_mode`) so it is
194/// queryable afterward via `session.status`/`session.list` (`Session.mode`)
195/// and `session.get_transcript` (`TranscriptRecord.mode`); builds the shared
196/// LLM client (real or the #2056 offline mock, per `TCODE_MOCK_LLM`); and
197/// calls `spawn_task_run`, which reserves the execution slot synchronously
198/// (rejecting a second overlapping run) before handing off to the background
199/// task. Returns immediately — the caller `session.attach`es to observe
200/// progress, per the ticket's "must not block the request thread on the whole
201/// LLM run" requirement. The response's own `mode`/`binding` fields are the
202/// SAME resolved values, surfaced immediately rather than requiring a
203/// follow-up `session.status` call.
204///
205/// **Invariant: a reused session's persisted binding is authoritative.** When
206/// `session_id` is supplied, `project` may only RESTATE that session's own
207/// `Session.binding` root (or be omitted); a `project` naming a DIFFERENT
208/// root is rejected as `-32003 invalid_argument` rather than silently
209/// executing the run against a project the session itself was never bound to
210/// (`SessionRegistry` has no binding-update path — `create` sets it once).
211/// Accepting the mismatch would let `session.status`/`session.list` report
212/// the ORIGINAL binding forever while the run actually executed against a
213/// different one — a silent audit/state divergence this validation exists to
214/// prevent (code-critic HIGH finding, PR #3189).
215/// Test: `task::protocol::tests::task_run_rejects_empty_task_description`,
216/// `task::protocol::tests::task_run_creates_session_when_none_given`,
217/// `task::protocol::tests::task_run_sessionful_reuses_existing_session`,
218/// `task::protocol::tests::task_run_unknown_session_id_errors`,
219/// `task::protocol::tests::task_run_resolves_and_reports_mode`,
220/// `task::protocol::tests::task_run_without_project_keeps_boot_binding`,
221/// `task::protocol::tests::task_run_with_project_overrides_boot_binding`,
222/// `task::protocol::tests::task_run_rejects_invalid_project`,
223/// `task::protocol::tests::task_run_session_id_with_matching_project_succeeds`,
224/// `task::protocol::tests::task_run_session_id_with_mismatched_project_is_rejected`.
225async fn task_run(
226 registry: Arc<SessionRegistry>,
227 params: Value,
228 binding: ProjectBinding,
229 agents_dir: PathBuf,
230 workstreams: SharedWorkstreamStore,
231) -> Result<Value, RpcError> {
232 let p: TaskRunRequestParams = serde_json::from_value(params)
233 .map_err(|e| RpcError::invalid_params(format!("task.run: {e}")))?;
234 if p.task_description.trim().is_empty() {
235 return Err(RpcError::invalid_argument(
236 "task_description must not be empty",
237 ));
238 }
239 // #3178: a per-call `project` overrides the boot-time binding for this
240 // call only, resolved through the exact same helper `session.create` uses
241 // — never a second, divergent implementation of "what is a project".
242 let project_given = p.project.is_some();
243 let binding = match p.project {
244 Some(project) => ProjectBinding::resolve(Some(project))
245 .map_err(|e| RpcError::invalid_argument(format!("task.run: {e}")))?,
246 None => binding,
247 };
248 let agent_name = p
249 .agent_name
250 .unwrap_or_else(|| DEFAULT_TASK_RUN_AGENT_NAME.to_string());
251
252 let session_id = match &p.session_id {
253 Some(id) => {
254 let existing = registry.status(id)?; // propagate session_not_found verbatim
255 // HIGH finding (code-critic, PR #3189): a session's persisted
256 // binding is authoritative once created — reject a per-call
257 // `project` that would silently redirect the run to a DIFFERENT
258 // root than `session.status`/`session.list` will keep reporting.
259 if project_given && existing.binding.root() != binding.root() {
260 return Err(RpcError::invalid_argument(format!(
261 "task.run: project `{}` does not match session `{id}`'s existing binding \
262 `{}` — a session's persisted binding is authoritative; project may only \
263 restate it, not change it",
264 binding
265 .label()
266 .unwrap_or_else(|| "<projectless>".to_string()),
267 existing
268 .binding
269 .label()
270 .unwrap_or_else(|| "<projectless>".to_string()),
271 )));
272 }
273 // (Issue #3298, DOC-48 §4.1 AC-1.3) A REUSED session's own
274 // persisted `workstream_id` is likewise authoritative — the
275 // exact same rule as the `project` check just above, applied to
276 // the sibling binding. `None` here never rejects: ambient
277 // default-targeting (§4.2) applies only at a session's FIRST
278 // binding, never re-applied on reuse.
279 crate::workstreams::protocol::check_workstream_immutable(
280 existing.workstream_id,
281 p.workstream_id.as_deref(),
282 "task.run",
283 )?;
284 id.clone()
285 }
286 None => {
287 // (PR #3354 code-critic HIGH 2) Validate the workstream target
288 // BEFORE minting: `SessionRegistry` has no delete/rollback, so
289 // a rejected bind (malformed/unknown/closed `workstream_id`)
290 // must fire while no session exists yet — the mint runs as a
291 // closure inside `resolve_validate_bind`, only after validation
292 // passes, under the same store lock (TOCTOU-free; see that
293 // helper's docs).
294 let (session_id, target) = crate::workstreams::protocol::resolve_validate_bind(
295 &workstreams,
296 p.workstream_id.as_deref(),
297 "task.run",
298 || {
299 registry
300 .create(
301 p.task_description.clone(),
302 Some(agent_name.clone()),
303 binding.clone(),
304 )
305 .id
306 },
307 )
308 .await?;
309 if let Some(ws_id) = target {
310 registry.bind_workstream(&session_id, ws_id)?;
311 }
312 session_id
313 }
314 };
315
316 let mode = crate::mode::resolve_mode(p.mode.as_deref(), binding.root());
317 registry.set_mode(&session_id, mode)?;
318
319 let llm = build_llm_client()?;
320 let task_params = TaskRunParams {
321 session_id: session_id.clone(),
322 task: p.task_description,
323 agent_name,
324 binding: binding.clone(),
325 agents_dir,
326 model_override: p.model_override,
327 mode,
328 deadline_secs: p.deadline_secs,
329 // #3902: no test-only override for this production call site.
330 telemetry_data_dir: None,
331 };
332 spawn_task_run(registry, llm, task_params)?;
333
334 Ok(json!({
335 "session_id": session_id,
336 "status": "running",
337 "mode": mode.as_str(),
338 "binding": binding.to_json(),
339 }))
340}
341
342#[cfg(test)]
343#[path = "protocol_tests.rs"]
344mod tests;