05_with_goals/
05_with_goals.rs

1//! Goal-Based Agent Example
2//!
3//! This example demonstrates how to use goals with the Ceylon Agent to:
4//! - Break down complex tasks into structured goals
5//! - Define success criteria
6//! - Track progress through sub-goals
7//! - Monitor goal completion and status
8//!
9//! Goals help agents understand what success looks like and work systematically
10//! toward achieving objectives with clear milestones and criteria.
11//!
12//! Run with: cargo run --example 05_with_goals --manifest-path ceylon/Cargo.toml
13
14use ceylon_next::agent::Agent;
15use ceylon_next::goal::{Goal, GoalAnalysis, GoalStatus};
16use ceylon_next::tasks::TaskRequest;
17
18// ============================================
19// Example 1: Manual Goal Creation
20// ============================================
21
22async fn example_1_manual_goal() {
23    println!("=== Example 1: Manual Goal Creation ===\n");
24
25    // Create an agent
26    let mut agent = Agent::new("MealPlanner", "ollama::gemma3:latest");
27
28    // Create a goal manually for a complex task
29    let mut goal = Goal::new(
30        "Plan a healthy meal prep for the week".to_string()
31    );
32
33    // Define what success looks like
34    println!("šŸ“‹ Setting success criteria...");
35    goal.add_criterion("7 breakfast recipes selected".to_string());
36    goal.add_criterion("7 lunch recipes selected".to_string());
37    goal.add_criterion("7 dinner recipes selected".to_string());
38    goal.add_criterion("Shopping list created".to_string());
39    goal.add_criterion("Prep schedule created".to_string());
40
41    // Break down into steps (sub-goals)
42    println!("šŸŽÆ Breaking down into sub-goals...\n");
43    goal.add_sub_goal("Ask user about dietary preferences".to_string(), 0);
44    goal.add_sub_goal("Ask about time available for prep".to_string(), 1);
45    goal.add_sub_goal("Suggest breakfast options".to_string(), 2);
46    goal.add_sub_goal("Suggest lunch options".to_string(), 3);
47    goal.add_sub_goal("Suggest dinner options".to_string(), 4);
48    goal.add_sub_goal("Create shopping list".to_string(), 5);
49    goal.add_sub_goal("Create prep schedule".to_string(), 6);
50
51    // Start working on the goal
52    goal.status = GoalStatus::InProgress;
53
54    // Set the goal on the agent
55    agent.set_goal(goal.clone());
56
57    // Create a task aligned with the goal
58    let task = TaskRequest::new("I need help with meal planning");
59
60    // Run the agent
61    println!("ā³ Agent is working on the meal planning task...\n");
62    let _response = agent.run(task).await;
63
64    // Show the goal summary
65    println!("\nšŸ“Š Goal Summary:");
66    println!("{}", goal.get_summary());
67
68    println!("\nāœ… Example 1 completed!\n");
69}
70
71// ============================================
72// Example 2: Goal Progress Tracking
73// ============================================
74
75async fn example_2_goal_progress_tracking() {
76    println!("\n=== Example 2: Goal Progress Tracking ===\n");
77
78    // Create a goal for a project
79    let mut goal = Goal::new(
80        "Create a project plan for building a mobile app".to_string()
81    );
82
83    // Add success criteria
84    goal.add_criterion("Project requirements documented".to_string());
85    goal.add_criterion("Timeline created with milestones".to_string());
86    goal.add_criterion("Resource allocation plan completed".to_string());
87    goal.add_criterion("Risk assessment performed".to_string());
88
89    // Add sub-goals
90    goal.add_sub_goal("Gather stakeholder requirements".to_string(), 0);
91    goal.add_sub_goal("Define project scope".to_string(), 1);
92    goal.add_sub_goal("Create development timeline".to_string(), 2);
93    goal.add_sub_goal("Allocate resources".to_string(), 3);
94    goal.add_sub_goal("Identify risks and mitigation strategies".to_string(), 4);
95
96    goal.status = GoalStatus::InProgress;
97
98    // Simulate progress through the goal
99    println!("šŸ“ˆ Tracking goal progress...\n");
100
101    // Complete first sub-goal
102    println!("Step 1: Gathering requirements");
103    goal.complete_sub_goal(0, Some("Interviewed 5 stakeholders".to_string()));
104    goal.mark_criterion_met(0, "Requirements documented".to_string());
105    println!("  Progress: {}%\n", goal.get_progress());
106
107    // Complete second sub-goal
108    println!("Step 2: Defining scope");
109    goal.complete_sub_goal(1, Some("Scope document created".to_string()));
110    println!("  Progress: {}%\n", goal.get_progress());
111
112    // Complete third sub-goal
113    println!("Step 3: Creating timeline");
114    goal.complete_sub_goal(2, Some("12-month timeline with milestones".to_string()));
115    goal.mark_criterion_met(1, "Timeline created".to_string());
116    println!("  Progress: {}%\n", goal.get_progress());
117
118    // Complete fourth sub-goal
119    println!("Step 4: Allocating resources");
120    goal.complete_sub_goal(3, Some("Resource allocation table created".to_string()));
121    goal.mark_criterion_met(2, "Resources allocated".to_string());
122    println!("  Progress: {}%\n", goal.get_progress());
123
124    // Complete fifth sub-goal
125    println!("Step 5: Assessing risks");
126    goal.complete_sub_goal(4, Some("Risk register created with 8 identified risks".to_string()));
127    goal.mark_criterion_met(3, "Risks identified".to_string());
128    println!("  Progress: {}%\n", goal.get_progress());
129
130    // Show final status
131    println!("\nšŸ“Š Final Goal Status:");
132    println!("{}", goal.get_summary());
133
134    println!("\nāœ… Example 2 completed!\n");
135}
136
137// ============================================
138// Example 3: Job Interview Preparation Goal
139// ============================================
140
141async fn example_3_interview_preparation() {
142    println!("\n=== Example 3: Job Interview Preparation Goal ===\n");
143
144    let mut agent = Agent::new("InterviewCoach", "ollama::gemma3:latest");
145
146    // Create a structured goal for interview prep
147    let mut goal = Goal::new(
148        "Prepare for a senior software engineer interview at a tech company".to_string()
149    );
150
151    // Define success criteria
152    println!("šŸŽÆ Success criteria:");
153    goal.add_criterion("Technical topics reviewed (algorithms, data structures, system design)".to_string());
154    goal.add_criterion("Behavioral questions prepared with STAR method examples".to_string());
155    goal.add_criterion("Company research completed".to_string());
156    goal.add_criterion("Practice mock interview conducted".to_string());
157    goal.add_criterion("Questions to ask the interviewer prepared".to_string());
158
159    for criterion in &goal.success_criteria {
160        println!("  • {}", criterion.description);
161    }
162
163    // Define steps
164    println!("\nšŸ“‹ Steps to take:");
165    goal.add_sub_goal("Review core algorithms and data structures".to_string(), 0);
166    goal.add_sub_goal("Study system design patterns".to_string(), 1);
167    goal.add_sub_goal("Prepare STAR method stories from past projects".to_string(), 2);
168    goal.add_sub_goal("Research company background and culture".to_string(), 3);
169    goal.add_sub_goal("Practice mock interview with a friend".to_string(), 4);
170    goal.add_sub_goal("Prepare thoughtful questions about the role".to_string(), 5);
171
172    for sub_goal in &goal.sub_goals {
173        println!("  {}. {}", sub_goal.priority + 1, sub_goal.description);
174    }
175
176    goal.status = GoalStatus::InProgress;
177
178    // Set goal on agent
179    agent.set_goal(goal.clone());
180
181    // Create related task
182    let task = TaskRequest::new("Help me prepare for my senior engineer interview");
183
184    println!("\nā³ Agent is creating interview preparation plan...\n");
185    let _response = agent.run(task).await;
186
187    println!("\nšŸ“Š Goal Summary:");
188    println!("{}", goal.get_summary());
189
190    println!("\nāœ… Example 3 completed!\n");
191}
192
193// ============================================
194// Example 4: Goal Analysis from Task Description
195// ============================================
196
197fn example_4_goal_analysis() {
198    println!("\n=== Example 4: Goal Analysis from Task Description ===\n");
199
200    // Simulate LLM analyzing a task and breaking it down into a goal
201    let task_description = "Help me learn Python programming";
202
203    println!("šŸ“ Original task: \"{}\"", task_description);
204    println!("\nšŸ” LLM analyzing task...\n");
205
206    // This is what the LLM would return
207    let analysis = GoalAnalysis {
208        main_goal: "Help user learn Python programming from basics to practical skills".to_string(),
209        success_criteria: vec![
210            "User's current skill level identified".to_string(),
211            "Learning path created based on skill level".to_string(),
212            "Resources (tutorials, books) provided".to_string(),
213            "Practice exercises suggested".to_string(),
214            "Study schedule created".to_string(),
215        ],
216        sub_goals: vec![
217            "Ask about current programming experience".to_string(),
218            "Identify learning goals (web dev, data science, etc)".to_string(),
219            "Create structured learning path".to_string(),
220            "Recommend learning resources".to_string(),
221            "Suggest practice projects".to_string(),
222            "Create study timeline".to_string(),
223        ],
224    };
225
226    // Convert analysis to a Goal
227    let goal = analysis.to_goal();
228
229    println!("āœ… Goal created from analysis:\n");
230    println!("{}", goal.get_summary());
231
232    println!("\nāœ… Example 4 completed!\n");
233}
234
235// ============================================
236// Example 5: Goal Completion Verification
237// ============================================
238
239async fn example_5_goal_completion() {
240    println!("\n=== Example 5: Goal Completion Verification ===\n");
241
242    let mut goal = Goal::new("Plan a birthday party".to_string());
243
244    // Set up success criteria
245    goal.add_criterion("Guest list created".to_string());
246    goal.add_criterion("Venue booked".to_string());
247    goal.add_criterion("Food ordered".to_string());
248    goal.add_criterion("Decorations purchased".to_string());
249
250    // Set up sub-goals
251    goal.add_sub_goal("Ask about guests".to_string(), 0);
252    goal.add_sub_goal("Choose and book venue".to_string(), 1);
253    goal.add_sub_goal("Order food".to_string(), 2);
254    goal.add_sub_goal("Purchase decorations".to_string(), 3);
255
256    goal.status = GoalStatus::InProgress;
257
258    println!("šŸŽ‰ Birthday party planning task started\n");
259    println!("Initial progress: {}%\n", goal.get_progress());
260
261    // Simulate completing tasks
262    println!("Working through sub-goals:\n");
263
264    // Task 1
265    println!("āœ“ Contacted 15 friends and family members");
266    goal.complete_sub_goal(0, Some("Got 15 confirmations".to_string()));
267    goal.mark_criterion_met(0, "List of 15 guests confirmed".to_string());
268    println!("  Progress: {}%", goal.get_progress());
269
270    // Task 2
271    println!("āœ“ Booked the community center for Saturday");
272    goal.complete_sub_goal(1, Some("Community center reserved for 6pm".to_string()));
273    goal.mark_criterion_met(1, "Community center booking confirmed".to_string());
274    println!("  Progress: {}%", goal.get_progress());
275
276    // Task 3
277    println!("āœ“ Ordered pizza and drinks for 15 people");
278    goal.complete_sub_goal(2, Some("Pizza and drinks ordered".to_string()));
279    goal.mark_criterion_met(2, "Food catering arranged".to_string());
280    println!("  Progress: {}%", goal.get_progress());
281
282    // Task 4
283    println!("āœ“ Bought balloons, streamers, and table decorations");
284    goal.complete_sub_goal(3, Some("All decorations purchased".to_string()));
285    goal.mark_criterion_met(3, "Decorations ready".to_string());
286    println!("  Progress: {}%\n", goal.get_progress());
287
288    // Check completion
289    if goal.is_successful() {
290        println!("šŸŽŠ All success criteria met!");
291        goal.status = GoalStatus::Completed;
292    }
293
294    if goal.all_sub_goals_complete() {
295        println!("āœ… All sub-goals completed!");
296    }
297
298    println!("\nFinal Status:");
299    println!("  Status: {:?}", goal.status);
300    println!("  All criteria met: {}", goal.is_successful());
301    println!("  Progress: {}%\n", goal.get_progress());
302
303    println!("šŸ“Š Final Summary:");
304    println!("{}", goal.get_summary());
305
306    println!("\nāœ… Example 5 completed!\n");
307}
308
309// ============================================
310// Example 6: Complex Multi-Step Project
311// ============================================
312
313async fn example_6_complex_project() {
314    println!("\n=== Example 6: Complex Multi-Step Project Goal ===\n");
315
316    let mut goal = Goal::new(
317        "Launch a new web application product".to_string()
318    );
319
320    // Success criteria
321    goal.add_criterion("Technical architecture designed and documented".to_string());
322    goal.add_criterion("Frontend and backend development completed".to_string());
323    goal.add_criterion("Testing completed (unit, integration, E2E)".to_string());
324    goal.add_criterion("Deployment pipeline set up".to_string());
325    goal.add_criterion("Marketing materials prepared".to_string());
326    goal.add_criterion("Team trained on deployment and support".to_string());
327
328    // Sub-goals in order
329    goal.add_sub_goal("Define technical requirements and architecture".to_string(), 0);
330    goal.add_sub_goal("Set up development environment and CI/CD".to_string(), 1);
331    goal.add_sub_goal("Develop backend API endpoints".to_string(), 2);
332    goal.add_sub_goal("Build frontend user interface".to_string(), 3);
333    goal.add_sub_goal("Write comprehensive test suite".to_string(), 4);
334    goal.add_sub_goal("Conduct security audit".to_string(), 5);
335    goal.add_sub_goal("Set up monitoring and logging".to_string(), 6);
336    goal.add_sub_goal("Deploy to staging environment".to_string(), 7);
337    goal.add_sub_goal("Perform final testing and QA".to_string(), 8);
338    goal.add_sub_goal("Create deployment documentation".to_string(), 9);
339    goal.add_sub_goal("Train support team".to_string(), 10);
340    goal.add_sub_goal("Deploy to production".to_string(), 11);
341
342    goal.status = GoalStatus::InProgress;
343
344    println!("šŸš€ Web Application Product Launch Plan\n");
345    println!("Total steps: {}\n", goal.sub_goals.len());
346
347    // Simulate progress
348    let completed_steps = vec![
349        (0, "Architecture documented with diagrams"),
350        (1, "GitHub Actions CI/CD configured"),
351        (2, "All 15 API endpoints implemented and tested"),
352        (3, "React frontend with all pages completed"),
353        (4, "Jest test suite with 85% coverage"),
354        (5, "No critical vulnerabilities found"),
355        (6, "Prometheus and ELK stack configured"),
356        (7, "Successfully deployed to staging"),
357        (8, "UAT passed with stakeholders"),
358        (9, "Deployment runbook created"),
359        (10, "Support team completed training"),
360    ];
361
362    for (index, notes) in completed_steps {
363        goal.complete_sub_goal(index, Some(notes.to_string()));
364    }
365
366    // Mark success criteria as met
367    goal.mark_criterion_met(0, "System design document completed".to_string());
368    goal.mark_criterion_met(1, "All features implemented and tested".to_string());
369    goal.mark_criterion_met(2, "85% test coverage achieved".to_string());
370    goal.mark_criterion_met(3, "GitHub Actions and monitoring configured".to_string());
371    goal.mark_criterion_met(4, "Marketing deck prepared".to_string());
372    goal.mark_criterion_met(5, "Team completed deployment training".to_string());
373
374    println!("šŸ“ˆ Project Progress:\n");
375    println!("Overall Progress: {}%\n", goal.get_progress());
376
377    println!("Remaining tasks:");
378    if let Some(next) = goal.get_next_sub_goal() {
379        println!("  • {}", next.description);
380    }
381
382    println!("\nšŸ“Š Status Summary:");
383    println!("{}", goal.get_summary());
384
385    if goal.get_progress() == 100 {
386        println!("\nāœ… All sub-goals completed!");
387        if goal.is_successful() {
388            println!("šŸŽ‰ All success criteria met!");
389            println!("Ready to mark goal as Completed!");
390        }
391    }
392
393    println!("\nāœ… Example 6 completed!\n");
394}
395
396// ============================================
397// Main function to run examples
398// ============================================
399
400#[tokio::main]
401async fn main() {
402    println!("šŸŽÆ Ceylon Agent - Goal-Based Examples\n");
403    println!("This example demonstrates how to structure tasks as goals,");
404    println!("break them into sub-goals, and track progress.\n");
405    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
406
407    // Run examples
408    example_1_manual_goal().await;
409    example_2_goal_progress_tracking().await;
410    example_3_interview_preparation().await;
411    example_4_goal_analysis();
412    example_5_goal_completion().await;
413    example_6_complex_project().await;
414
415    println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
416    println!("\nāœ… All goal-based examples completed successfully!\n");
417
418    println!("šŸ“š Key Takeaways:");
419    println!("  1. Goals provide structure to complex tasks");
420    println!("  2. Success criteria define what \"done\" looks like");
421    println!("  3. Sub-goals break work into manageable steps");
422    println!("  4. Progress tracking helps monitor completion");
423    println!("  5. Goal status helps coordinate multi-step workflows\n");
424
425    println!("šŸ”— Next steps:");
426    println!("  • Combine goals with tools for autonomous task execution");
427    println!("  • Use goal analysis to break down user requests automatically");
428    println!("  • Integrate goal progress into agent memory for context\n");
429}
430
431/*
432
433KEY CONCEPTS:
434
4351. GOAL STRUCTURE
436   ā”œā”€ Main Goal: What you're trying to achieve
437   ā”œā”€ Success Criteria: How to know when you're done (2-5 items)
438   └─ Sub-Goals: Steps to achieve the goal (prioritized, ordered)
439
4402. GOAL STATUS
441   • NotStarted: Just created
442   • InProgress: Currently working on it
443   • Completed: Successfully finished
444   • Failed: Could not complete
445   • Cancelled: User stopped it
446
4473. PROGRESS TRACKING
448   • get_progress(): Returns 0-100% based on sub-goals completed
449   • get_next_sub_goal(): Shows what to work on next
450   • is_successful(): All criteria met?
451   • all_sub_goals_complete(): All steps done?
452
4534. WHEN TO USE GOALS
454   āœ“ Complex tasks with multiple steps
455   āœ“ Multi-part projects
456   āœ“ Tasks requiring user interaction
457   āœ“ When you need clear milestones
458   āœ“ When you want to track progress
459
4605. BENEFITS
461   • Clear understanding of task scope
462   • Systematic progress through complex work
463   • Easy to track what's done vs pending
464   • Better user communication
465   • Deterministic completion criteria
466
467*/