task-graph-mcp 0.5.0

MCP server for agent task workflows with phases, prompts, gates, and multi-agent coordination
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! Transition prompts system.
//!
//! Loads and delivers prompts when tasks transition between states/phases.
//! Prompts are defined in `workflows.yaml` with the following structure:
//!
//! - State prompts: `states.<state>.prompts.enter` / `states.<state>.prompts.exit`
//! - Phase prompts: `phases.<phase>.prompts.enter` / `phases.<phase>.prompts.exit`
//! - Combo prompts: `combos.<state>+<phase>.enter` / `combos.<state>+<phase>.exit`
//!
//! Trigger naming convention:
//! - `enter~{status}` - entering a status (any phase)
//! - `exit~{status}` - exiting a status (any phase)
//! - `enter%{phase}` - entering a phase (any status)
//! - `exit%{phase}` - exiting a phase (any status)
//! - `enter~{status}%{phase}` - entering specific status+phase combo
//! - `exit~{status}%{phase}` - exiting specific status+phase combo
//!
//! Template variables are expanded in prompts:
//! - `{{valid_exits}}` - valid states to transition to from current state
//! - `{{current_phase}}` - current phase if set
//! - `{{valid_phases}}` - list of valid phases that can be set
//! - `{{current_status}}` - current status name

use crate::config::workflows::WorkflowsConfig;
use crate::config::{PhasesConfig, StatesConfig};
use serde::Serialize;

/// A prompt string paired with its source attribution.
///
/// The `source` field indicates where the prompt originated from:
/// - `"state:<name>"` - state enter/exit prompt (e.g., `"state:working"`)
/// - `"phase:<name>"` - phase enter/exit prompt (e.g., `"phase:implement"`)
/// - `"combo:<state>+<phase>"` - state+phase combo prompt (e.g., `"combo:working+implement"`)
/// - `"role:<name>"` - role-specific prompt (e.g., `"role:worker"`)
/// - `"workflow"` - base workflow prompt (fallback)
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct AttributedPrompt {
    pub text: String,
    pub source: String,
}

/// Context for expanding template variables in prompts.
///
/// Provides both workflow context (status, phase, valid transitions) and
/// situational context (task metadata, agent identity) for rich prompt
/// template expansion.
#[derive(Debug, Clone)]
pub struct PromptContext<'a> {
    /// Current status of the task
    pub status: &'a str,
    /// Current phase of the task (if any)
    pub phase: Option<&'a str>,
    /// States configuration for looking up valid transitions
    pub states_config: &'a StatesConfig,
    /// Phases configuration for listing valid phases
    pub phases_config: &'a PhasesConfig,
    /// Task ID (if available)
    pub task_id: Option<&'a str>,
    /// Task title (if available)
    pub task_title: Option<&'a str>,
    /// Task priority (if available)
    pub task_priority: Option<i32>,
    /// Task tags (if available)
    pub task_tags: Option<&'a [String]>,
    /// Agent/worker ID (if available)
    pub agent_id: Option<&'a str>,
    /// Agent's matched role name (if available)
    pub agent_role: Option<&'a str>,
    /// Agent's tags (if available)
    pub agent_tags: Option<&'a [String]>,
    /// Task's hierarchy level extracted from level:* tags (if available)
    pub task_level: Option<&'a str>,
    /// Number of direct children (contains deps) of the task (if available)
    pub child_count: Option<usize>,
}

impl<'a> PromptContext<'a> {
    /// Create a new prompt context with workflow information only.
    ///
    /// For backwards compatibility -- callers that don't have task/agent
    /// info can use this constructor. Use `with_task()` and `with_agent()`
    /// to add situational context.
    pub fn new(
        status: &'a str,
        phase: Option<&'a str>,
        states_config: &'a StatesConfig,
        phases_config: &'a PhasesConfig,
    ) -> Self {
        Self {
            status,
            phase,
            states_config,
            phases_config,
            task_id: None,
            task_title: None,
            task_priority: None,
            task_tags: None,
            agent_id: None,
            agent_role: None,
            agent_tags: None,
            task_level: None,
            child_count: None,
        }
    }

    /// Add task context to the prompt context.
    pub fn with_task(
        mut self,
        id: &'a str,
        title: &'a str,
        priority: i32,
        tags: &'a [String],
    ) -> Self {
        self.task_id = Some(id);
        self.task_title = Some(title);
        self.task_priority = Some(priority);
        self.task_tags = Some(tags);
        self
    }

    /// Add hierarchy level and child count context.
    pub fn with_level(mut self, level: Option<&'a str>, child_count: Option<usize>) -> Self {
        self.task_level = level;
        self.child_count = child_count;
        self
    }

    /// Add agent context to the prompt context.
    pub fn with_agent(
        mut self,
        agent_id: &'a str,
        role: Option<&'a str>,
        tags: &'a [String],
    ) -> Self {
        self.agent_id = Some(agent_id);
        self.agent_role = role;
        self.agent_tags = Some(tags);
        self
    }
}

/// Load a prompt by trigger name from WorkflowsConfig.
///
/// Returns None if no prompt exists for this trigger.
pub fn load_prompt(trigger: &str, workflows: &WorkflowsConfig) -> Option<String> {
    workflows.get_prompt(trigger).map(|s| s.to_string())
}

/// Expand template variables in a prompt string.
///
/// Supported variables:
///
/// **Workflow context:**
/// - `{{valid_exits}}` - markdown list of valid exit states
/// - `{{current_phase}}` - current phase or "(none)" if not set
/// - `{{valid_phases}}` - comma-separated list of valid phases
/// - `{{current_status}}` - current status name
///
/// **Task context** (available when task info is provided):
/// - `{{task_id}}` - task identifier
/// - `{{task_title}}` - task title
/// - `{{task_priority}}` - task priority (0-10)
/// - `{{task_tags}}` - comma-separated task tags
///
/// **Agent context** (available when agent info is provided):
/// - `{{agent_id}}` - agent/worker identifier
/// - `{{agent_role}}` - matched role name or "(none)"
/// - `{{agent_tags}}` - comma-separated agent tags
pub fn expand_prompt(content: &str, ctx: &PromptContext) -> String {
    let mut result = content.to_string();

    // === Workflow context ===

    // Expand {{current_status}}
    result = result.replace("{{current_status}}", ctx.status);

    // Expand {{valid_exits}}
    if result.contains("{{valid_exits}}") {
        let exits = ctx.states_config.get_exits(ctx.status);
        let exits_md = if exits.is_empty() {
            "- _(no transitions available - terminal state)_".to_string()
        } else {
            exits
                .iter()
                .map(|s| format!("- `{}`", s))
                .collect::<Vec<_>>()
                .join("\n")
        };
        result = result.replace("{{valid_exits}}", &exits_md);
    }

    // Expand {{current_phase}}
    if result.contains("{{current_phase}}") {
        let phase_str = ctx
            .phase
            .map(|p| format!("`{}`", p))
            .unwrap_or_else(|| "_(none)_".to_string());
        result = result.replace("{{current_phase}}", &phase_str);
    }

    // Expand {{valid_phases}}
    if result.contains("{{valid_phases}}") {
        let mut phases: Vec<&str> = ctx.phases_config.phase_names();
        phases.sort();
        let phases_str = phases.join(", ");
        result = result.replace("{{valid_phases}}", &phases_str);
    }

    // === Task context ===

    if result.contains("{{task_id}}") {
        let val = ctx.task_id.unwrap_or("_unknown_");
        result = result.replace("{{task_id}}", val);
    }

    if result.contains("{{task_title}}") {
        let val = ctx.task_title.unwrap_or("_untitled_");
        result = result.replace("{{task_title}}", val);
    }

    if result.contains("{{task_priority}}") {
        let val = ctx
            .task_priority
            .map(|p| p.to_string())
            .unwrap_or_else(|| "_unset_".to_string());
        result = result.replace("{{task_priority}}", &val);
    }

    if result.contains("{{task_tags}}") {
        let val = ctx
            .task_tags
            .map(|tags| {
                if tags.is_empty() {
                    "_(none)_".to_string()
                } else {
                    tags.join(", ")
                }
            })
            .unwrap_or_else(|| "_(none)_".to_string());
        result = result.replace("{{task_tags}}", &val);
    }

    // === Hierarchy context ===

    if result.contains("{{task_level}}") {
        let val = ctx.task_level.unwrap_or("_unset_");
        result = result.replace("{{task_level}}", val);
    }

    if result.contains("{{child_count}}") {
        let val = ctx
            .child_count
            .map(|c| c.to_string())
            .unwrap_or_else(|| "_unknown_".to_string());
        result = result.replace("{{child_count}}", &val);
    }

    // === Agent context ===

    if result.contains("{{agent_id}}") {
        let val = ctx.agent_id.unwrap_or("_unknown_");
        result = result.replace("{{agent_id}}", val);
    }

    if result.contains("{{agent_role}}") {
        let val = ctx
            .agent_role
            .map(|r| format!("`{}`", r))
            .unwrap_or_else(|| "_(none)_".to_string());
        result = result.replace("{{agent_role}}", &val);
    }

    if result.contains("{{agent_tags}}") {
        let val = ctx
            .agent_tags
            .map(|tags| {
                if tags.is_empty() {
                    "_(none)_".to_string()
                } else {
                    tags.join(", ")
                }
            })
            .unwrap_or_else(|| "_(none)_".to_string());
        result = result.replace("{{agent_tags}}", &val);
    }

    result
}

/// Get the list of triggers that should fire for a state transition.
///
/// Order: exits (specific → general), then enters (general → specific)
pub fn get_transition_triggers(
    old_status: &str,
    old_phase: Option<&str>,
    new_status: &str,
    new_phase: Option<&str>,
) -> Vec<String> {
    let mut triggers = Vec::new();

    let status_changed = old_status != new_status;
    let phase_changed = old_phase != new_phase;

    // === EXITS (specific → general) ===

    // Exit combo (if either changed and had a phase)
    if (status_changed || phase_changed)
        && old_phase.is_some()
        && let Some(op) = old_phase
    {
        triggers.push(format!("exit~{}%{}", old_status, op));
    }

    // Exit phase (if phase changed)
    if phase_changed && let Some(op) = old_phase {
        triggers.push(format!("exit%{}", op));
    }

    // Exit status (if status changed)
    if status_changed {
        triggers.push(format!("exit~{}", old_status));
    }

    // === ENTERS (general → specific) ===

    // Enter status (if status changed)
    if status_changed {
        triggers.push(format!("enter~{}", new_status));
    }

    // Enter phase (if phase changed)
    if phase_changed && let Some(np) = new_phase {
        triggers.push(format!("enter%{}", np));
    }

    // Enter combo (if either changed and has a phase)
    if (status_changed || phase_changed)
        && new_phase.is_some()
        && let Some(np) = new_phase
    {
        triggers.push(format!("enter~{}%{}", new_status, np));
    }

    triggers
}

/// Get all prompts that should be delivered for a state transition.
///
/// Returns a vector of prompt strings (caller concatenates as needed).
/// This version does NOT expand template variables - use `get_transition_prompts_with_context` for that.
pub fn get_transition_prompts(
    old_status: &str,
    old_phase: Option<&str>,
    new_status: &str,
    new_phase: Option<&str>,
    workflows: &WorkflowsConfig,
) -> Vec<String> {
    get_transition_triggers(old_status, old_phase, new_status, new_phase)
        .iter()
        .filter_map(|trigger| load_prompt(trigger, workflows))
        .collect()
}

/// Get all prompts that should be delivered for a state transition, with template expansion.
///
/// Returns a vector of prompt strings with template variables expanded.
pub fn get_transition_prompts_with_context(
    old_status: &str,
    old_phase: Option<&str>,
    new_status: &str,
    new_phase: Option<&str>,
    workflows: &WorkflowsConfig,
    ctx: &PromptContext,
) -> Vec<String> {
    get_transition_triggers(old_status, old_phase, new_status, new_phase)
        .iter()
        .filter_map(|trigger| load_prompt(trigger, workflows))
        .map(|content| expand_prompt(&content, ctx))
        .collect()
}

/// Derive a human-readable source label from a prompt trigger name.
///
/// Trigger naming convention:
/// - `enter~working` / `exit~working` -> `"state:working"`
/// - `enter%implement` / `exit%implement` -> `"phase:implement"`
/// - `enter~working%implement` / `exit~working%implement` -> `"combo:working+implement"`
fn trigger_to_source(trigger: &str) -> String {
    // Phase-only triggers: enter%phase / exit%phase
    if let Some(phase) = trigger.strip_prefix("enter%") {
        return format!("phase:{}", phase);
    }
    if let Some(phase) = trigger.strip_prefix("exit%") {
        return format!("phase:{}", phase);
    }

    // State or combo triggers: enter~state / exit~state / enter~state%phase / exit~state%phase
    let rest = trigger
        .strip_prefix("enter~")
        .or_else(|| trigger.strip_prefix("exit~"))
        .unwrap_or(trigger);

    if let Some(idx) = rest.find('%') {
        let state = &rest[..idx];
        let phase = &rest[idx + 1..];
        format!("combo:{}+{}", state, phase)
    } else {
        format!("state:{}", rest)
    }
}

/// Get all prompts with source attribution for a state transition, with template expansion.
///
/// Returns a vector of `AttributedPrompt` structs containing both the expanded
/// prompt text and a source label indicating where the prompt came from.
pub fn get_transition_prompts_attributed(
    old_status: &str,
    old_phase: Option<&str>,
    new_status: &str,
    new_phase: Option<&str>,
    workflows: &WorkflowsConfig,
    ctx: &PromptContext,
) -> Vec<AttributedPrompt> {
    get_transition_triggers(old_status, old_phase, new_status, new_phase)
        .iter()
        .filter_map(|trigger| {
            load_prompt(trigger, workflows).map(|content| AttributedPrompt {
                text: expand_prompt(&content, ctx),
                source: trigger_to_source(trigger),
            })
        })
        .collect()
}

/// List all available prompt triggers from the workflows config.
pub fn list_available_prompts(workflows: &WorkflowsConfig) -> Vec<String> {
    workflows.list_prompt_triggers()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_triggers_status_change_only() {
        let triggers = get_transition_triggers("pending", None, "working", None);
        assert_eq!(triggers, vec!["exit~pending", "enter~working"]);
    }

    #[test]
    fn test_triggers_phase_change_only() {
        let triggers =
            get_transition_triggers("working", Some("diagnose"), "working", Some("review"));
        assert_eq!(
            triggers,
            vec![
                "exit~working%diagnose",
                "exit%diagnose",
                "enter%review",
                "enter~working%review"
            ]
        );
    }

    #[test]
    fn test_triggers_both_change() {
        let triggers =
            get_transition_triggers("working", Some("diagnose"), "finished", Some("review"));
        assert_eq!(
            triggers,
            vec![
                "exit~working%diagnose",
                "exit%diagnose",
                "exit~working",
                "enter~finished",
                "enter%review",
                "enter~finished%review"
            ]
        );
    }

    #[test]
    fn test_triggers_enter_phase_from_none() {
        let triggers = get_transition_triggers("working", None, "working", Some("diagnose"));
        assert_eq!(triggers, vec!["enter%diagnose", "enter~working%diagnose"]);
    }

    #[test]
    fn test_triggers_exit_phase_to_none() {
        let triggers = get_transition_triggers("working", Some("diagnose"), "working", None);
        assert_eq!(triggers, vec!["exit~working%diagnose", "exit%diagnose"]);
    }

    #[test]
    fn test_no_triggers_when_unchanged() {
        let triggers =
            get_transition_triggers("working", Some("diagnose"), "working", Some("diagnose"));
        assert!(triggers.is_empty());
    }

    #[test]
    fn test_expand_prompt_valid_exits() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);

        let template = "From {{current_status}} you can go to:\n{{valid_exits}}";
        let result = expand_prompt(template, &ctx);

        assert!(result.contains("From working you can go to:"));
        assert!(result.contains("`completed`"));
        assert!(result.contains("`failed`"));
        assert!(result.contains("`pending`"));
    }

    #[test]
    fn test_expand_prompt_current_phase() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();

        // With a phase
        let ctx = PromptContext::new("working", Some("implement"), &states_config, &phases_config);
        let template = "Phase: {{current_phase}}";
        let result = expand_prompt(template, &ctx);
        assert_eq!(result, "Phase: `implement`");

        // Without a phase
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);
        let result = expand_prompt(template, &ctx);
        assert_eq!(result, "Phase: _(none)_");
    }

    #[test]
    fn test_expand_prompt_valid_phases() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);

        let template = "Phases: {{valid_phases}}";
        let result = expand_prompt(template, &ctx);

        // Should contain various default phases
        assert!(result.contains("implement"));
        assert!(result.contains("test"));
        assert!(result.contains("review"));
    }

    #[test]
    fn test_expand_prompt_terminal_state() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let ctx = PromptContext::new("cancelled", None, &states_config, &phases_config);

        let template = "Exits: {{valid_exits}}";
        let result = expand_prompt(template, &ctx);

        // Cancelled is a terminal state (no exits)
        assert!(result.contains("no transitions available"));
    }

    #[test]
    fn test_load_prompt_from_workflows() {
        let workflows = WorkflowsConfig::default();

        // Should find enter~working
        let prompt = load_prompt("enter~working", &workflows);
        assert!(prompt.is_some());
        assert!(prompt.unwrap().contains("actively working"));

        // Should find enter%implement
        let prompt = load_prompt("enter%implement", &workflows);
        assert!(prompt.is_some());
        assert!(prompt.unwrap().contains("Implementation"));
    }

    #[test]
    fn test_get_transition_prompts() {
        let workflows = WorkflowsConfig::default();

        let prompts = get_transition_prompts("pending", None, "working", None, &workflows);

        // Should have at least the enter~working prompt
        assert!(!prompts.is_empty());
        assert!(prompts.iter().any(|p| p.contains("actively working")));
    }

    #[test]
    fn test_list_available_prompts() {
        let workflows = WorkflowsConfig::default();
        let prompts = list_available_prompts(&workflows);

        assert!(prompts.contains(&"enter~working".to_string()));
        assert!(prompts.contains(&"exit~working".to_string()));
        assert!(prompts.contains(&"enter%implement".to_string()));
    }

    // === Tests for context-sensitive template variables ===

    #[test]
    fn test_expand_prompt_task_context() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let tags = vec!["backend".to_string(), "api".to_string()];
        let ctx = PromptContext::new("working", Some("implement"), &states_config, &phases_config)
            .with_task("fix-auth-bug", "Fix authentication bypass", 8, &tags);

        let template = "Working on {{task_id}}: {{task_title}} (priority {{task_priority}}, tags: {{task_tags}})";
        let result = expand_prompt(template, &ctx);

        assert_eq!(
            result,
            "Working on fix-auth-bug: Fix authentication bypass (priority 8, tags: backend, api)"
        );
    }

    #[test]
    fn test_expand_prompt_task_context_empty_tags() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let tags: Vec<String> = vec![];
        let ctx = PromptContext::new("working", None, &states_config, &phases_config).with_task(
            "my-task",
            "Some task",
            5,
            &tags,
        );

        let template = "Tags: {{task_tags}}";
        let result = expand_prompt(template, &ctx);

        assert_eq!(result, "Tags: _(none)_");
    }

    #[test]
    fn test_expand_prompt_task_context_missing() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        // No with_task() call - should use fallbacks
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);

        let template = "Task: {{task_id}} / {{task_title}} / {{task_priority}} / {{task_tags}}";
        let result = expand_prompt(template, &ctx);

        assert_eq!(result, "Task: _unknown_ / _untitled_ / _unset_ / _(none)_");
    }

    #[test]
    fn test_expand_prompt_agent_context() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let agent_tags = vec!["worker".to_string(), "implement".to_string()];
        let ctx = PromptContext::new("working", None, &states_config, &phases_config).with_agent(
            "worker-21",
            Some("worker"),
            &agent_tags,
        );

        let template = "Agent {{agent_id}} (role: {{agent_role}}, tags: {{agent_tags}})";
        let result = expand_prompt(template, &ctx);

        assert_eq!(
            result,
            "Agent worker-21 (role: `worker`, tags: worker, implement)"
        );
    }

    #[test]
    fn test_expand_prompt_agent_context_no_role() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let agent_tags = vec!["generic".to_string()];
        let ctx = PromptContext::new("working", None, &states_config, &phases_config).with_agent(
            "worker-5",
            None,
            &agent_tags,
        );

        let template = "Role: {{agent_role}}";
        let result = expand_prompt(template, &ctx);

        assert_eq!(result, "Role: _(none)_");
    }

    #[test]
    fn test_expand_prompt_agent_context_missing() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        // No with_agent() call
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);

        let template = "{{agent_id}} / {{agent_role}} / {{agent_tags}}";
        let result = expand_prompt(template, &ctx);

        assert_eq!(result, "_unknown_ / _(none)_ / _(none)_");
    }

    #[test]
    fn test_expand_prompt_combined_context() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let task_tags = vec!["design".to_string()];
        let agent_tags = vec!["worker".to_string(), "design".to_string()];
        let ctx = PromptContext::new("working", Some("design"), &states_config, &phases_config)
            .with_task(
                "prompt-guidance",
                "Context-sensitive prompts",
                7,
                &task_tags,
            )
            .with_agent("worker-21", Some("worker"), &agent_tags);

        let template = "{{agent_id}} is working on {{task_id}} in phase {{current_phase}} with status {{current_status}}";
        let result = expand_prompt(template, &ctx);

        assert_eq!(
            result,
            "worker-21 is working on prompt-guidance in phase `design` with status working"
        );
    }

    #[test]
    fn test_prompt_context_builder_pattern() {
        let states_config = StatesConfig::default();
        let phases_config = PhasesConfig::default();
        let task_tags = vec![];
        let agent_tags = vec!["worker".to_string()];

        // Verify builder pattern works correctly
        let ctx = PromptContext::new("pending", None, &states_config, &phases_config)
            .with_task("t1", "Title", 5, &task_tags)
            .with_agent("w1", Some("worker"), &agent_tags);

        assert_eq!(ctx.task_id, Some("t1"));
        assert_eq!(ctx.task_title, Some("Title"));
        assert_eq!(ctx.task_priority, Some(5));
        assert_eq!(ctx.agent_id, Some("w1"));
        assert_eq!(ctx.agent_role, Some("worker"));
    }

    // === Tests for source attribution ===

    #[test]
    fn test_trigger_to_source_state() {
        assert_eq!(trigger_to_source("enter~working"), "state:working");
        assert_eq!(trigger_to_source("exit~pending"), "state:pending");
    }

    #[test]
    fn test_trigger_to_source_phase() {
        assert_eq!(trigger_to_source("enter%implement"), "phase:implement");
        assert_eq!(trigger_to_source("exit%review"), "phase:review");
    }

    #[test]
    fn test_trigger_to_source_combo() {
        assert_eq!(
            trigger_to_source("enter~working%implement"),
            "combo:working+implement"
        );
        assert_eq!(
            trigger_to_source("exit~working%review"),
            "combo:working+review"
        );
    }

    #[test]
    fn test_get_transition_prompts_attributed() {
        let workflows = WorkflowsConfig::default();
        let states_config: StatesConfig = (&workflows).into();
        let phases_config: PhasesConfig = (&workflows).into();
        let ctx = PromptContext::new("working", None, &states_config, &phases_config);

        let attributed =
            get_transition_prompts_attributed("pending", None, "working", None, &workflows, &ctx);

        // Should have at least the enter~working prompt
        assert!(!attributed.is_empty());
        assert!(
            attributed
                .iter()
                .any(|p| p.text.contains("actively working") && p.source == "state:working")
        );
    }

    #[test]
    fn test_attributed_prompts_phase_change() {
        let workflows = WorkflowsConfig::default();
        let states_config: StatesConfig = (&workflows).into();
        let phases_config: PhasesConfig = (&workflows).into();
        let ctx = PromptContext::new("working", Some("implement"), &states_config, &phases_config);

        let attributed = get_transition_prompts_attributed(
            "working",
            None,
            "working",
            Some("implement"),
            &workflows,
            &ctx,
        );

        // Should have prompts for entering implement phase
        if !attributed.is_empty() {
            // If there's an implement phase prompt, it should be attributed to phase:implement
            for p in &attributed {
                assert!(
                    p.source.starts_with("phase:")
                        || p.source.starts_with("combo:")
                        || p.source.starts_with("state:"),
                    "source should have a valid prefix, got: {}",
                    p.source
                );
            }
        }
    }
}