Skip to main content

aidaemon_tools/
checklist.rs

1//! `track_requirements`: the model's own checklist, plus a stop hook that
2//! refuses to finish while items are open.
3
4use std::sync::{Arc, Mutex};
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9
10use aidaemon_core::{
11    CallEffects, Hook, HookContext, StopDecision, Tool, ToolAnnotations, ToolContext, ToolOutput,
12    ToolResult, ToolSpec,
13};
14
15use crate::util::{fail, parse_args};
16
17/// Most items a checklist may hold.
18pub const MAX_ITEMS: usize = 100;
19
20/// Where an item stands. The model sets `pending`, `in_progress`, `done`,
21/// `deferred` and `superseded`; only the application sets `waived`
22/// ([`ChecklistState::waive`]), because only the owner can drop scope.
23///
24/// Stopping and succeeding are separate: `deferred` lets the run stop, but
25/// a deferred item is unmet, so the run does not count as succeeded.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum ItemStatus {
29    Pending,
30    InProgress,
31    Done,
32    /// The model is not doing it in this run; needs a `reason`. Unmet.
33    Deferred,
34    /// Replaced by another item (`superseded_by`); met only once that item
35    /// is done.
36    Superseded,
37    /// The owner dropped it from scope; set by the application only.
38    Waived,
39}
40
41impl ItemStatus {
42    fn marker(self) -> &'static str {
43        match self {
44            Self::Pending => "[ ]",
45            Self::InProgress => "[~]",
46            Self::Done => "[x]",
47            Self::Deferred => "[-]",
48            Self::Superseded => "[>]",
49            Self::Waived => "[w]",
50        }
51    }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct ChecklistItem {
57    pub text: String,
58    pub status: ItemStatus,
59    /// Why the item is deferred or waived.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub reason: Option<String>,
62    /// For `superseded`: the 1-based number of the item that replaces it,
63    /// in the same list.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub superseded_by: Option<usize>,
66}
67
68impl ChecklistItem {
69    pub fn new(text: impl Into<String>, status: ItemStatus) -> Self {
70        Self {
71            text: text.into(),
72            status,
73            reason: None,
74            superseded_by: None,
75        }
76    }
77}
78
79/// How one item resolves once the run stops.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81enum Resolution {
82    /// Still being worked on (directly, or through the item replacing it).
83    Open,
84    Met,
85    Unmet,
86}
87
88/// Follow `superseded_by` to the item that settles `index`. A superseded
89/// item may only point at an item that is not itself superseded, so this is
90/// one hop at most; anything else resolves as unmet.
91fn resolve(items: &[ChecklistItem], index: usize) -> Resolution {
92    let item = &items[index];
93    match item.status {
94        ItemStatus::Pending | ItemStatus::InProgress => Resolution::Open,
95        ItemStatus::Done | ItemStatus::Waived => Resolution::Met,
96        ItemStatus::Deferred => Resolution::Unmet,
97        ItemStatus::Superseded => {
98            let target = item
99                .superseded_by
100                .and_then(|n| n.checked_sub(1))
101                .filter(|&t| t != index)
102                .filter(|&t| {
103                    items
104                        .get(t)
105                        .is_some_and(|i| i.status != ItemStatus::Superseded)
106                });
107            match target {
108                Some(t) => resolve(items, t),
109                None => Resolution::Unmet,
110            }
111        }
112    }
113}
114
115/// Shared checklist state. Clone it to share between the tool, the gate and
116/// your own code. Use one per run or session.
117#[derive(Debug, Clone, Default)]
118pub struct ChecklistState {
119    items: Arc<Mutex<Vec<ChecklistItem>>>,
120}
121
122impl ChecklistState {
123    pub fn new() -> Self {
124        Self::default()
125    }
126
127    pub fn items(&self) -> Vec<ChecklistItem> {
128        self.items.lock().expect("checklist poisoned").clone()
129    }
130
131    /// Items work is still expected on: pending or in progress, or
132    /// superseded by one that is.
133    pub fn open_items(&self) -> Vec<ChecklistItem> {
134        let items = self.items();
135        (0..items.len())
136            .filter(|&i| resolve(&items, i) == Resolution::Open)
137            .map(|i| items[i].clone())
138            .collect()
139    }
140
141    /// Items that will not be met in this run: deferred, or superseded by
142    /// an item that will not be met.
143    pub fn unmet_items(&self) -> Vec<ChecklistItem> {
144        let items = self.items();
145        (0..items.len())
146            .filter(|&i| resolve(&items, i) == Resolution::Unmet)
147            .map(|i| items[i].clone())
148            .collect()
149    }
150
151    /// Replace the list as the application (no provenance checks). The
152    /// model's updates go through the tool, which checks them.
153    pub fn set(&self, items: Vec<ChecklistItem>) {
154        *self.items.lock().expect("checklist poisoned") = items;
155    }
156
157    /// The owner drops an item from scope. Returns false when no item has
158    /// this text. Only the application can do this; the model can defer an
159    /// item but not waive it.
160    pub fn waive(&self, text: &str, reason: impl Into<String>) -> bool {
161        let mut items = self.items.lock().expect("checklist poisoned");
162        let Some(item) = items.iter_mut().find(|i| i.text == text.trim()) else {
163            return false;
164        };
165        item.status = ItemStatus::Waived;
166        item.reason = Some(reason.into());
167        item.superseded_by = None;
168        true
169    }
170}
171
172fn render(items: &[ChecklistItem]) -> String {
173    items
174        .iter()
175        .enumerate()
176        .map(|(i, item)| format!("{}. {}", i + 1, describe(item)))
177        .collect::<Vec<_>>()
178        .join("\n")
179}
180
181fn describe(item: &ChecklistItem) -> String {
182    let mut line = format!("{} {}", item.status.marker(), item.text);
183    match item.status {
184        ItemStatus::Deferred | ItemStatus::Waived => {
185            if let Some(reason) = &item.reason {
186                line.push_str(&format!(" ({}: {reason})", status_word(item.status)));
187            }
188        }
189        ItemStatus::Superseded => {
190            if let Some(n) = item.superseded_by {
191                line.push_str(&format!(" (superseded by item {n})"));
192            }
193        }
194        _ => {}
195    }
196    line
197}
198
199fn status_word(status: ItemStatus) -> &'static str {
200    match status {
201        ItemStatus::Pending => "pending",
202        ItemStatus::InProgress => "in progress",
203        ItemStatus::Done => "done",
204        ItemStatus::Deferred => "deferred",
205        ItemStatus::Superseded => "superseded",
206        ItemStatus::Waived => "waived",
207    }
208}
209
210/// Check a model's update against the current list. Every item that is not
211/// done or waived must stay visible: removing an open, deferred or
212/// superseded item would erase the record that it was not accomplished.
213/// Only the owner waives; a waived item the model keeps stays waived.
214fn validate(previous: &[ChecklistItem], items: &[ChecklistItem]) -> Result<(), String> {
215    for (i, item) in items.iter().enumerate() {
216        let n = i + 1;
217        let reason = item.reason.as_deref().map(str::trim).unwrap_or("");
218        let was_waived = previous
219            .iter()
220            .any(|p| p.text == item.text && p.status == ItemStatus::Waived);
221        match item.status {
222            ItemStatus::Waived if !was_waived => {
223                return Err(format!(
224                    "item {n} (\"{}\"): only the owner can waive an item. Mark it deferred \
225                     with a reason if you are not doing it.",
226                    item.text
227                ));
228            }
229            ItemStatus::Deferred if reason.is_empty() => {
230                return Err(format!(
231                    "item {n} (\"{}\"): a deferred item needs a `reason`.",
232                    item.text
233                ));
234            }
235            ItemStatus::Superseded => {
236                let target = item
237                    .superseded_by
238                    .filter(|&t| t >= 1 && t != n)
239                    .and_then(|t| items.get(t - 1));
240                match target {
241                    None => {
242                        return Err(format!(
243                            "item {n} (\"{}\"): a superseded item needs `superseded_by`, the \
244                             number of another item in this list that replaces it.",
245                            item.text
246                        ));
247                    }
248                    Some(t) if t.status == ItemStatus::Superseded => {
249                        return Err(format!(
250                            "item {n} (\"{}\"): it is superseded by an item that is itself \
251                             superseded; point it at the final replacement.",
252                            item.text
253                        ));
254                    }
255                    Some(_) => {}
256                }
257            }
258            _ if was_waived => {
259                return Err(format!(
260                    "item {n} (\"{}\") was waived by the owner; keep its status `waived`.",
261                    item.text
262                ));
263            }
264            _ => {}
265        }
266        if item.status != ItemStatus::Superseded && item.superseded_by.is_some() {
267            return Err(format!(
268                "item {n} (\"{}\"): `superseded_by` is only for superseded items.",
269                item.text
270            ));
271        }
272    }
273    let missing: Vec<&ChecklistItem> = previous
274        .iter()
275        .filter(|p| !matches!(p.status, ItemStatus::Done | ItemStatus::Waived))
276        .filter(|p| !items.iter().any(|i| i.text == p.text))
277        .collect();
278    if !missing.is_empty() {
279        let list = missing
280            .iter()
281            .map(|p| format!("- {}", describe(p)))
282            .collect::<Vec<_>>()
283            .join("\n");
284        return Err(format!(
285            "these items are not done and cannot be removed:\n{list}\nKeep each one in the \
286             list: mark it done once it is finished, deferred with a reason if you are not \
287             doing it, or superseded with `superseded_by` pointing at the item that replaces \
288             it (to reword an item, add the new wording and supersede the old one)."
289        ));
290    }
291    Ok(())
292}
293
294/// The `track_requirements` tool. Each call replaces the whole list, so the
295/// model always states the full current plan.
296#[derive(Debug, Clone, Default)]
297pub struct Checklist {
298    state: ChecklistState,
299}
300
301impl Checklist {
302    pub fn new(state: ChecklistState) -> Self {
303        Self { state }
304    }
305
306    /// A tool and its matching stop gate over fresh shared state.
307    pub fn with_gate() -> (Self, ChecklistGate) {
308        let state = ChecklistState::new();
309        (Self::new(state.clone()), ChecklistGate::new(state))
310    }
311
312    pub fn state(&self) -> &ChecklistState {
313        &self.state
314    }
315}
316
317#[derive(Deserialize)]
318#[serde(deny_unknown_fields)]
319struct ChecklistArgs {
320    items: Vec<ChecklistItem>,
321}
322
323#[async_trait]
324impl Tool for Checklist {
325    fn spec(&self) -> ToolSpec {
326        ToolSpec {
327            name: "track_requirements".into(),
328            description: "Declare or update your checklist for the current task. Send the \
329                 complete list every time (it replaces the previous one). Use it for \
330                 multi-step work: list every requirement up front, keep one item in_progress, \
331                 and mark an item done only after it is actually finished and verified. You \
332                 cannot finish while items are pending or in_progress. If you will not do an \
333                 item, mark it deferred with a reason: the run can then end, but it is \
334                 reported as not fully done. If another item replaces one, mark the old one \
335                 superseded with superseded_by set to the new item's number. Items that are \
336                 not done cannot be removed from the list. Each item is a piece of work \
337                 with a result you can check. Rules the whole task must keep (follow the \
338                 project's instructions, don't commit, keep the tests passing) are not items: \
339                 keep them while doing the items, and check them as part of the item they \
340                 apply to."
341                .into(),
342            parameters: json!({
343                "type": "object",
344                "properties": {
345                    "items": {
346                        "type": "array",
347                        "maxItems": MAX_ITEMS,
348                        "items": {
349                            "type": "object",
350                            "properties": {
351                                "text": {"type": "string", "description": "What must be true when this item is done: a result, not a rule to follow throughout."},
352                                "status": {"type": "string", "enum": ["pending", "in_progress", "done", "deferred", "superseded"]},
353                                "reason": {"type": "string", "description": "Required for deferred: why it is not being done."},
354                                "superseded_by": {"type": "integer", "minimum": 1, "description": "Required for superseded: the number (1-based) of the item in this list that replaces it."}
355                            },
356                            "required": ["text", "status"],
357                            "additionalProperties": false
358                        }
359                    }
360                },
361                "required": ["items"],
362                "additionalProperties": false
363            }),
364        }
365    }
366
367    fn annotations(&self) -> ToolAnnotations {
368        // Changes only agent-internal state, but two updates in one turn
369        // must not race, so it is not read-only.
370        ToolAnnotations {
371            read_only: false,
372            destructive: false,
373            idempotent: true,
374            egress: false,
375        }
376    }
377
378    /// Only the agent's own list changes; nothing outside the agent.
379    fn effects(&self, _arguments: &Value) -> CallEffects {
380        CallEffects::none()
381    }
382
383    async fn call(&self, arguments: Value, _ctx: &ToolContext) -> ToolResult {
384        let args: ChecklistArgs = match parse_args("track_requirements", arguments) {
385            Ok(a) => a,
386            Err(e) => return Ok(fail(e)),
387        };
388        if args.items.len() > MAX_ITEMS {
389            return Ok(fail(format!(
390                "too many items ({}); at most {MAX_ITEMS}",
391                args.items.len()
392            )));
393        }
394        let mut items = args.items;
395        for item in &mut items {
396            item.text = item.text.trim().to_string();
397            item.reason = item
398                .reason
399                .take()
400                .map(|r| r.trim().to_string())
401                .filter(|r| !r.is_empty());
402        }
403        if items.iter().any(|i| i.text.is_empty()) {
404            return Ok(fail("every item needs non-empty `text`"));
405        }
406        for (i, item) in items.iter().enumerate() {
407            if items[..i].iter().any(|earlier| earlier.text == item.text) {
408                return Ok(fail(format!(
409                    "item {} repeats the text of an earlier item; each item needs its own text",
410                    i + 1
411                )));
412            }
413        }
414        if let Err(e) = validate(&self.state.items(), &items) {
415            return Ok(fail(e));
416        }
417        self.state.set(items.clone());
418        let resolutions: Vec<Resolution> = (0..items.len()).map(|i| resolve(&items, i)).collect();
419        let open = resolutions
420            .iter()
421            .filter(|r| **r == Resolution::Open)
422            .count();
423        let unmet = resolutions
424            .iter()
425            .filter(|r| **r == Resolution::Unmet)
426            .count();
427        let done = items
428            .iter()
429            .filter(|i| i.status == ItemStatus::Done)
430            .count();
431        let summary = if items.is_empty() {
432            "Checklist cleared.".to_string()
433        } else {
434            format!(
435                "Checklist updated: {done}/{} done.\n{}",
436                items.len(),
437                render(&items)
438            )
439        };
440        Ok(ToolOutput::text(summary).with_details(json!({
441            "total": items.len(),
442            "done": done,
443            "open": open,
444            "unmet": unmet,
445        })))
446    }
447}
448
449/// Stop hook: while any item is pending or in progress, ask the model to
450/// keep going, listing them. Once nothing is open it lets the run stop; if
451/// any item is deferred (or superseded by one that is), it reports those as
452/// unmet ([`StopDecision::AcceptUnmet`]) so the run is not counted as a
453/// success. The agent's turn limits still bound how long this can continue.
454#[derive(Debug, Clone)]
455pub struct ChecklistGate {
456    state: ChecklistState,
457}
458
459impl ChecklistGate {
460    pub fn new(state: ChecklistState) -> Self {
461        Self { state }
462    }
463}
464
465#[async_trait]
466impl Hook for ChecklistGate {
467    async fn on_stop(&self, _ctx: &HookContext<'_>, _final_text: &str) -> StopDecision {
468        let open = self.state.open_items();
469        if !open.is_empty() {
470            let list = open
471                .iter()
472                .map(|i| format!("- {}", describe(i)))
473                .collect::<Vec<_>>()
474                .join("\n");
475            return StopDecision::Continue {
476                message: format!(
477                    "Your checklist still has {} open item(s):\n{list}\n\nFinish them and mark \
478                     them done with track_requirements before giving your final answer. If you \
479                     will not do one, mark it deferred with a reason; if another item replaces \
480                     it, mark it superseded.",
481                    open.len()
482                ),
483            };
484        }
485        let unmet = self.state.unmet_items();
486        if unmet.is_empty() {
487            return StopDecision::Accept;
488        }
489        StopDecision::AcceptUnmet {
490            unmet: unmet
491                .iter()
492                .map(|i| format!("checklist: {}", describe(i)))
493                .collect(),
494        }
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use aidaemon_core::testing::{ScriptedProvider, call, text, tool_calls};
502    use aidaemon_core::{Agent, Role};
503
504    #[test]
505    fn checklist_has_no_effects_outside_the_agent() {
506        // Complete and empty, so a decline in the run never puts the
507        // checklist to the owner.
508        assert_eq!(
509            Checklist::default().effects(&json!({"items": []})),
510            aidaemon_core::CallEffects::none()
511        );
512    }
513
514    #[tokio::test]
515    async fn tool_replaces_list_and_validates() {
516        let tool = Checklist::default();
517        let out = tool
518            .call(
519                json!({"items": [
520                    {"text": "write parser", "status": "done"},
521                    {"text": "add tests", "status": "in_progress"}
522                ]}),
523                &crate::testutil::ctx(),
524            )
525            .await
526            .unwrap();
527        assert!(!out.is_error);
528        assert!(out.content.contains("1/2 done"));
529        assert!(out.content.contains("2. [~] add tests"));
530        assert_eq!(tool.state().open_items().len(), 1);
531
532        let out = tool
533            .call(
534                json!({"items": [{"text": "x", "status": "finished"}]}),
535                &crate::testutil::ctx(),
536            )
537            .await
538            .unwrap();
539        assert!(out.is_error);
540        // A rejected update leaves the previous list in place.
541        assert_eq!(tool.state().items().len(), 2);
542    }
543
544    #[tokio::test]
545    async fn gate_blocks_until_items_are_done() {
546        let (tool, gate) = Checklist::with_gate();
547        let provider = ScriptedProvider::new([
548            tool_calls([call(
549                "c1",
550                "track_requirements",
551                json!({"items": [
552                    {"text": "update config", "status": "in_progress"},
553                    {"text": "run tests", "status": "pending"}
554                ]}),
555            )]),
556            // Tries to finish early; the gate pushes back.
557            text("All done!"),
558            tool_calls([call(
559                "c2",
560                "track_requirements",
561                json!({"items": [
562                    {"text": "update config", "status": "done"},
563                    {"text": "run tests", "status": "done"}
564                ]}),
565            )]),
566            text("Config updated and tests pass."),
567        ]);
568        let state = tool.state().clone();
569        let agent = Agent::builder("checklist-test")
570            .allow_unguarded()
571            .model("scripted")
572            .provider(provider)
573            .tool(tool)
574            .hook(gate)
575            .build()
576            .unwrap();
577        let outcome = agent
578            .run("test:synthetic-user-1", "Do the task")
579            .await
580            .unwrap();
581        assert!(outcome.is_completed(), "{:?}", outcome.status);
582        assert!(outcome.is_succeeded());
583        assert_eq!(
584            outcome.final_text.as_deref(),
585            Some("Config updated and tests pass.")
586        );
587        let nudge = outcome
588            .state
589            .messages
590            .iter()
591            .find(|m| m.role == Role::User && m.content.contains("open item"))
592            .expect("gate message in transcript");
593        assert!(nudge.content.contains("update config") && nudge.content.contains("run tests"));
594        assert!(state.open_items().is_empty());
595    }
596
597    async fn gate_decision(state: &ChecklistState) -> StopDecision {
598        let ctx = HookContext {
599            run_id: aidaemon_core::RunId::new(),
600            agent_id: "a",
601            session_id: "s",
602            turn: 1,
603            messages: &[],
604            receipts: &[],
605            usage: Default::default(),
606            run_usage: Default::default(),
607            untrusted_seen: false,
608            declined: &[],
609        };
610        ChecklistGate::new(state.clone())
611            .on_stop(&ctx, "done")
612            .await
613    }
614
615    async fn update(tool: &Checklist, items: Value) -> ToolOutput {
616        tool.call(json!({ "items": items }), &crate::testutil::ctx())
617            .await
618            .unwrap()
619    }
620
621    #[tokio::test]
622    async fn deferring_lets_the_run_stop_but_not_succeed() {
623        let (tool, gate) = Checklist::with_gate();
624        let provider = ScriptedProvider::new([
625            tool_calls([call(
626                "c1",
627                "track_requirements",
628                json!({"items": [
629                    {"text": "export the report", "status": "in_progress"},
630                    {"text": "email the report", "status": "pending"}
631                ]}),
632            )]),
633            tool_calls([call(
634                "c2",
635                "track_requirements",
636                json!({"items": [
637                    {"text": "export the report", "status": "done"},
638                    {"text": "email the report", "status": "deferred",
639                     "reason": "no mail tool is available"}
640                ]}),
641            )]),
642            text("Exported. I could not email it."),
643        ]);
644        let agent = Agent::builder("checklist-test")
645            .allow_unguarded()
646            .model("scripted")
647            .provider(provider)
648            .tool(tool)
649            .hook(gate)
650            .build()
651            .unwrap();
652        let outcome = agent
653            .run("test:synthetic-user-1", "Export and email")
654            .await
655            .unwrap();
656
657        assert!(outcome.is_completed(), "deferral may stop the run");
658        assert_eq!(outcome.turns(), 3, "the gate does not nag about a deferral");
659        assert!(
660            !outcome.is_succeeded(),
661            "a deferred item is not accomplished"
662        );
663        assert_eq!(outcome.unmet().len(), 1);
664        assert!(outcome.unmet()[0].contains("email the report"));
665        assert!(outcome.unmet()[0].contains("no mail tool"));
666    }
667
668    #[tokio::test]
669    async fn unfinished_items_cannot_be_removed_or_cleared() {
670        let tool = Checklist::default();
671        let out = update(
672            &tool,
673            json!([
674                {"text": "a", "status": "done"},
675                {"text": "b", "status": "pending"},
676                {"text": "c", "status": "pending"}
677            ]),
678        )
679        .await;
680        assert!(!out.is_error);
681
682        // Dropping an open item, or clearing the list, is refused and the
683        // previous list stays.
684        let out = update(&tool, json!([{"text": "a", "status": "done"}])).await;
685        assert!(out.is_error);
686        assert!(out.content.contains("cannot be removed") && out.content.contains("b"));
687        assert!(update(&tool, json!([])).await.is_error);
688        assert_eq!(tool.state().items().len(), 3);
689
690        // A deferral needs a reason; once deferred it still cannot vanish.
691        let out = update(
692            &tool,
693            json!([
694                {"text": "a", "status": "done"},
695                {"text": "b", "status": "deferred"},
696                {"text": "c", "status": "done"}
697            ]),
698        )
699        .await;
700        assert!(out.is_error && out.content.contains("needs a `reason`"));
701        let out = update(
702            &tool,
703            json!([
704                {"text": "a", "status": "done"},
705                {"text": "b", "status": "deferred", "reason": "blocked on access"},
706                {"text": "c", "status": "done"}
707            ]),
708        )
709        .await;
710        assert!(!out.is_error, "{}", out.content);
711        assert!(
712            update(&tool, json!([{"text": "c", "status": "done"}]))
713                .await
714                .is_error
715        );
716
717        // Done items may be dropped.
718        let out = update(
719            &tool,
720            json!([{"text": "b", "status": "deferred", "reason": "blocked on access"}]),
721        )
722        .await;
723        assert!(!out.is_error, "{}", out.content);
724    }
725
726    #[tokio::test]
727    async fn only_the_owner_waives() {
728        let tool = Checklist::default();
729        update(&tool, json!([{"text": "migrate db", "status": "pending"}])).await;
730        let out = update(&tool, json!([{"text": "migrate db", "status": "waived"}])).await;
731        assert!(out.is_error && out.content.contains("only the owner"));
732        assert!(matches!(
733            gate_decision(tool.state()).await,
734            StopDecision::Continue { .. }
735        ));
736
737        assert!(tool.state().waive("migrate db", "owner: not this sprint"));
738        assert_eq!(gate_decision(tool.state()).await, StopDecision::Accept);
739        // The model cannot reopen or relabel what the owner waived.
740        let out = update(
741            &tool,
742            json!([{"text": "migrate db", "status": "deferred",
743                                         "reason": "x"}]),
744        )
745        .await;
746        assert!(out.is_error && out.content.contains("waived by the owner"));
747        assert!(!tool.state().waive("no such item", "x"));
748    }
749
750    #[tokio::test]
751    async fn superseded_items_resolve_through_their_replacement() {
752        let tool = Checklist::default();
753        update(
754            &tool,
755            json!([{"text": "use library A", "status": "in_progress"}]),
756        )
757        .await;
758
759        // Reword by superseding: the old item follows the new one.
760        let out = update(
761            &tool,
762            json!([
763                {"text": "use library A", "status": "superseded", "superseded_by": 2},
764                {"text": "use library B", "status": "in_progress"}
765            ]),
766        )
767        .await;
768        assert!(!out.is_error, "{}", out.content);
769        assert!(matches!(
770            gate_decision(tool.state()).await,
771            StopDecision::Continue { .. }
772        ));
773
774        // Replacement deferred: both are unmet.
775        update(
776            &tool,
777            json!([
778                {"text": "use library A", "status": "superseded", "superseded_by": 2},
779                {"text": "use library B", "status": "deferred", "reason": "license review"}
780            ]),
781        )
782        .await;
783        let StopDecision::AcceptUnmet { unmet } = gate_decision(tool.state()).await else {
784            panic!("expected unmet");
785        };
786        assert_eq!(unmet.len(), 2);
787
788        // Replacement done: both are met.
789        update(
790            &tool,
791            json!([
792                {"text": "use library A", "status": "superseded", "superseded_by": 2},
793                {"text": "use library B", "status": "done"}
794            ]),
795        )
796        .await;
797        assert_eq!(gate_decision(tool.state()).await, StopDecision::Accept);
798
799        // Bad pointers are refused.
800        for bad in [json!(null), json!(1), json!(9)] {
801            let out = update(
802                &tool,
803                json!([
804                    {"text": "use library A", "status": "superseded", "superseded_by": bad},
805                    {"text": "use library B", "status": "done"}
806                ]),
807            )
808            .await;
809            assert!(out.is_error, "superseded_by {bad} must be refused");
810        }
811        let out = update(
812            &tool,
813            json!([
814                {"text": "use library A", "status": "superseded", "superseded_by": 2},
815                {"text": "use library B", "status": "superseded", "superseded_by": 3},
816                {"text": "use library C", "status": "done"}
817            ]),
818        )
819        .await;
820        assert!(out.is_error && out.content.contains("itself superseded"));
821    }
822
823    /// The invariant below any wording: whatever sequence of updates the
824    /// model sends, an item it declared and never marked done can only let
825    /// the run stop as unmet, never as a plain success.
826    #[tokio::test]
827    async fn no_update_sequence_without_done_reaches_success() {
828        const TEXTS: [&str; 3] = ["x", "y", "z"];
829        const STATUSES: [&str; 4] = ["pending", "in_progress", "deferred", "superseded"];
830        // Small xorshift so the test is deterministic without extra deps.
831        let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
832        let mut next = move |n: usize| {
833            seed ^= seed << 13;
834            seed ^= seed >> 7;
835            seed ^= seed << 17;
836            (seed % n as u64) as usize
837        };
838        let (mut accepted, mut stopped_unmet) = (0, 0);
839        for _ in 0..300 {
840            let tool = Checklist::default();
841            for _ in 0..6 {
842                let len = next(TEXTS.len() + 1);
843                let items: Vec<Value> = (0..len)
844                    .map(|i| {
845                        let status = STATUSES[next(STATUSES.len())];
846                        let mut item = json!({"text": TEXTS[i], "status": status});
847                        if status == "deferred" && next(2) == 0 {
848                            item["reason"] = json!("cannot");
849                        }
850                        if status == "superseded" {
851                            item["superseded_by"] = json!(next(len + 1));
852                        }
853                        item
854                    })
855                    .collect();
856                if !update(&tool, Value::Array(items)).await.is_error {
857                    accepted += 1;
858                }
859                if !tool.state().items().is_empty() {
860                    let decision = gate_decision(tool.state()).await;
861                    assert_ne!(decision, StopDecision::Accept, "{:?}", tool.state().items());
862                    if matches!(decision, StopDecision::AcceptUnmet { .. }) {
863                        stopped_unmet += 1;
864                    }
865                }
866            }
867        }
868        // The sequences exercise both accepted updates and unmet stops.
869        assert!(
870            accepted > 100 && stopped_unmet > 50,
871            "{accepted} {stopped_unmet}"
872        );
873    }
874}