Skip to main content

speccoder_runtime/substrate/
attempt.rs

1//! `speccoder.task.attempt`: one bounded, governed attempt at a task
2//!.
3//!
4//! The model works through speccoder's tools; every call it asks for is
5//! classified by the policy first (deny → refused and told; approval → the
6//! attempt stops for a person; allow → dispatched through agentplane). The
7//! model's closing report is recorded as its claim — the verdict is computed
8//! afterwards by the verifier, never here.
9
10use crate::format::Wording;
11use agentplane::core::Label;
12use agentplane::model::{ToolDeclaration, Transcript};
13use agentplane::prelude::*;
14use agentplane::tools::ToolId;
15use serde_json::{Value, json};
16
17use super::model_config::{CacheTtl, PromptStyle};
18use super::propose::layout;
19use super::provenance;
20use crate::approvals::{Answer, Decision as Said, PresentContext, Request, Scope, Who};
21use crate::tools::policy::{Decision, Object, Policy};
22
23/// The capability the skill provides.
24pub const CAPABILITY: &str = "speccoder.task.attempt";
25
26/// The control tool for an honest exit. Handled by the skill, not
27/// dispatched anywhere.
28pub const REPORT_BLOCKED: &str = "report_blocked";
29
30/// What speccoder tells the model about an attempt; stable for the project.
31pub fn policy(w: &Wording) -> String {
32    format!(
33        "You are speccoder, a coding agent implementing exactly one {product} task in a git \
34worktree. Use the tools to inspect the code, make the smallest change that completes the \
35task, and run the project's checks with run_command to see whether it works. Stay inside \
36the task's scope. You cannot edit the spec ({intent}), the checks' configuration or \
37.git; such calls are refused. Some commands need a person's approval and will end the \
38attempt — prefer configured checks. If the task cannot be done as written — it \
39contradicts the spec, needs information or access you lack, or a test is wrong — call \
40report_blocked with the reason instead of working around it. Test files that existed \
41when the attempt started are frozen: add new tests in new files (or next to the code), \
42never by editing those. Never weaken, skip or delete tests to make checks pass. Never \
43return values copied from tests or examples in place of the specified behaviour (a \
44constant where the spec asks for a computed, fetched or current value is a cheat): if \
45the specified behaviour is impossible under the stated constraints, call report_blocked. \
46You are not the judge: when you finish, speccoder runs the checks itself and decides. \
47Finish with the requested structured report.",
48        product = w.product,
49        intent = w.intent_paths,
50    )
51}
52
53/// The final report's schema (the model's claim).
54#[must_use]
55pub fn report_schema() -> Value {
56    let strings = json!({ "type": "array", "items": { "type": "string" } });
57    json!({
58        "type": "object",
59        "properties": {
60            "summary": { "type": "string" },
61            "status": { "type": "string", "enum": ["done", "incomplete"] },
62            "files_changed": strings,
63            "checks_run": strings,
64            "notes": strings,
65        },
66        "required": ["summary", "status", "files_changed", "checks_run", "notes"],
67        "additionalProperties": false,
68    })
69}
70
71fn report_blocked() -> ToolDeclaration {
72    ToolDeclaration::new(
73        REPORT_BLOCKED,
74        "Stop the attempt because the task cannot be done as written; a person will look at the reason.",
75        json!({
76            "type": "object",
77            "properties": { "reason": { "type": "string" } },
78            "required": ["reason"],
79            "additionalProperties": false,
80        }),
81    )
82}
83
84/// The question tool a hosted skill may use.
85pub const ASK_PERSON: &str = "ask_person";
86
87/// The `ask_person` declaration.
88#[must_use]
89pub fn ask_person() -> ToolDeclaration {
90    ToolDeclaration::new(
91        ASK_PERSON,
92        "Ask the person one question and wait for their answer. If nobody can answer, the reply says so.",
93        json!({
94            "type": "object",
95            "properties": { "question": { "type": "string" } },
96            "required": ["question"],
97            "additionalProperties": false,
98        }),
99    )
100}
101
102/// How an attempt waits for a person when a call needs one: on an
103/// agentplane human task the person decides — inline, from an editor, or
104/// later with `speccoder task approve` — while the run is suspended.
105#[derive(Debug, Clone)]
106pub struct Asker {
107    /// `feature/task`, shown to the person.
108    pub task: String,
109    /// The task's title.
110    pub task_title: String,
111    /// What the live run knows for the presentation.
112    pub context: PresentContext,
113    /// How long a call waits before it is denied as expired.
114    pub wait_secs: u64,
115}
116
117impl Asker {
118    /// The asker the journaled settings describe: `asks = "tasks"` waits on
119    /// a task; anything else (`"stop"`, a lane) stops the attempt instead.
120    #[must_use]
121    pub fn from_settings(
122        settings: &Value,
123        task: String,
124        task_title: String,
125        context: PresentContext,
126    ) -> Option<Self> {
127        (settings["asks"] == "tasks").then(|| Self {
128            task,
129            task_title,
130            context,
131            wait_secs: settings["wait_secs"].as_u64().unwrap_or(7 * 86_400),
132        })
133    }
134}
135
136/// Waits for a person's decision on `spec`, registering the `approval`
137/// obligation the first time: the run suspends until someone decides or the
138/// deadline passes. Journaled — replay reads the decision back.
139async fn wait_for_person(
140    cx: &mut StepCtx<'_>,
141    asker: &Asker,
142    obligation: &mut bool,
143    spec: &agentplane::core::TaskSpec,
144) -> Result<agentplane::core::Decision, SkillError> {
145    if !*obligation {
146        let minutes = u32::try_from(asker.wait_secs.div_ceil(60).max(1)).unwrap_or(u32::MAX);
147        cx.deadline(
148            crate::approvals::tasks::DEADLINE,
149            &agentplane::core::DeadlineSpec::minutes(minutes),
150            None,
151        )
152        .await?;
153        *obligation = true;
154    }
155    Ok(cx.task(spec).await?)
156}
157
158/// The coded skill.
159///
160/// Everything its decisions depend on — the bundle, the policy's command
161/// prefixes and the limits — arrives in the run's input, so it is journaled
162/// and strict replay needs no configuration. Only the prompt dialect
163/// is construction-time, and it is part of each model call's effect key.
164#[derive(Debug)]
165pub struct Attempt {
166    /// Prompt dialect.
167    pub style: PromptStyle,
168    /// Cache breakpoint lifetime.
169    pub cache_ttl: CacheTtl,
170    /// Where live progress goes; not journaled, `None` in replay.
171    pub progress: Option<std::sync::Arc<dyn crate::progress::Progress>>,
172    /// The project's spec format.
173    pub format: &'static dyn crate::format::Adapter,
174    /// The sandbox, as a person asked about a command is told; live only.
175    pub present: PresentContext,
176}
177
178/// The run input: `{ bundle, settings: { checks, allow, max_turns,
179/// max_tool_calls, frozen, … }, digest }` — `digest` is the verifier's
180/// account of the previous attempt, `null` on a first attempt.
181///
182/// Labelled by where each part came from: the bundle is the
183/// person's committed spec and plan (trusted); the digest quotes check
184/// output (`speccoder://verifier`); the settings list MCP tool descriptions
185/// (their servers).
186#[must_use]
187pub fn input(
188    bundle: Value,
189    settings: &Settings<'_>,
190    digest: Option<&Value>,
191    instructions: &[crate::instructions::Instruction],
192    test_layout: Option<&str>,
193) -> Tainted<Value> {
194    let digest = match digest.filter(|d| !d.is_null()) {
195        Some(d) => Tainted::with_label(d.clone(), provenance::from(provenance::VERIFIER)),
196        None => Tainted::trusted(Value::Null),
197    };
198    // Each MCP tool's description and schema are its server's words.
199    let mcp = Tainted::array(settings.mcp.iter().map(|t| {
200        Tainted::with_label(
201            serde_json::to_value(t).unwrap_or(Value::Null),
202            agentplane::core::Label::untrusted(provenance::tool(&t.server, &t.tool)),
203        )
204    }));
205    let trusted = |v: Value| Tainted::trusted(v);
206    let autopilot = settings.autopilot;
207    let settings = vec![
208        ("checks", trusted(json!(settings.checks))),
209        ("allow", trusted(json!(settings.allow))),
210        ("max_turns", trusted(json!(settings.max_turns))),
211        ("max_tool_calls", trusted(json!(settings.max_tool_calls))),
212        ("reasoning", trusted(json!(settings.reasoning))),
213        ("frozen", trusted(json!(settings.frozen))),
214        ("approved", trusted(json!(settings.approved))),
215        ("rejected", trusted(json!(settings.rejected))),
216        ("run_approved", trusted(json!(settings.run_approved))),
217        ("approved_once", trusted(json!(settings.approved_once))),
218        ("nudges", trusted(json!(settings.nudges))),
219        ("mcp", mcp),
220        ("root", trusted(json!(settings.root))),
221        (
222            "frozen_additions",
223            trusted(json!(settings.frozen_additions)),
224        ),
225        ("network_allow", trusted(json!(settings.network_allow))),
226        ("allow_prefix", trusted(json!(settings.allow_prefix))),
227        (
228            "network_allow_prefix",
229            trusted(json!(settings.network_allow_prefix)),
230        ),
231        ("run_id", trusted(json!(settings.run_id))),
232        ("asked", trusted(json!(settings.asked))),
233        ("budget", trusted(json!(settings.budget))),
234        ("prompts", trusted(json!(settings.prompts))),
235        ("asks", trusted(json!(settings.asks))),
236        ("wait_secs", trusted(json!(settings.wait_secs))),
237        ("in_place", trusted(json!(settings.in_place))),
238        ("hidden", trusted(json!(settings.hidden))),
239    ];
240    // Only an autopilot run carries the key: every other input reads as
241    // it was recorded before it existed.
242    let mut settings = settings;
243    if autopilot {
244        settings.push(("autopilot", trusted(json!(true))));
245    }
246    let settings = Tainted::object(settings);
247    Tainted::object([
248        ("bundle", Tainted::trusted(bundle)),
249        ("digest", digest),
250        ("settings", settings),
251        // The repository's text, as if the model had read the files itself;
252        // none is no text, and no label.
253        (
254            "instructions",
255            if instructions.is_empty() {
256                Tainted::trusted(json!([]))
257            } else {
258                Tainted::with_label(json!(instructions), provenance::from(provenance::WORKTREE))
259            },
260        ),
261        // The test layout speccoder detected from the checkout.
262        (
263            "test_layout",
264            match test_layout {
265                Some(t) => Tainted::with_label(json!(t), provenance::from(provenance::WORKTREE)),
266                None => Tainted::trusted(Value::Null),
267            },
268        ),
269    ])
270}
271
272/// A refusal speccoder composes about a call quotes it — the tool, path or
273/// command the model chose — so it carries the call's label; only
274/// constant replies are trusted.
275fn refusal(text: String, call: &agentplane::core::Label) -> Tainted<String> {
276    Tainted::with_label(text, call.clone())
277}
278
279/// The parts of an attempt's input its messages quote.
280const MESSAGE_PARTS: [&str; 7] = [
281    "/bundle",
282    "/instructions",
283    "/test_layout",
284    "/digest",
285    "/settings/nudges",
286    "/settings/rejected",
287    "/settings/mcp",
288];
289
290/// The label of the conversation part: the join of the labels the run was
291/// admitted with for the parts it quotes — read, never inferred. A part
292/// without a label of its own takes the whole input's (fails closed).
293fn conversation_label(input: &Tainted<Value>) -> agentplane::core::Label {
294    MESSAGE_PARTS
295        .iter()
296        .map(|p| input.label_at(p).unwrap_or_else(|| input.label()).clone())
297        .fold(agentplane::core::Label::trusted(), |acc, l| acc.join(&l))
298}
299
300/// What an attempt decides by, besides its bundle (all journaled).
301#[derive(Debug, Clone, Copy)]
302pub struct Settings<'a> {
303    /// Configured checks' argvs (their prefixes are allowed commands).
304    pub checks: &'a [Vec<String>],
305    /// Exact commands allowed (`[commands] allow`).
306    pub allow: &'a [Vec<String>],
307    /// Allowed command prefixes (`[commands] allow_prefix`).
308    pub allow_prefix: &'a [Vec<String>],
309    /// Model turns.
310    pub max_turns: u32,
311    /// Tool calls.
312    pub max_tool_calls: u32,
313    /// Ask for the model's reasoning summary on every turn.
314    pub reasoning: bool,
315    /// Test files frozen for this attempt.
316    pub frozen: &'a [String],
317    /// A person's approvals for this task, in this run.
318    pub approved: &'a [Object],
319    /// A person's rejections for this task.
320    pub rejected: &'a [crate::tools::policy::Rejection],
321    /// Objects a person approved for every task of this run.
322    pub run_approved: &'a [Object],
323    /// Objects a person approved for one call each (a call a lane stopped,
324    /// decided in its run's batch): this attempt may make each one time.
325    pub approved_once: &'a [Object],
326    /// A person's notes for this task (`nudge`).
327    pub nudges: &'a [String],
328    /// The project's MCP tools for this run.
329    pub mcp: &'a [crate::mcp::McpTool],
330    /// The worktree's absolute (canonical) path.
331    pub root: &'a str,
332    /// Frozen tests may gain lines without approval (`[tests] frozen`).
333    pub frozen_additions: bool,
334    /// How a call needing a person is handled: `"tasks"` (the attempt waits
335    /// on a human task) or `"stop"` (it ends `needs_approval`; lanes).
336    pub asks: &'a str,
337    /// How long a call waits for a person before it is denied as expired.
338    pub wait_secs: u64,
339    /// Exact commands that get the network (`[sandbox] network_allow`).
340    pub network_allow: &'a [Vec<String>],
341    /// Prefixes that get it (`[sandbox] network_allow_prefix`).
342    pub network_allow_prefix: &'a [Vec<String>],
343    /// The run the attempt belongs to.
344    pub run_id: &'a str,
345    /// Prompts the run has shown a person so far.
346    pub asked: u32,
347    /// `[approvals] budget`.
348    pub budget: u32,
349    /// A person is prompted inline (not `--no-prompt`).
350    pub prompts: bool,
351    /// An in-place attempt: git that moves the checkout is denied.
352    pub in_place: bool,
353    /// In place: what git ignored at the run's start, hidden from the tools.
354    pub hidden: &'a [String],
355    /// An autopilot run: a call that would ask is refused instead.
356    pub autopilot: bool,
357}
358
359/// The calls consecutive denials of which end an attempt.
360pub const MAX_CONSECUTIVE_DENIALS: u32 = 3;
361
362/// The digest as the model reads it: facts from the verifier only.
363fn digest_text(digest: &Value) -> String {
364    let mut out = format!(
365        "# Previous attempt\n\nAttempt {} at this task was verified by speccoder and FAILED. Its \
366changes were discarded; the worktree is back where that attempt started. You start fresh — use \
367these facts from the verifier, check them yourself, and do not repeat the mistake.\n",
368        digest["attempt"].as_u64().unwrap_or(1)
369    );
370    let strings = |v: &Value| -> Vec<String> {
371        v.as_array()
372            .map(|a| {
373                a.iter()
374                    .filter_map(|x| x.as_str().map(str::to_owned))
375                    .collect()
376            })
377            .unwrap_or_default()
378    };
379    let reasons = strings(&digest["reasons"]);
380    if !reasons.is_empty() {
381        out.push_str("\n## Verdict reasons\n\n");
382        for r in reasons {
383            out.push_str(&format!("- {r}\n"));
384        }
385    }
386    for c in digest["checks"].as_array().into_iter().flatten() {
387        out.push_str(&format!(
388            "\n## Check `{}` ({}): `{}`\n",
389            c["name"].as_str().unwrap_or_default(),
390            c["status"].as_str().unwrap_or_default(),
391            strings(&c["argv"]).join(" ")
392        ));
393        let tests = strings(&c["failing_tests"]);
394        if !tests.is_empty() {
395            out.push_str(&format!("\nFailing tests: {}\n", tests.join(", ")));
396        }
397        out.push_str(&format!(
398            "\n```text\n{}\n```\n",
399            c["excerpt"].as_str().unwrap_or_default()
400        ));
401    }
402    let uncollected = strings(&digest["uncollected"]);
403    if !uncollected.is_empty() {
404        out.push_str("\n## Tests that never ran\n\n");
405        for l in uncollected {
406            out.push_str(&format!("- {l}\n"));
407        }
408    }
409    let discarded = strings(&digest["discarded"]);
410    if !discarded.is_empty() {
411        out.push_str(&format!(
412            "\n## Files the discarded attempt changed\n\n{}\n",
413            discarded.join("\n")
414        ));
415    }
416    out
417}
418
419fn argvs(v: &Value) -> Vec<Vec<String>> {
420    v.as_array()
421        .map(|a| {
422            a.iter()
423                .map(|argv| {
424                    argv.as_array()
425                        .map(|p| {
426                            p.iter()
427                                .filter_map(|x| x.as_str().map(str::to_owned))
428                                .collect()
429                        })
430                        .unwrap_or_default()
431                })
432                .collect()
433        })
434        .unwrap_or_default()
435}
436
437/// A person's decisions of the journaled input at `key`: none when absent,
438/// an error when present and unreadable — never read as "no decisions",
439/// which would drop rejections.
440fn decisions_of<T: serde::de::DeserializeOwned>(
441    settings: &Value,
442    key: &str,
443) -> Result<Vec<T>, SkillError> {
444    match &settings[key] {
445        Value::Null => Ok(Vec::new()),
446        v => serde_json::from_value(v.clone())
447            .map_err(|e| SkillError::Input(format!("settings.{key}: {e}"))),
448    }
449}
450
451#[async_trait]
452impl Skill for Attempt {
453    fn descriptor(&self) -> SkillDescriptor {
454        SkillDescriptor::new("speccoder.task.attempt").provides(CAPABILITY)
455    }
456
457    async fn invoke(
458        &self,
459        cx: &mut StepCtx<'_>,
460        input: Tainted<Value>,
461    ) -> Result<Outcome, SkillError> {
462        let (ttl, style) = (self.cache_ttl, self.style);
463        let settings = input.peek()["settings"].clone();
464        let task_name = format!(
465            "{}/{}",
466            input.peek()["bundle"]["feature"]
467                .as_str()
468                .unwrap_or_default(),
469            input.peek()["bundle"]["task"]["id"]
470                .as_str()
471                .unwrap_or_default()
472        );
473        let frozen: Vec<String> = settings["frozen"]
474            .as_array()
475            .map(|a| {
476                a.iter()
477                    .filter_map(|v| v.as_str().map(str::to_owned))
478                    .collect()
479            })
480            .unwrap_or_default();
481        let approved: Vec<Object> = decisions_of(&settings, "approved")?;
482        let rejected: Vec<crate::tools::policy::Rejection> = decisions_of(&settings, "rejected")?;
483        let told = rejected.clone();
484        let mcp: Vec<crate::mcp::McpTool> =
485            serde_json::from_value(settings["mcp"].clone()).unwrap_or_default();
486        let policy = Policy::new(&argvs(&settings["checks"]), &argvs(&settings["allow"]))
487            .with_prefixes(argvs(&settings["allow_prefix"]))
488            .with_network_prefixes(argvs(&settings["network_allow_prefix"]))
489            .rules(self.format.rules())
490            .with_frozen(frozen)
491            .with_decisions(approved, rejected)
492            .with_mcp(mcp.iter().map(|t| (t.name.clone(), t.decision.clone())))
493            .with_network(argvs(&settings["network_allow"]))
494            .with_hidden(
495                serde_json::from_value::<Vec<String>>(settings["hidden"].clone())
496                    .unwrap_or_default(),
497            );
498        let policy = if settings["in_place"] == true {
499            policy.in_place()
500        } else {
501            policy
502        };
503        let policy = if settings["autopilot"] == true {
504            policy.autopilot()
505        } else {
506            policy
507        };
508        let max_turns = settings["max_turns"]
509            .as_u64()
510            .map_or(30, |n| u32::try_from(n).unwrap_or(u32::MAX))
511            .max(1);
512        let max_tool_calls = settings["max_tool_calls"]
513            .as_u64()
514            .map_or(100, |n| u32::try_from(n).unwrap_or(u32::MAX));
515        // Same stable prefix as `propose`, with the attempt policy in front;
516        // a retry's digest goes after it, so the cached prefix is shared.
517        let label = conversation_label(&input);
518        let raw = input.peek().clone();
519        let prompt = provenance::labelled_prompt(
520            {
521                let input = raw;
522                let mut p = layout(
523                    &input["bundle"],
524                    ttl,
525                    style,
526                    &self::policy(self.format.wording()),
527                    self.format,
528                );
529                let given: Vec<crate::instructions::Instruction> =
530                    serde_json::from_value(input["instructions"].clone()).unwrap_or_default();
531                if let Some(text) = crate::instructions::section(&given) {
532                    let (key, kind) = match style {
533                        PromptStyle::OpenAi => ("input", "input_text"),
534                        PromptStyle::Anthropic | PromptStyle::Chat => ("messages", "text"),
535                    };
536                    if let Some(content) = p[key][0]["content"].as_array_mut() {
537                        content.push(json!({ "type": kind, "text": text }));
538                    }
539                }
540                if let Some(text) = input["test_layout"].as_str().filter(|t| !t.is_empty()) {
541                    let (key, kind) = match style {
542                        PromptStyle::OpenAi => ("input", "input_text"),
543                        PromptStyle::Anthropic | PromptStyle::Chat => ("messages", "text"),
544                    };
545                    if let Some(content) = p[key][0]["content"].as_array_mut() {
546                        content.push(json!({ "type": kind, "text": text }));
547                    }
548                }
549                if !input["digest"].is_null() {
550                    let (key, kind) = match style {
551                        PromptStyle::OpenAi => ("input", "input_text"),
552                        PromptStyle::Anthropic | PromptStyle::Chat => ("messages", "text"),
553                    };
554                    if let Some(content) = p[key][0]["content"].as_array_mut() {
555                        content
556                            .push(json!({ "type": kind, "text": digest_text(&input["digest"]) }));
557                    }
558                }
559                // A person's notes for this task.
560                let notes: Vec<String> = input["settings"]["nudges"]
561                    .as_array()
562                    .map(|a| {
563                        a.iter()
564                            .filter_map(|n| n.as_str().map(|n| format!("- {n}")))
565                            .collect()
566                    })
567                    .unwrap_or_default();
568                if !notes.is_empty() {
569                    let (key, kind) = match style {
570                        PromptStyle::OpenAi => ("input", "input_text"),
571                        PromptStyle::Anthropic | PromptStyle::Chat => ("messages", "text"),
572                    };
573                    let text = format!("# Notes from a person\n\n{}\n", notes.join("\n"));
574                    if let Some(content) = p[key][0]["content"].as_array_mut() {
575                        content.push(json!({ "type": kind, "text": text }));
576                    }
577                }
578                // A person's rejections, so the model does not ask again.
579                if !told.is_empty() {
580                    let (key, kind) = match style {
581                        PromptStyle::OpenAi => ("input", "input_text"),
582                        PromptStyle::Anthropic | PromptStyle::Chat => ("messages", "text"),
583                    };
584                    let lines: Vec<String> = told
585                        .iter()
586                        .map(|r| format!("- {}: {}", r.object.describe(), r.reason))
587                        .collect();
588                    let text = format!(
589                        "# Rejected by a person\n\nThese calls were rejected for this task; find another way or call report_blocked:\n\n{}\n",
590                        lines.join("\n")
591                    );
592                    if let Some(content) = p[key][0]["content"].as_array_mut() {
593                        content.push(json!({ "type": kind, "text": text }));
594                    }
595                }
596                p
597            },
598            &label,
599        );
600        let mut tools = crate::tools::declarations();
601        tools.push(report_blocked());
602        // MCP tools the policy does not deny, as the journaled input lists them.
603        let routes: Vec<(String, String, String)> = mcp
604            .iter()
605            .filter(|t| t.decision != "deny")
606            .map(|t| (t.name.clone(), t.server.clone(), t.tool.clone()))
607            .collect();
608        tools.extend(mcp.iter().filter(|t| t.decision != "deny").map(|t| {
609            ToolDeclaration::new(t.name.clone(), t.description.clone(), t.schema.clone())
610        }));
611        // Journaled: whether this attempt asks inline decides its effects.
612        let ask = Asker::from_settings(
613            &settings,
614            task_name.clone(),
615            input.peek()["bundle"]["task"]["title"]
616                .as_str()
617                .unwrap_or_default()
618                .to_owned(),
619            PresentContext {
620                root: settings["root"].as_str().map(std::path::PathBuf::from),
621                ..self.present.clone()
622            },
623        );
624        let remembered: Vec<Object> = decisions_of(&settings, "run_approved")?;
625        let once: Vec<Object> = decisions_of(&settings, "approved_once")?;
626        // Untrusted text the prompt itself carries.
627        let mut parts = Vec::new();
628        let given: Vec<crate::instructions::Instruction> =
629            serde_json::from_value(input.peek()["instructions"].clone()).unwrap_or_default();
630        if let Some(text) = crate::instructions::section(&given) {
631            parts.push(crate::approvals::derived::Part {
632                from: provenance::WORKTREE.to_owned(),
633                turn: 0,
634                text,
635            });
636        }
637        if !input.peek()["digest"].is_null() {
638            parts.push(crate::approvals::derived::Part {
639                from: provenance::VERIFIER.to_owned(),
640                turn: 0,
641                text: crate::approvals::derived::text_of(&input.peek()["digest"]),
642            });
643        }
644        let number = |k: &str, d: u32| {
645            settings[k]
646                .as_u64()
647                .map_or(d, |n| u32::try_from(n).unwrap_or(u32::MAX))
648        };
649        tool_loop(
650            cx,
651            &prompt,
652            LoopSpec {
653                tools,
654                policy,
655                max_turns,
656                max_tool_calls,
657                reasoning: settings["reasoning"] == true,
658                schema: report_schema(),
659                routes,
660                root: settings["root"].as_str().map(str::to_owned),
661                frozen_additions: settings["frozen_additions"] == true,
662                ask,
663                run_approved: remembered,
664                once,
665                run: settings["run_id"].as_str().map(str::to_owned),
666                asking: Asking {
667                    asked: number("asked", 0),
668                    budget: number("budget", DEFAULT_BUDGET),
669                    prompts: settings["prompts"] == true,
670                },
671                parts,
672                mcp_digests: mcp
673                    .iter()
674                    .map(|t| (t.name.clone(), t.digest.clone()))
675                    .collect(),
676                observer: self.progress.clone().map(|p| {
677                    (
678                        task_name.rsplit('/').next().unwrap_or_default().to_owned(),
679                        p,
680                    )
681                }),
682                finish: |report| {
683                    // The model's own word that it did not finish is believed;
684                    // its word that it did is not (the verifier decides that).
685                    if report["status"] == "incomplete" {
686                        "incomplete"
687                    } else {
688                        "completed"
689                    }
690                },
691            },
692        )
693        .await
694    }
695}
696
697/// Turns an absolute `path` argument inside the workspace `root` into a
698/// workspace-relative one. Tools print absolute paths (Spec Kit's scripts
699/// do), and a model passes them on; outside the root a path stays as it is
700/// — and the policy refuses it.
701fn relativise(arguments: &mut Value, root: Option<&str>) {
702    let (Some(root), Some(path)) = (root, arguments.get("path").and_then(Value::as_str)) else {
703        return;
704    };
705    let root = root.trim_end_matches('/');
706    if let Some(rel) = path.strip_prefix(root).and_then(|r| r.strip_prefix('/')) {
707        let rel = if rel.is_empty() {
708            ".".to_owned()
709        } else {
710            rel.to_owned()
711        };
712        arguments["path"] = Value::String(rel);
713    }
714}
715
716/// Reports one logged tool call to whoever watches.
717fn emit(
718    observer: Option<&(String, std::sync::Arc<dyn crate::progress::Progress>)>,
719    turn: u32,
720    entry: &Value,
721) {
722    emit_with_tail(observer, turn, entry, Vec::new());
723}
724
725/// [`emit`] with the last lines of a failed command's output (live only,
726/// never journaled).
727fn emit_with_tail(
728    observer: Option<&(String, std::sync::Arc<dyn crate::progress::Progress>)>,
729    turn: u32,
730    entry: &Value,
731    tail: Vec<String>,
732) {
733    if let Some((task, p)) = observer {
734        let tool = entry["tool"].as_str().unwrap_or_default();
735        p.event(&crate::progress::Event::ToolCall {
736            task: task.clone(),
737            turn,
738            tool: tool.to_owned(),
739            target: crate::progress::target(tool, &entry["arguments"]),
740            decision: entry["decision"].as_str().unwrap_or_default().to_owned(),
741            ok: entry["ok"].as_bool(),
742            tail,
743        });
744    }
745}
746
747/// A person is needed for `asked`: the run tells whoever watches.
748fn needs_person(
749    observer: Option<&(String, std::sync::Arc<dyn crate::progress::Progress>)>,
750    asked: &agentplane::model::ToolCall,
751    object: Option<&Object>,
752) {
753    if let Some((task, p)) = observer {
754        let (tool, arguments) = (asked.name.as_str(), &asked.arguments);
755        let target = crate::progress::target(tool, arguments);
756        let what: String = format!("{tool} {target}")
757            .chars()
758            .filter(|c| !c.is_control())
759            .take(60)
760            .collect();
761        p.event(&crate::progress::Event::ApprovalRequested {
762            task: task.clone(),
763            call: asked.id.clone(),
764            tool: tool.to_owned(),
765            what,
766            class: object
767                .map(|o| o.class().as_str().to_owned())
768                .unwrap_or_default(),
769            object: object.map(Object::short).unwrap_or_default(),
770        });
771    }
772}
773
774/// A person decided `asked`: the run tells whoever watches.
775fn person_decided(
776    observer: Option<&(String, std::sync::Arc<dyn crate::progress::Progress>)>,
777    asked: &agentplane::model::ToolCall,
778    decision: &str,
779    scope: Option<&str>,
780    who: Option<&Who>,
781    object: Option<&Object>,
782) {
783    if let Some((task, p)) = observer {
784        p.event(&crate::progress::Event::ApprovalDecided {
785            task: task.clone(),
786            call: asked.id.clone(),
787            decision: decision.to_owned(),
788            scope: scope.map(str::to_owned),
789            by: who.map_or_else(|| "nobody (expired)".to_owned(), |w| w.name.clone()),
790            how: who.map_or_else(|| "expired".to_owned(), |w| w.basis.clone()),
791            class: object
792                .map(|o| o.class().as_str().to_owned())
793                .unwrap_or_default(),
794            object: object.map(Object::short).unwrap_or_default(),
795        });
796    }
797}
798
799/// What a call needing a person is asked by.
800struct Question<'a> {
801    asked: &'a agentplane::model::ToolCall,
802    reason: &'a str,
803    turn: u32,
804    said: &'a str,
805    asker: Option<&'a Asker>,
806    policy: &'a Policy,
807    object: Option<&'a Object>,
808    remembered: &'a [(Object, &'static str)],
809    parts: &'a [crate::approvals::derived::Part],
810    run: Option<&'a str>,
811}
812
813/// The journaled question for a call needing a person: its object, what
814/// changed since an approval of the same name, where its arguments were
815/// copied from, and the choices that leaves — all from journaled data.
816fn question(q: &Question<'_>) -> Request {
817    let (tool, arguments) = (q.asked.name.as_str(), &q.asked.arguments);
818    let kind = crate::approvals::kind_of(tool, arguments);
819    let risk = crate::approvals::risk(tool, q.reason);
820    // Always Allow commits an exact entry: judged without the network.
821    let always_risk = if kind == "network" {
822        let mut bare = arguments.clone();
823        if let Some(o) = bare.as_object_mut() {
824            o.remove("network");
825        }
826        match q.policy.base(tool, &bare) {
827            Decision::Allow => "low",
828            Decision::Approval(r) => crate::approvals::risk(tool, &r),
829            Decision::Deny(_) => "high",
830        }
831    } else {
832        risk
833    };
834    let (sources, more) = crate::approvals::derived::sources(tool, arguments, q.parts);
835    let changed = q.object.and_then(|o| {
836        q.remembered
837            .iter()
838            .map(|(r, _)| r)
839            .chain(q.policy.approved())
840            .find_map(|earlier| o.changed_from(earlier))
841    });
842    Request {
843        task: q.asker.map(|a| a.task.clone()).unwrap_or_default(),
844        task_title: q.asker.map(|a| a.task_title.clone()).unwrap_or_default(),
845        turn: q.turn,
846        tool: tool.to_owned(),
847        arguments: arguments.clone(),
848        kind: kind.to_owned(),
849        reason: q.reason.to_owned(),
850        object: q.object.cloned(),
851        changed,
852        risk: risk.to_owned(),
853        claim: crate::approvals::claim(q.said),
854        options: crate::approvals::options(
855            risk,
856            q.object.is_some(),
857            !sources.is_empty(),
858            kind,
859            always_risk,
860        ),
861        sources,
862        more,
863        run: q.run.map(str::to_owned),
864        asked: 0,
865        budget: 0,
866        batched: false,
867    }
868}
869
870/// What a governed tool loop offers the model and asks of it.
871pub(crate) struct LoopSpec {
872    /// The tools declared to the model; any other name is refused.
873    pub tools: Vec<ToolDeclaration>,
874    /// Classifies every call before dispatch.
875    pub policy: Policy,
876    /// Model turns.
877    pub max_turns: u32,
878    /// Tool calls.
879    pub max_tool_calls: u32,
880    /// Ask each turn for the model's reasoning summary.
881    pub reasoning: bool,
882    /// The closing answer's schema.
883    pub schema: Value,
884    /// Declared tools served elsewhere: (name, server, tool) — MCP.
885    pub routes: Vec<(String, String, String)>,
886    /// The workspace's absolute path, from the journaled input: absolute
887    /// paths inside it are made relative before the policy sees them.
888    pub root: Option<String>,
889    /// A write to a frozen test that only adds lines needs no approval.
890    pub frozen_additions: bool,
891    /// The status for a closing answer.
892    pub finish: fn(&Value) -> &'static str,
893    /// Ask a person instead of stopping when a call needs approval.
894    pub ask: Option<Asker>,
895    /// Objects a person approved for this run: allowed without asking.
896    pub run_approved: Vec<Object>,
897    /// Objects a person approved for one call each: the first call of
898    /// each is allowed without asking, later ones ask again.
899    pub once: Vec<Object>,
900    /// Live progress: the task ID and where to report.
901    pub observer: Option<(String, std::sync::Arc<dyn crate::progress::Progress>)>,
902    /// The run the attempt belongs to (`run-<secs>-<hex>`).
903    pub run: Option<String>,
904    /// How a run asks: its count so far, its budget and whether a person is
905    /// prompted at all.
906    pub asking: Asking,
907    /// Untrusted content the prompt carries (inlined worktree text, the
908    /// verifier's digest): what derived arguments are found in.
909    pub parts: Vec<crate::approvals::derived::Part>,
910    /// MCP tools' digests by model-facing name: their objects.
911    pub mcp_digests: std::collections::BTreeMap<String, String>,
912}
913
914/// A run's asking budget as an attempt sees it (all journaled).
915#[derive(Debug, Clone, Copy, PartialEq, Eq)]
916pub struct Asking {
917    /// Prompts shown to a person in the run so far.
918    pub asked: u32,
919    /// `[approvals] budget`: at most this many per run.
920    pub budget: u32,
921    /// A person is prompted inline; `false` with `--no-prompt` (calls wait
922    /// as ordinary approvals, nothing is counted).
923    pub prompts: bool,
924}
925
926impl Default for Asking {
927    fn default() -> Self {
928        Self {
929            asked: 0,
930            budget: DEFAULT_BUDGET,
931            prompts: false,
932        }
933    }
934}
935
936/// `[approvals] budget` unless configured.
937pub use super::run_config::DEFAULT_BUDGET;
938
939/// The governed tool loop shared by attempts and convergence: every call is
940/// classified first (deny → refused and told; approval → stop; allow →
941/// dispatched through agentplane); the closing structured answer ends it.
942pub(crate) async fn tool_loop(
943    cx: &mut StepCtx<'_>,
944    prompt: &Tainted<Value>,
945    spec: LoopSpec,
946) -> Result<Outcome, SkillError> {
947    let LoopSpec {
948        tools,
949        policy,
950        max_turns,
951        max_tool_calls,
952        reasoning,
953        schema,
954        routes,
955        root,
956        frozen_additions,
957        finish,
958        ask,
959        run_approved,
960        mut once,
961        observer,
962        run,
963        asking,
964        mut parts,
965        mcp_digests,
966    } = spec;
967    // Objects allowed without asking: this run's, then what a person
968    // answered "for the task" or "for this run" in this attempt.
969    let mut remembered: Vec<(Object, &'static str)> =
970        run_approved.into_iter().map(|g| (g, "run-grant")).collect();
971    let mut prompted = asking.asked;
972    let mut told_budget = false;
973    let catalog = crate::tools::catalog();
974
975    // What the conversation has read, with its labels: agentplane checks
976    // every model call against the join.
977    let mut transcript = Transcript::new(prompt);
978    let mut conversation: Label = prompt.label().clone();
979    let mut calls = 0u32;
980    let mut denied_in_a_row = 0u32;
981    // Whether this attempt registered the `approval` obligation yet.
982    let mut obligation = false;
983    let mut usage = agentplane::model::Usage::default();
984    let mut log: Vec<Value> = Vec::new();
985
986    let end = |status: &str,
987               extra: Value,
988               log: &[Value],
989               usage: agentplane::model::Usage,
990               conversation: &Label,
991               prompted: u32| {
992        let mut out = json!({
993            "status": status,
994            "tool_calls": log,
995            "asked": prompted,
996            "usage": {
997                "input_tokens": usage.input_tokens,
998                "output_tokens": usage.output_tokens,
999                "cache_read_tokens": usage.cache_read_tokens,
1000                "cache_write_tokens": usage.cache_write_tokens,
1001            },
1002        });
1003        if let (Some(o), Some(e)) = (out.as_object_mut(), extra.as_object()) {
1004            o.extend(e.clone());
1005        }
1006        Ok(Outcome::done(Tainted::with_label(
1007            out,
1008            conversation.clone(),
1009        )))
1010    };
1011
1012    for turn in 0..max_turns {
1013        // The prompt was built from labelled parts (`/system` is speccoder's
1014        // constant instruction); what the conversation read since rides in
1015        // the transcript, so the request is labelled by its real sources.
1016        let tools_now = tools.clone();
1017        let schema_now = schema.clone();
1018        let read_so_far = &transcript;
1019        let completion = cx
1020            .complete_with(prompt, move |call| {
1021                let call = call
1022                    .with_tools(tools_now)
1023                    .continuing(read_so_far)
1024                    .expecting(schema_now);
1025                if reasoning {
1026                    call.with_reasoning_summary()
1027                } else {
1028                    call
1029                }
1030            })
1031            .await?;
1032        conversation = transcript.label().join(completion.label());
1033        usage = usage.plus(completion.peek().usage);
1034        if let Some((task, p)) = &observer {
1035            p.event(&crate::progress::Event::Usage {
1036                task: task.clone(),
1037                input_tokens: usage.input_tokens,
1038                output_tokens: usage.output_tokens,
1039                cache_read_tokens: usage.cache_read_tokens,
1040                cache_write_tokens: usage.cache_write_tokens,
1041                usd: None,
1042            });
1043        }
1044
1045        // The model's summary of its reasoning, when asked and given: its
1046        // account of why, a claim like its words.
1047        if let (Some((task, p)), Some(reasoning)) =
1048            (&observer, completion.peek().reasoning.as_deref())
1049            && !reasoning.trim().is_empty()
1050        {
1051            let text: String = crate::approvals::present::escape(reasoning.trim())
1052                .chars()
1053                .take(4000)
1054                .collect();
1055            p.event(&crate::progress::Event::Reasoning {
1056                task: task.clone(),
1057                turn: turn + 1,
1058                text,
1059            });
1060        }
1061        if completion.peek().truncated {
1062            return Ok(Outcome::fail(
1063                "the model ran out of output budget mid-turn; nothing it was still writing was executed — raise [model] max_output_tokens",
1064            ));
1065        }
1066        let asked_calls = transcript.asked(&completion);
1067        // The model's own words beside its calls, live: its account, a
1068        // claim. A turn without calls is its final answer, reported as such;
1069        // its commentary, where the provider marks one, is still words.
1070        let said = super::said(completion.peek());
1071        if let (Some((task, p)), Some(said)) = (observer.as_ref(), said.as_deref()) {
1072            let text: String = crate::approvals::present::escape(said)
1073                .chars()
1074                .take(2000)
1075                .collect();
1076            p.event(&crate::progress::Event::Said {
1077                task: task.clone(),
1078                turn: turn + 1,
1079                text,
1080            });
1081        }
1082        if asked_calls.is_empty() {
1083            let report = completion
1084                .peek()
1085                .structured
1086                .clone()
1087                .unwrap_or_else(|| json!({ "summary": completion.peek().text, "status": "incomplete", "files_changed": [], "checks_run": [], "notes": ["the answer was not the requested structure"] }));
1088            let status = finish(&report);
1089            return end(
1090                status,
1091                json!({ "report": report }),
1092                &log,
1093                usage,
1094                &conversation,
1095                prompted,
1096            );
1097        }
1098
1099        for mut asked in asked_calls {
1100            relativise(&mut asked.arguments, root.as_deref());
1101            // Only speccoder sets the object a call is checked against.
1102            if let Some(o) = asked.arguments.as_object_mut() {
1103                o.remove(crate::tools::EXPECT);
1104            }
1105            calls += 1;
1106            if calls > max_tool_calls {
1107                return end(
1108                    "budget_exhausted",
1109                    json!({ "reason": format!("more than {max_tool_calls} tool calls") }),
1110                    &log,
1111                    usage,
1112                    &conversation,
1113                    prompted,
1114                );
1115            }
1116            if asked.name == ASK_PERSON && tools.iter().any(|t| t.name == ASK_PERSON) {
1117                let question = asked.arguments["question"]
1118                    .as_str()
1119                    .unwrap_or_default()
1120                    .to_owned();
1121                // A person's answer is their input, recorded with who gave it
1122                // — never speccoder's own trusted text.
1123                let decided = match &ask {
1124                    Some(asker) => Some(
1125                        wait_for_person(
1126                            cx,
1127                            asker,
1128                            &mut obligation,
1129                            &crate::approvals::tasks::question_task(&asker.task, &question),
1130                        )
1131                        .await?,
1132                    ),
1133                    None => None,
1134                };
1135                let read = decided.as_ref().map(crate::approvals::tasks::read);
1136                let by = read.as_ref().and_then(|r| r.by.clone());
1137                let entry = json!({
1138                    "tool": ASK_PERSON,
1139                    "arguments": asked.arguments,
1140                    "decision": "allow",
1141                    "answered": read.as_ref().is_some_and(|r| r.text.is_some()),
1142                    "operator": by.as_ref().map(Who::view),
1143                    "via": by.as_ref().map(|w| w.via.clone()),
1144                });
1145                emit(observer.as_ref(), turn + 1, &entry);
1146                log.push(entry);
1147                let text = match (&read, &by) {
1148                    (Some(r), _) if r.text.is_some() => r.text.clone().unwrap_or_default(),
1149                    (Some(_), Some(w)) => format!("{} declined to answer.", w.name),
1150                    _ => "Nobody can answer now. Record the question in the artifact as [NEEDS CLARIFICATION: <question>] and continue.".to_owned(),
1151                };
1152                let label = match &by {
1153                    Some(_) => provenance::from(provenance::PERSON),
1154                    None => Label::trusted(),
1155                };
1156                transcript.answered(
1157                    asked,
1158                    &Tainted::with_label(json!({ "answer": text }), label),
1159                );
1160                continue;
1161            }
1162            if asked.name == REPORT_BLOCKED && tools.iter().any(|t| t.name == REPORT_BLOCKED) {
1163                let reason = asked.arguments["reason"]
1164                    .as_str()
1165                    .unwrap_or("no reason given")
1166                    .to_owned();
1167                let entry = json!({ "tool": REPORT_BLOCKED, "arguments": asked.arguments, "decision": "stop" });
1168                emit(observer.as_ref(), turn + 1, &entry);
1169                log.push(entry);
1170                return end(
1171                    "blocked",
1172                    json!({ "reason": reason }),
1173                    &log,
1174                    usage,
1175                    &conversation,
1176                    prompted,
1177                );
1178            }
1179            let declared = tools.iter().any(|t| t.name == asked.name);
1180            let target = catalog
1181                .iter()
1182                .find(|t| declared && t.name == asked.name)
1183                .map(|t| ToolId::new(t.server, t.name))
1184                .or_else(|| {
1185                    routes
1186                        .iter()
1187                        .find(|(n, _, _)| declared && *n == asked.name)
1188                        .map(|(_, server, tool)| ToolId::new(server, tool))
1189                });
1190            let Some(target) = target else {
1191                let entry = json!({ "tool": asked.name, "arguments": asked.arguments, "decision": "unknown" });
1192                emit(observer.as_ref(), turn + 1, &entry);
1193                log.push(entry);
1194                transcript.failed(asked, Tainted::trusted("no tool of that name".to_owned()));
1195                continue;
1196            };
1197            let mut decision = policy.base(&asked.name, &asked.arguments);
1198            // `[tests] frozen = "additions"`: read the frozen test (a
1199            // journaled call, so replay sees the same content) and allow a
1200            // write that keeps every existing line.
1201            let mut additions_only = false;
1202            if frozen_additions
1203                && matches!(&decision, Decision::Approval(r) if r.contains("frozen test"))
1204            {
1205                let path = asked.arguments["path"]
1206                    .as_str()
1207                    .unwrap_or_default()
1208                    .to_owned();
1209                let read = cx
1210                    .call_tool(
1211                        ToolId::new("fs", "read_file"),
1212                        Tainted::with_label(json!({ "path": path }), completion.label().clone()),
1213                    )
1214                    .await?;
1215                let current = read.peek().clone();
1216                // `read_file` joins lines with `\n`; the file's last newline is
1217                // restored so an edit's `old_string` matches as on disk.
1218                let lines = current["content"].as_str().unwrap_or_default();
1219                let old_text = if lines.is_empty() {
1220                    String::new()
1221                } else {
1222                    format!("{lines}\n")
1223                };
1224                let old = old_text.as_str();
1225                let readable = current["ok"] == true && current["truncated"] != true;
1226                let new = match asked.name.as_str() {
1227                    "write_file" => asked.arguments["content"].as_str().map(str::to_owned),
1228                    "edit_file" => {
1229                        let (from, to) = (
1230                            asked.arguments["old_string"].as_str().unwrap_or_default(),
1231                            asked.arguments["new_string"].as_str().unwrap_or_default(),
1232                        );
1233                        let all = asked.arguments["replace_all"] == true;
1234                        (!from.is_empty() && (all || old.matches(from).count() == 1))
1235                            .then(|| old.replace(from, to))
1236                    }
1237                    _ => None,
1238                };
1239                if readable && new.is_some_and(|n| crate::integrity::only_additions(old, &n)) {
1240                    decision = Decision::Allow;
1241                    additions_only = true;
1242                }
1243            }
1244            // A person would be needed: the object the call reaches is
1245            // resolved by a journaled step (replay reads the same object
1246            // back), and only a decision on that very object applies.
1247            let mut object: Option<Object> = None;
1248            if matches!(decision, Decision::Approval(_)) {
1249                if asked.name.starts_with(crate::mcp::PREFIX) {
1250                    object = mcp_digests.get(&asked.name).map(|digest| Object::Tool {
1251                        name: asked.name.clone(),
1252                        digest: digest.clone(),
1253                    });
1254                } else {
1255                    let resolved = cx
1256                        .call_tool(
1257                            ToolId::new("fs", "resolve"),
1258                            Tainted::with_label(
1259                                json!({ "tool": asked.name, "arguments": asked.arguments }),
1260                                completion.label().clone(),
1261                            ),
1262                        )
1263                        .await?;
1264                    let out = resolved.peek();
1265                    if out["ok"] == true {
1266                        object = serde_json::from_value(out["object"].clone()).ok();
1267                    } else {
1268                        decision = Decision::Deny(
1269                            out["error"]
1270                                .as_str()
1271                                .unwrap_or("the call's object cannot be resolved")
1272                                .to_owned(),
1273                        );
1274                    }
1275                }
1276                if matches!(decision, Decision::Approval(_)) {
1277                    decision = policy.classify(&asked.name, &asked.arguments, object.as_ref());
1278                }
1279            }
1280            let mut person: Option<Value> = None;
1281            // Allowed by a person's grant for the task (of this run): the
1282            // person's decision, not a rule's.
1283            if decision == Decision::Allow && object.is_some() {
1284                person = Some(json!({
1285                    "approved_by": "person",
1286                    "scope": "task-grant",
1287                    "grant": { "scope": "task", "run": run },
1288                }));
1289            }
1290            let mut note: Option<String> = None;
1291            // An object a person approved for one call: this one.
1292            if matches!(decision, Decision::Approval(_))
1293                && let Some(at) = object
1294                    .as_ref()
1295                    .and_then(|o| once.iter().position(|r| r == o))
1296            {
1297                once.remove(at);
1298                person = Some(json!({
1299                    "approved_by": "person",
1300                    "scope": "once-grant",
1301                    "grant": { "scope": "once", "run": run },
1302                }));
1303                decision = Decision::Allow;
1304            }
1305            // An object a person already approved for this run or task.
1306            if matches!(decision, Decision::Approval(_))
1307                && let Some((_, scope)) = object
1308                    .as_ref()
1309                    .and_then(|o| remembered.iter().find(|(r, _)| r == o))
1310            {
1311                person = Some(json!({
1312                    "approved_by": "person",
1313                    "scope": scope,
1314                    "grant": { "scope": scope.trim_end_matches("-grant"), "run": run },
1315                }));
1316                decision = Decision::Allow;
1317            }
1318            // On autopilot nobody is asked: what would wait for a person is
1319            // refused for the run and listed for them afterwards.
1320            decision = policy.settle(decision);
1321            // Still a person's: the question, with everything it is decided by.
1322            let request = match &decision {
1323                Decision::Approval(reason) => Some(question(&Question {
1324                    asked: &asked,
1325                    reason,
1326                    turn: turn + 1,
1327                    said: said.as_deref().unwrap_or_default(),
1328                    asker: ask.as_ref(),
1329                    policy: &policy,
1330                    object: object.as_ref(),
1331                    remembered: &remembered,
1332                    parts: &parts,
1333                    run: run.as_deref(),
1334                })),
1335                _ => None,
1336            };
1337            // ask a person now, as a journaled effect, instead of stopping.
1338            if let (Some(mut request), Some(asker)) = (request.clone(), &ask) {
1339                // The run's asking budget: within it a person is prompted
1340                // (and counted, whatever they answer); past it the call
1341                // waits in the run's batch, nobody interrupted.
1342                if asking.prompts {
1343                    if prompted < asking.budget {
1344                        prompted += 1;
1345                        request.asked = prompted;
1346                    } else {
1347                        request.batched = true;
1348                    }
1349                    request.budget = asking.budget;
1350                }
1351                if request.batched {
1352                    // The batch item is created: the person is notified
1353                    // once; calls joining it notify no one.
1354                    if !told_budget {
1355                        needs_person(observer.as_ref(), &asked, object.as_ref());
1356                    }
1357                    if !told_budget && let Some((_, p)) = &observer {
1358                        p.event(&crate::progress::Event::Notice {
1359                            text: format!(
1360                                "approval budget ({}) reached: calls wait in Needs You (speccoder approvals)",
1361                                asking.budget
1362                            ),
1363                        });
1364                    }
1365                    told_budget = true;
1366                } else {
1367                    needs_person(observer.as_ref(), &asked, object.as_ref());
1368                }
1369                let decided = wait_for_person(
1370                    cx,
1371                    asker,
1372                    &mut obligation,
1373                    &crate::approvals::tasks::approval_task(&request, &log),
1374                )
1375                .await?;
1376                let read = crate::approvals::tasks::read(&decided);
1377                // A batch decision may start the run's asking again.
1378                if read.resume_asking {
1379                    prompted = 0;
1380                }
1381                let answer: Answer = read.answer.clone();
1382                // Who decided, and how that is known, is journaled with it.
1383                let approver = serde_json::to_value(&answer.by).unwrap_or(Value::Null);
1384                let operator = read.by.as_ref().map(Who::view);
1385                person_decided(
1386                    observer.as_ref(),
1387                    &asked,
1388                    if answer.decision == Said::Approve {
1389                        "approve"
1390                    } else {
1391                        "reject"
1392                    },
1393                    (answer.decision == Said::Approve).then(|| answer.scope.name()),
1394                    read.by.as_ref().filter(|_| !read.expired),
1395                    object.as_ref(),
1396                );
1397                match answer.decision {
1398                    Said::Approve => {
1399                        let mut p = json!({
1400                            "approved_by": "person",
1401                            "scope": answer.scope.name(),
1402                            "note": answer.note,
1403                            "approver": approver,
1404                            "operator": operator,
1405                        });
1406                        if answer.always {
1407                            p["always"] = json!(true);
1408                        }
1409                        if let (Some(o), Scope::Task | Scope::Run) = (&object, answer.scope) {
1410                            let remembered_as = if answer.scope == Scope::Run {
1411                                "run-grant"
1412                            } else {
1413                                "task-grant"
1414                            };
1415                            p["grant"] = json!({ "scope": answer.scope.name(), "run": run });
1416                            remembered.push((o.clone(), remembered_as));
1417                        }
1418                        person = Some(p);
1419                        note = answer.note;
1420                        decision = Decision::Allow;
1421                    }
1422                    // "Later" is a task left undecided: the run stays
1423                    // suspended and never reaches here.
1424                    Said::Reject | Said::Stop => {
1425                        let why = answer
1426                            .reason
1427                            .unwrap_or_else(|| "no reason given".to_owned());
1428                        person = Some(if read.expired {
1429                            json!({ "expired": true, "rejection": why })
1430                        } else {
1431                            json!({ "rejected_by": "person", "approver": approver, "operator": operator, "rejection": why })
1432                        });
1433                        decision = Decision::Deny(format!("a person rejected this: {why}"));
1434                    }
1435                }
1436            }
1437            // Who decided: a person (now, or by a grant they gave), or a rule
1438            // — named, so a rule's decision is never read as a person's.
1439            let rule = person
1440                .is_none()
1441                .then(|| policy.rule(&asked.name, &asked.arguments, object.as_ref()));
1442            let with_person = |mut entry: Value| {
1443                if let Some(o) = entry.as_object_mut() {
1444                    // The object decided on, whoever decided.
1445                    if let Some(obj) = &object {
1446                        o.insert("object".to_owned(), json!(obj));
1447                    }
1448                    match (person.as_ref().and_then(Value::as_object), &rule) {
1449                        (Some(p), _) => {
1450                            // An expiry is nobody's decision.
1451                            let by = if p.contains_key("expired") {
1452                                "expiry"
1453                            } else {
1454                                "person"
1455                            };
1456                            o.insert("by".to_owned(), json!(by));
1457                            o.extend(p.clone());
1458                        }
1459                        (None, Some(r)) => {
1460                            o.insert("by".to_owned(), json!("rule"));
1461                            o.insert("rule".to_owned(), json!(r));
1462                        }
1463                        (None, None) => {}
1464                    }
1465                }
1466                entry
1467            };
1468            match decision {
1469                Decision::Deny(reason) => {
1470                    let entry = with_person(
1471                        json!({ "tool": asked.name, "arguments": asked.arguments, "decision": "deny", "reason": reason }),
1472                    );
1473                    emit(observer.as_ref(), turn + 1, &entry);
1474                    log.push(entry);
1475                    // The reason quotes the call (its tool, path, command, or a
1476                    // person's words about it): it carries the call's label.
1477                    transcript.failed(
1478                        asked,
1479                        refusal(format!("denied: {reason}"), completion.label()),
1480                    );
1481                    // Escalation: a model that keeps asking for what it may
1482                    // not do is stopped for a person.
1483                    denied_in_a_row += 1;
1484                    if denied_in_a_row >= MAX_CONSECUTIVE_DENIALS {
1485                        return end(
1486                            "denied",
1487                            json!({ "reason": format!("{denied_in_a_row} calls in a row were denied; last: {reason}") }),
1488                            &log,
1489                            usage,
1490                            &conversation,
1491                            prompted,
1492                        );
1493                    }
1494                    continue;
1495                }
1496                Decision::Approval(reason) => {
1497                    let mut entry = json!({ "tool": asked.name, "arguments": asked.arguments, "decision": "approval", "reason": reason });
1498                    if let Some(obj) = &object {
1499                        entry["object"] = json!(obj);
1500                    }
1501                    emit(observer.as_ref(), turn + 1, &entry);
1502                    needs_person(observer.as_ref(), &asked, object.as_ref());
1503                    log.push(entry);
1504                    return end(
1505                        "needs_approval",
1506                        json!({ "pending": {
1507                            "tool": asked.name,
1508                            "arguments": asked.arguments,
1509                            "reason": reason,
1510                            "object": object,
1511                            "run": run,
1512                            "request": request,
1513                        } }),
1514                        &log,
1515                        usage,
1516                        &conversation,
1517                        prompted,
1518                    );
1519                }
1520                Decision::Allow => {
1521                    denied_in_a_row = 0;
1522                    // The arguments carry the model's label: agentplane's
1523                    // taint gate checks them against the grant's fields (an
1524                    // argument-less mutating tool is granted exactly `{}`).
1525                    // A command gets the call's id (`SPECCODER_CALL_ID`):
1526                    // a call resumed after a crash has the same one, so a
1527                    // script can tell a repeat from a new call.
1528                    let mut arguments = asked.arguments.clone();
1529                    if asked.name == "run_command"
1530                        && let Some(o) = arguments.as_object_mut()
1531                    {
1532                        o.insert("call_id".to_owned(), Value::String(asked.id.clone()));
1533                    }
1534                    // Decided on an object: the tool checks it again at
1535                    // use, and refuses when the call now reaches another.
1536                    if let (Some(obj), Some(o)) = (&object, arguments.as_object_mut())
1537                        && matches!(
1538                            asked.name.as_str(),
1539                            "write_file" | "edit_file" | "run_command"
1540                        )
1541                    {
1542                        o.insert(crate::tools::EXPECT.to_owned(), json!(obj));
1543                    }
1544                    let args = Tainted::with_label(arguments, completion.label().clone());
1545                    let result = match cx.call_tool(target.clone(), args).await {
1546                        Ok(r) => r,
1547                        // A failure the far side reported is the model's to
1548                        // read, labelled by who wrote it.
1549                        Err(error) => match cx.relayed(&error) {
1550                            Some(detail) => {
1551                                let entry = with_person(
1552                                    json!({ "tool": asked.name, "arguments": asked.arguments, "decision": "allow", "ok": false }),
1553                                );
1554                                emit(observer.as_ref(), turn + 1, &entry);
1555                                log.push(entry);
1556                                transcript.failed(asked, detail);
1557                                continue;
1558                            }
1559                            None => return Err(error.into()),
1560                        },
1561                    };
1562                    let output = result.peek().clone();
1563                    let ok = output["ok"].as_bool() != Some(false);
1564                    let mut entry = with_person(
1565                        json!({ "tool": asked.name, "arguments": asked.arguments, "decision": "allow", "ok": ok }),
1566                    );
1567                    if let Some(changed) = output["object_changed"].as_object() {
1568                        entry["decision"] = json!("refused_changed");
1569                        entry["expected"] = changed.get("expected").cloned().unwrap_or(Value::Null);
1570                        entry["found"] = changed.get("found").cloned().unwrap_or(Value::Null);
1571                    }
1572                    // What the tool returned is content the attempt read:
1573                    // arguments copied from it later are named as such.
1574                    if let Some(part) = crate::approvals::derived::part_of(
1575                        &asked.name,
1576                        &asked.arguments,
1577                        &output,
1578                        turn + 1,
1579                        &format!("tool://{}/{}", target.server, target.tool),
1580                        |p: &str| {
1581                            policy.protected().write_class(p)
1582                                == Some(crate::tools::paths::Class::Intent)
1583                        },
1584                    ) {
1585                        parts.push(part);
1586                    }
1587                    if additions_only {
1588                        entry["frozen_additions"] = json!(true);
1589                    }
1590                    let tail = if asked.name == "run_command" && !ok {
1591                        crate::progress::tail(&format!(
1592                            "{}\n{}",
1593                            output["stdout"].as_str().unwrap_or_default(),
1594                            output["stderr"].as_str().unwrap_or_default()
1595                        ))
1596                    } else {
1597                        Vec::new()
1598                    };
1599                    emit_with_tail(observer.as_ref(), turn + 1, &entry, tail);
1600                    log.push(entry);
1601                    // A command that changed a judge input ends the attempt
1602                    // before the model sees another turn.
1603                    if let Some(drift) = output["integrity"].as_array().filter(|d| !d.is_empty()) {
1604                        let paths: Vec<&str> =
1605                            drift.iter().filter_map(|d| d["path"].as_str()).collect();
1606                        return end(
1607                            "integrity",
1608                            json!({
1609                                "reason": format!("a command changed what judges the task: {}", paths.join(", ")),
1610                                "integrity": drift,
1611                            }),
1612                            &log,
1613                            usage,
1614                            &conversation,
1615                            prompted,
1616                        );
1617                    }
1618                    // A tool that refused (`error`) is a failed call; a
1619                    // command that ran and exited non-zero is a result the
1620                    // model must read in full — its stdout and stderr are
1621                    // the diagnostics (found by the first real evaluation,
1622                    // where the model saw only the word "failed").
1623                    match output["error"].as_str() {
1624                        Some(error) if !ok => transcript.failed(
1625                            asked,
1626                            Tainted::with_label(error.to_owned(), result.label().clone()),
1627                        ),
1628                        // A person's note rides with the result it approved.
1629                        _ => match &note {
1630                            Some(n) => {
1631                                let n = format!("Note from the person who approved this call: {n}");
1632                                transcript.answered(
1633                                    asked,
1634                                    &result.map(|mut v| {
1635                                        v["note_from_person"] = Value::String(n);
1636                                        v
1637                                    }),
1638                                );
1639                            }
1640                            None => transcript.answered(asked, &result),
1641                        },
1642                    }
1643                }
1644            }
1645        }
1646    }
1647    end(
1648        "budget_exhausted",
1649        json!({ "reason": format!("more than {max_turns} model turns") }),
1650        &log,
1651        usage,
1652        &conversation,
1653        prompted,
1654    )
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659    use super::*;
1660
1661    #[test]
1662    fn labels_are_read_from_the_parts_and_refusals_carry_the_call() {
1663        use agentplane::core::{Label, SourceId};
1664        let model = Label::untrusted(SourceId::new("model:x/y"));
1665        // A refusal quoting the call is the call's; a constant is trusted.
1666        assert!(
1667            refusal("denied: `src/x` is protected".to_owned(), &model)
1668                .label()
1669                .is_untrusted()
1670        );
1671        // Parts labelled when admitted: the spec trusted, the digest the verifier's.
1672        let input = Tainted::object([
1673            ("bundle", Tainted::trusted(json!({}))),
1674            (
1675                "digest",
1676                Tainted::with_label(json!({}), provenance::from(provenance::VERIFIER)),
1677            ),
1678            (
1679                "settings",
1680                Tainted::object([("nudges", Tainted::trusted(json!([])))]),
1681            ),
1682        ]);
1683        let label = conversation_label(&input);
1684        assert!(
1685            label
1686                .provenance
1687                .contains(&SourceId::new(provenance::VERIFIER))
1688        );
1689        // No labels of its own: every part takes the whole input's (fails closed).
1690        let flat = Tainted::with_label(json!({ "bundle": {} }), model.clone());
1691        assert_eq!(conversation_label(&flat).provenance, model.provenance);
1692    }
1693
1694    #[test]
1695    fn absolute_paths_inside_the_root_become_relative_and_others_stay() {
1696        let mut a = json!({ "path": "/work/repo/specs/001-x/plan.md" });
1697        relativise(&mut a, Some("/work/repo"));
1698        assert_eq!(a["path"], "specs/001-x/plan.md");
1699        let mut outside = json!({ "path": "/work/repository-two/x" });
1700        relativise(&mut outside, Some("/work/repo"));
1701        assert_eq!(outside["path"], "/work/repository-two/x");
1702        let mut none = json!({ "path": "/etc/passwd" });
1703        relativise(&mut none, None);
1704        assert_eq!(none["path"], "/etc/passwd");
1705    }
1706}