aidaemon-work 0.25.0

Goals, mandates, tasks and work coordination with a SQLite store; internal to aidaemon, no stability promise
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Tests of `track_requirements` against the crate's own SQLite work store.

use crate::plans::PlanStore;
use crate::tools::test_support::*;
use crate::tools::track_requirements::*;
use crate::traits::StableObservationSubject;
use crate::traits::ToolSemanticFacet;
use crate::traits::ToolSemantics;
use crate::traits::*;
use aidaemon_tools::OutcomeTool as Tool;
use aidaemon_tools::testing::CallWithFacts;
use serde_json::Value;
use serde_json::json;
use sqlx::sqlite::SqlitePoolOptions;
use std::sync::Arc;

async fn test_tool() -> (TrackRequirementsTool, Arc<PlanStore>) {
    let pool = SqlitePoolOptions::new()
        .max_connections(1)
        .connect("sqlite::memory:")
        .await
        .unwrap();
    let plan_store = Arc::new(PlanStore::new(pool).await.unwrap());
    // The tool only persists checklist state; UI delivery is handled by the
    // agent loop via StatusUpdate::Checklist, so there is no hub to wire here.
    (TrackRequirementsTool::new(plan_store.clone()), plan_store)
}

/// The card's header follows the honest outcome (live 2026-11-12: step 3
/// found no price, yet the card read "Done ยท 3 of 3 steps"). An item
/// tried and not achieved is not done, and a partial or blocked verdict
/// never reads as done.
#[tokio::test]
async fn checklist_header_follows_unmet_items_and_the_claimed_outcome() {
    let (tool, _plan_store) = test_tool().await;
    let failed_item = json!({
        "items": [
            {"text": "Say the date", "status": "completed"},
            {"text": "Multiply the numbers", "status": "completed"},
            {"text": "Find the synthetic quote", "status": "failed"}
        ],
        "outcome": "done"
    })
    .to_string();
    tool.validate_arguments(&failed_item).unwrap();
    let statuses = &tool.schema()["parameters"]["properties"]["items"]["items"]["properties"]["status"]
        ["enum"];
    assert!(statuses.as_array().unwrap().contains(&json!("failed")));
    let out = tool
        .call_with(
            &failed_item,
            aidaemon_tools::testing::call_facts("sess-failed"),
        )
        .await
        .unwrap();
    assert!(!out.contains("Done ยท"), "{out}");
    // Ticked on the model's word only: done. Neither changes anything,
    // so neither needs a receipt and the card adds no note.
    assert!(out.contains("Stopped ยท 2 of 3 done\n"), "{out}");
    assert!(!out.contains("verify"), "{out}");

    let partial = json!({
        "items": [
            {"text": "Say the date", "status": "completed"},
            {"text": "Find the synthetic quote", "status": "completed"}
        ],
        "outcome": "partial"
    })
    .to_string();
    let out = tool
        .call_with(
            &partial,
            aidaemon_tools::testing::call_facts("sess-partial"),
        )
        .await
        .unwrap();
    assert!(!out.contains("Done ยท"), "{out}");
    assert!(out.contains("Stopped short ยท 2 of 2 done\n"), "{out}");

    let done = partial.replace("partial", "done");
    let out = tool
        .call_with(&done, aidaemon_tools::testing::call_facts("sess-done"))
        .await
        .unwrap();
    assert!(out.contains("โœ… Done ยท 2 of 2 steps"), "{out}");

    // An action step that declared a side effect and that nothing
    // verified is the one step the card flags, in plain words.
    let action = json!({
        "items": [
            {"text": "Say the date", "status": "completed"},
            {"text": "Save the quote to quote.txt", "status": "completed",
             "mutation_effects": ["local_workspace_write"]}
        ],
        "outcome": "done"
    })
    .to_string();
    let out = tool
        .call_with(&action, aidaemon_tools::testing::call_facts("sess-action"))
        .await
        .unwrap();
    assert!(
        out.contains("โ˜‘๏ธ Finished ยท 2 of 2 done; I couldn't verify 1"),
        "{out}"
    );
    assert!(
        out.contains("โ˜‘๏ธ Save the quote to quote.txt (I couldn't verify this one)"),
        "{out}"
    );
    assert!(out.contains("โœ… Say the date"), "{out}");
    assert!(!out.to_lowercase().contains("tool"), "{out}");
}

/// Steps left open while the chat's background sub-agents run read as
/// continuing in the background, never "stopped short", even when no
/// launch named them (typed: the running records, not the wording).
#[tokio::test]
async fn open_steps_wait_on_running_background_sub_agents() {
    let (tool, _plan_store) = test_tool().await;
    let state = test_store().await;
    state
        .record_background_spawn(&crate::traits::BackgroundSpawn {
            id: "background_spawn:synthetic".to_string(),
            session_id: "sess-bg".to_string(),
            mission: "Install a synthetic site".to_string(),
            started_at: chrono::Utc::now().to_rfc3339(),
        })
        .await
        .unwrap();
    let tool = tool.with_state(state);
    let args = json!({
        "items": [
            {"text": "Check the tools", "status": "completed"},
            {"text": "Install the synthetic site", "status": "deferred"}
        ],
        "outcome": "partial"
    })
    .to_string();
    let out = tool
        .call_with(&args, aidaemon_tools::testing::call_facts("sess-bg"))
        .await
        .unwrap();
    assert!(
        out.contains("Continuing in the background ยท 1 of 2 done\n"),
        "{out}"
    );
    assert!(
        !out.contains("Stopped short") && !out.contains("not done"),
        "{out}"
    );

    // Another chat with nothing running keeps its own verdict.
    let out = tool
        .call_with(&args, aidaemon_tools::testing::call_facts("sess-quiet"))
        .await
        .unwrap();
    assert!(out.contains("Stopped short"), "{out}");
}

/// A step with nothing to do is finished, not failed: the card reads
/// done and can go once the reply lands.
#[tokio::test]
async fn a_step_with_nothing_to_do_reads_as_not_needed() {
    let (tool, _plan_store) = test_tool().await;
    let args = json!({
        "items": [
            {"text": "Find your open orders", "status": "completed"},
            {"text": "Cancel the open orders", "status": "skipped"}
        ],
        "outcome": "done"
    })
    .to_string();
    tool.validate_arguments(&args).unwrap();
    let out = tool
        .call_with(&args, aidaemon_tools::testing::call_facts("sess-skip"))
        .await
        .unwrap();
    assert!(out.contains("โœ… Done ยท 1 done, 1 not needed"), "{out}");
    assert!(
        out.contains("โž– Cancel the open orders (not needed)"),
        "{out}"
    );
    assert!(!out.contains('โš '), "{out}");
}

/// Read-only correctly kept a write from happening: the card says why it
/// was not done instead of "โŒ Stopped".
#[tokio::test]
async fn read_only_holds_steps_back_instead_of_failing_them() {
    let (tool, plan_store) = test_tool().await;
    let args = json!({
        "items": [
            {"text": "Read your config", "status": "completed"},
            {"text": "Write the new setting", "status": "failed"}
        ],
        "outcome": "blocked"
    })
    .to_string();
    let mut facts = aidaemon_tools::testing::call_facts("sess-ro");
    facts.mutation_forbidden = true;
    let out = tool.call_with(&args, facts).await.unwrap();
    assert!(
        out.contains("โญ๏ธ Not done: read-only is on ยท 1 of 2 done\n"),
        "{out}"
    );
    assert!(
        out.contains("โญ๏ธ Write the new setting (not done: read-only is on)"),
        "{out}"
    );
    assert!(!out.contains('โŒ') && !out.contains("Stopped"), "{out}");
    let plan = plan_store
        .get_recent_for_session("sess-ro", 1)
        .await
        .unwrap();
    assert_eq!(
        plan[0].steps[1].not_done,
        Some(crate::plans::NotDoneReason::ChangesOff)
    );
}

/// One step is the request itself: no card, the reply says how it went.
#[tokio::test]
async fn a_one_step_checklist_gets_no_card() {
    let (tool, _plan_store) = test_tool().await;
    let args =
        json!({"items": [{"text": "Save your test name", "status": "in_progress"}]}).to_string();
    let out = tool
        .call_with(&args, aidaemon_tools::testing::call_facts("sess-one"))
        .await
        .unwrap();
    let (_, after_header) = out.split_once(CHECKLIST_HEADER).expect("header");
    let (_, card) = after_header.split_once(":\n").expect("card");
    assert!(card.trim().is_empty(), "{out}");
    assert!(out.contains("Save your test name"), "{out}");
}

#[tokio::test]
async fn test_track_requirements_persists_and_returns_rendered_list() {
    let (tool, plan_store) = test_tool().await;
    let args = json!({
        "items": [
            {"text": "create script", "status": "in_progress"},
            {"text": "send the file", "status": "pending"}
        ]
    })
    .to_string();
    let out = tool
        .call_with(&args, aidaemon_tools::testing::call_facts("sess-1"))
        .await
        .unwrap();
    assert!(out.contains("create script"));
    assert!(out.contains("send the file"));
    let plan = plan_store
        .get_incomplete_for_session("sess-1")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(plan.steps.len(), 2);
    assert_eq!(plan.unchecked_steps().len(), 2);
}

#[tokio::test]
async fn test_track_requirements_marks_completed_on_update() {
    let (tool, plan_store) = test_tool().await;
    let mk = |status: &str| {
        json!({
            "items": [{"text": "send the file", "status": status}]
        })
        .to_string()
    };
    tool.call_with(
        &mk("pending"),
        aidaemon_tools::testing::call_facts("sess-2"),
    )
    .await
    .unwrap();
    // While still pending it is the session's active (incomplete) checklist.
    let id = plan_store
        .get_incomplete_for_session("sess-2")
        .await
        .unwrap()
        .unwrap()
        .id;

    tool.call_with(
        &mk("completed"),
        aidaemon_tools::testing::call_facts("sess-2"),
    )
    .await
    .unwrap();
    // Once all items are completed the plan is auto-completed (no longer
    // "incomplete"), so fetch it by id to verify the final state.
    let plan = plan_store.get(&id).await.unwrap().unwrap();
    assert_eq!(plan.unchecked_steps().len(), 0);
    assert_eq!(plan.completed_steps(), 1);
}

fn synthetic_vocabulary() -> StableSubjectVocabulary {
    StableSubjectVocabulary::from_subjects(vec![
        StableObservationSubject::collection(
            "objective_collection:scheduled_goals",
            &[ToolSemanticFacet::Schedule, ToolSemanticFacet::RunState],
            "objective:",
            "every scheduled goal",
        ),
        StableObservationSubject::collection(
            "objective_collection:mandate_controllers",
            &[ToolSemanticFacet::Control],
            "objective:",
            "every mandate controller",
        ),
        StableObservationSubject::collection(
            "auth_profile_collection:configured",
            &[ToolSemanticFacet::Authorization],
            "auth_profile:",
            "every configured API auth profile",
        ),
        StableObservationSubject::namespace("res_", "session resource handles"),
    ])
}

/// The live 2026-09-01 audit shape: two items bound to advertised
/// collections and a third bound to an invented credential-state ID that
/// no adapter reports.
fn audit_checklist_arguments(status: &str) -> Value {
    json!({
        "items": [
            {
                "text": "Audit the schedule state and latest run outcome.",
                "status": status,
                "requires_observation": true,
                "targets": [{
                    "subject": {"kind": "resource_id", "value": "objective_collection:scheduled_goals"},
                    "facets": ["schedule", "run_state"],
                    "collection_coverage": {
                        "collection": {"kind": "resource_id", "value": "objective_collection:scheduled_goals"},
                        "minimum_completeness": "complete"
                    }
                }]
            },
            {
                "text": "Audit objective-control presence.",
                "status": status,
                "requires_observation": true,
                "targets": [{
                    "subject": {"kind": "resource_id", "value": "objective_collection:mandate_controllers"},
                    "facets": ["control"],
                    "collection_coverage": {
                        "collection": {"kind": "resource_id", "value": "objective_collection:mandate_controllers"},
                        "minimum_completeness": "complete"
                    }
                }]
            },
            {
                "text": "Audit owner configuration and credential readiness.",
                "status": status,
                "requires_observation": true,
                "targets": ["x_owner_credential_state"]
            }
        ]
    })
}

#[tokio::test]
async fn unbound_resource_id_target_is_dropped_and_reported() {
    let (tool, plan_store) = test_tool().await;
    let tool = tool.with_stable_subjects(synthetic_vocabulary());
    let raw = audit_checklist_arguments("in_progress").to_string();

    let canonical = tool.canonicalize_arguments(&raw).unwrap();
    let canonical_value: Value = serde_json::from_str(&canonical).unwrap();
    let items = canonical_value["items"].as_array().unwrap();
    assert_eq!(
        items[0]["targets"],
        audit_checklist_arguments("in_progress")["items"][0]["targets"],
        "an advertised collection binding must survive untouched"
    );
    assert_eq!(items[1]["targets"].as_array().unwrap().len(), 1);
    assert_eq!(
        items[2]["targets"].as_array().map(Vec::len),
        Some(0),
        "an invented resource ID can never be credited, so it must not become an exact obligation"
    );
    assert_eq!(
        items[2][UNBOUND_TARGETS_KEY],
        json!(["x_owner_credential_state"]),
        "the drop must be recorded, never silent"
    );

    let facts = crate::traits::ToolCallContext {
        task_id: Some("task-audit".into()),
        ..aidaemon_tools::testing::call_facts("sess-audit")
    };
    let out = tool.call_with(&canonical, facts).await.unwrap();
    assert!(
        out.contains("x_owner_credential_state"),
        "the model must be told which target was unbound: {out}"
    );
    assert!(
        out.contains("auth_profile_collection:configured") && out.contains("objective:"),
        "the notice must name the stable subjects the model can bind instead: {out}"
    );
    assert!(
        out.contains("Checklist updated (0/3 done):\n"),
        "the checklist header must remain the live-surface delimiter: {out}"
    );
    let plan = plan_store
        .get_incomplete_for_session("sess-audit")
        .await
        .unwrap()
        .unwrap();
    assert!(plan.steps[2].expected_targets.is_empty());
    assert_eq!(
        plan.steps[0].expected_targets,
        ["objective_collection:scheduled_goals"]
    );
}