agentwerk 0.1.13

A minimal Rust crate that gives any application agentic capabilities.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Atomic finisher + spawner: validate the agent's `result`, finish the
//! current ticket through the shared `write_result` helper, then insert
//! a child ticket pinned to `to` with the current ticket recorded as
//! its `parent`. Sister tool to `CloseTicketTool` — both finish the
//! current ticket; this one also chains a follow-up.

use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;

use serde_json::Value;

use crate::agents::tickets::Ticket;
use crate::providers::ProviderResult;
use crate::schemas::Schema;

use super::super::tool::{ToolContext, ToolLike, ToolResult};
use super::super::tool_file::ToolFile;
use super::{resolve_current_key, write_result};

pub struct HandoverTicketTool;

/// Reserved placeholders substituted into the child ticket's `task`
/// string at handover time: `{parent_key}` and `{parent_result}`.
/// Single-pass `str::replace` over each in turn; unknown `{name}`
/// placeholders pass through verbatim. The non-string arm is
/// defensive: input validation already rejects non-string `task`.
fn apply_handover_templates(task: Value, parent_key: &str, parent_result: &str) -> Value {
    match task {
        Value::String(s) => Value::String(
            s.replace("{parent_key}", parent_key)
                .replace("{parent_result}", parent_result),
        ),
        other => other,
    }
}

fn tool_file() -> &'static ToolFile {
    static FILE: OnceLock<ToolFile> = OnceLock::new();
    FILE.get_or_init(|| ToolFile::parse(include_str!("handover_ticket.tool.json")))
}

fn description() -> &'static str {
    static DESC: OnceLock<String> = OnceLock::new();
    DESC.get_or_init(|| tool_file().render_markdown())
}

impl ToolLike for HandoverTicketTool {
    fn name(&self) -> &str {
        &tool_file().name
    }

    fn description(&self) -> &str {
        description()
    }

    fn input_schema(&self) -> Value {
        tool_file().input_schema.clone()
    }

    fn is_read_only(&self) -> bool {
        tool_file().read_only
    }

    fn call<'a>(
        &'a self,
        input: Value,
        ctx: &'a ToolContext,
    ) -> Pin<Box<dyn Future<Output = ProviderResult<ToolResult>> + Send + 'a>> {
        Box::pin(async move {
            let Some(ticket_system) = ctx.ticket_system_handle().cloned() else {
                return Ok(ToolResult::error(
                    "Ticket system unavailable in this context",
                ));
            };

            let to = match input.get("to").and_then(|v| v.as_str()) {
                Some(s) if !s.trim().is_empty() => s.trim().to_string(),
                _ => return Ok(ToolResult::error("Missing required parameter: to")),
            };
            let task = match input.get("task") {
                Some(Value::String(s)) if !s.is_empty() => Value::String(s.clone()),
                Some(Value::String(_)) => {
                    return Ok(ToolResult::error("`task` must not be an empty string"))
                }
                Some(Value::Null) | None => {
                    return Ok(ToolResult::error("Missing required parameter: task"))
                }
                Some(_) => return Ok(ToolResult::error("`task` must be a string")),
            };
            let result = match input.get("result") {
                Some(Value::String(s)) if !s.is_empty() => Value::String(s.clone()),
                Some(Value::String(_)) => {
                    return Ok(ToolResult::error("`result` must not be an empty string"))
                }
                Some(Value::Null) | None => {
                    return Ok(ToolResult::error("Missing required parameter: result"))
                }
                Some(_) => {
                    return Ok(ToolResult::error(
                        "`result` must be a string — pass plain prose, not numbers or arrays. For structured results use `close_ticket` instead.",
                    ))
                }
            };
            let child_schema: Option<Schema> = match input.get("schema") {
                Some(doc) if !doc.is_null() => match Schema::parse(doc.clone()) {
                    Ok(s) => Some(s),
                    Err(e) => {
                        return Ok(ToolResult::error(format!(
                            "Cannot hand off: supplied `schema` is invalid: {e}"
                        )));
                    }
                },
                _ => None,
            };

            let parent_key = match resolve_current_key(&ticket_system, ctx) {
                Ok(k) => k,
                Err(e) => return Ok(e),
            };

            // Captured before `write_result` consumes `result`. The
            // value was validated as a non-empty string above, so the
            // `as_str` cannot fail.
            let parent_result_str = result
                .as_str()
                .expect("`result` validated as String above")
                .to_string();

            // Parent-side finish runs first. The result is already
            // validated to be a non-empty string above; schema-bound
            // parents whose schema rejects strings will be caught by
            // the helper's schema validation and abort before any
            // child is created.
            let parent_outcome = write_result(&ticket_system, ctx, &parent_key, result);
            if !matches!(parent_outcome, ToolResult::Success(_)) {
                return Ok(parent_outcome);
            }

            let reporter = ctx
                .agent_name_str()
                .expect("agent_name on ToolContext")
                .to_string();
            let task = apply_handover_templates(task, &parent_key, &parent_result_str);
            let mut child = Ticket::new(task).label(&to).parent(&parent_key);
            if let Some(schema) = child_schema {
                child = child.schema(schema);
            }
            let child_key = ticket_system.insert(child, reporter);

            Ok(ToolResult::success(format!(
                "Ticket {parent_key} marked done; handed off to {child_key} (to: {to})"
            )))
        })
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::Arc;

    use super::*;
    use crate::agents::tickets::{Status, Ticket, TicketSystem};
    use crate::schemas::Schema;

    fn ctx_with(ticket_system: Arc<TicketSystem>, agent: &str, dir: PathBuf) -> ToolContext {
        ToolContext::new(dir)
            .ticket_system(ticket_system)
            .agent_name(agent.to_string())
    }

    /// Process-lifetime tempdir used as the default `TicketSystem` root
    /// for tests in this module. Tests that need an isolated workspace
    /// still call `sys.dir(...)` explicitly to override.
    fn shared_test_dir() -> &'static std::path::Path {
        use std::sync::OnceLock;
        static DIR: OnceLock<crate::test_util::TempDir> = OnceLock::new();
        DIR.get_or_init(|| crate::test_util::TempDir::new().unwrap())
            .path()
    }

    fn one_ticket(agent: &str) -> (Arc<TicketSystem>, String) {
        let sys = TicketSystem::new();
        sys.dir(shared_test_dir().to_path_buf());
        sys.insert(Ticket::new("parent body").label(agent), "tester".into());
        let key = sys
            .claim(|t| t.status == Status::Todo, agent)
            .expect("claim must succeed");
        (sys, key)
    }

    #[tokio::test]
    async fn happy_path_finishes_parent_creates_child_with_parent_link() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "continue with X",
                    "result": "summary of alice's work"
                }),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Success(_)));

        let parent = sys.get(&parent_key).unwrap();
        assert_eq!(parent.status, Status::Done);
        assert_eq!(
            parent.result_string().as_deref(),
            Some("summary of alice's work")
        );

        let child = sys.get("TICKET-2").unwrap();
        assert_eq!(child.status, Status::Todo);
        assert_eq!(child.parent_key(), Some(parent_key.as_str()));
        assert_eq!(child.labels, vec!["bob".to_string()]);
        assert_eq!(child.reporter(), "alice");
    }

    #[tokio::test]
    async fn appends_one_ndjson_line_for_parent_result() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        HandoverTicketTool
            .call(
                serde_json::json!({"to": "bob", "task": "next", "result": "done part 1"}),
                &ctx,
            )
            .await
            .unwrap();

        let log = std::fs::read_to_string(dir.path().join("results.jsonl")).unwrap();
        let lines: Vec<&str> = log.lines().collect();
        assert_eq!(
            lines.len(),
            1,
            "only the parent finish writes a result line"
        );
        let parsed: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
        assert_eq!(parsed["ticket"], parent_key.as_str());
        assert_eq!(parsed["agent"], "alice");
        assert_eq!(parsed["result"], "done part 1");
    }

    #[tokio::test]
    async fn schema_violation_aborts_atomically() {
        // Parent demands a string of at least 50 characters; we pass
        // a short string, which violates the schema but passes the
        // type check, so we exercise the schema-validation abort path.
        let dir = crate::test_util::TempDir::new().unwrap();
        let sys = TicketSystem::new();
        sys.dir(shared_test_dir().to_path_buf());
        sys.dir(dir.path().to_path_buf());
        let schema = Schema::parse(serde_json::json!({
            "type": "string",
            "minLength": 50
        }))
        .unwrap();
        sys.insert(
            Ticket::new("strict parent").schema(schema).label("alice"),
            "tester".into(),
        );
        let parent_key = sys
            .claim(|t| t.status == Status::Todo, "alice")
            .expect("claim must succeed");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({"to": "bob", "task": "next", "result": "too short"}),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::SchemaError(_)));

        let parent = sys.get(&parent_key).unwrap();
        assert_eq!(parent.status, Status::InProgress);
        assert!(parent.result().is_none());
        assert!(
            sys.get("TICKET-2").is_none(),
            "no child created on schema failure"
        );
        assert!(!dir.path().join("results.jsonl").exists());
    }

    #[tokio::test]
    async fn malformed_schema_aborts_atomically() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "next",
                    "result": "ok",
                    "schema": {"type": "not_a_real_type"}
                }),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));

        let parent = sys.get(&parent_key).unwrap();
        assert_eq!(parent.status, Status::InProgress);
        assert!(sys.get("TICKET-2").is_none());
        assert!(!dir.path().join("results.jsonl").exists());
    }

    #[tokio::test]
    async fn optional_schema_attached_to_child() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "produce a report",
                    "result": "alice's findings",
                    "schema": {"type": "object", "required": ["title"]}
                }),
                &ctx,
            )
            .await
            .unwrap();

        let child = sys.get("TICKET-2").unwrap();
        assert!(child.schema.is_some());
    }

    #[tokio::test]
    async fn rejects_missing_to() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(serde_json::json!({"task": "x", "result": "y"}), &ctx)
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn rejects_empty_to() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({"to": "  ", "task": "x", "result": "y"}),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn rejects_missing_task() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(serde_json::json!({"to": "bob", "result": "y"}), &ctx)
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn rejects_missing_result() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(serde_json::json!({"to": "bob", "task": "x"}), &ctx)
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn rejects_null_or_empty_result() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        for body in [
            serde_json::json!({"to": "bob", "task": "x", "result": null}),
            serde_json::json!({"to": "bob", "task": "x", "result": ""}),
        ] {
            let outcome = HandoverTicketTool.call(body, &ctx).await.unwrap();
            assert!(matches!(outcome, ToolResult::Error(_)));
        }
    }

    #[tokio::test]
    async fn rejects_non_string_result() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        for non_string in [
            serde_json::json!({"to": "bob", "task": "next", "result": 42}),
            serde_json::json!({"to": "bob", "task": "next", "result": [1, 2, 3]}),
            serde_json::json!({"to": "bob", "task": "next", "result": {"k": "v"}}),
        ] {
            let outcome = HandoverTicketTool.call(non_string, &ctx).await.unwrap();
            assert!(matches!(outcome, ToolResult::Error(_)));
        }
        assert_eq!(sys.get(&parent_key).unwrap().status, Status::InProgress);
        assert!(!dir.path().join("results.jsonl").exists());
    }

    #[tokio::test]
    async fn rejects_non_string_task() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, _key) = one_ticket("alice");
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({"to": "bob", "task": 42, "result": "ok"}),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn errors_when_no_current_ticket() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let sys = TicketSystem::new();
        sys.dir(shared_test_dir().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());
        let outcome = HandoverTicketTool
            .call(
                serde_json::json!({"to": "bob", "task": "x", "result": "y"}),
                &ctx,
            )
            .await
            .unwrap();
        assert!(matches!(outcome, ToolResult::Error(_)));
    }

    #[tokio::test]
    async fn substitutes_parent_key_and_result_in_task() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "Continue {parent_key}: {parent_result}",
                    "result": "alice's findings"
                }),
                &ctx,
            )
            .await
            .unwrap();

        let child = sys.get("TICKET-2").unwrap();
        assert_eq!(
            child.task,
            serde_json::Value::String(format!("Continue {parent_key}: alice's findings")),
        );
    }

    #[tokio::test]
    async fn unknown_placeholders_pass_through() {
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "See {parent_key} and {unknown}",
                    "result": "ok"
                }),
                &ctx,
            )
            .await
            .unwrap();

        let child = sys.get("TICKET-2").unwrap();
        assert_eq!(
            child.task,
            serde_json::Value::String(format!("See {parent_key} and {{unknown}}")),
        );
    }

    #[tokio::test]
    async fn substitution_is_single_pass() {
        // A `result` that itself contains the literal text `{parent_key}`
        // must NOT be re-expanded — the substitution pass runs once
        // per placeholder, not recursively.
        let dir = crate::test_util::TempDir::new().unwrap();
        let (sys, parent_key) = one_ticket("alice");
        sys.dir(dir.path().to_path_buf());
        let ctx = ctx_with(Arc::clone(&sys), "alice", dir.path().to_path_buf());

        HandoverTicketTool
            .call(
                serde_json::json!({
                    "to": "bob",
                    "task": "[{parent_result}]",
                    "result": "{parent_key}"
                }),
                &ctx,
            )
            .await
            .unwrap();

        let child = sys.get("TICKET-2").unwrap();
        assert_eq!(
            child.task,
            serde_json::Value::String("[{parent_key}]".to_string()),
            "result containing `{{parent_key}}` should be inserted literally, \
             not recursively expanded (parent_key was {parent_key})",
        );
    }
}