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
|
//! Learning injection for enhanced task prompts.
//!
//! This module implements Ralph-inspired learning injection into Claude prompts.
//! It prepends context recovery information and recent learnings to base prompts,
//! enabling cross-task learning and context preservation.
//!
//! The injection includes:
//! - Context recovery info (branch, git status, last checkpoint, recent progress)
//! - Previous learnings from progress log (patterns, gotchas, tips)
//!
//! Output format:
//! ```markdown
//! ## Context Recovery
//! [from context_recovery.rs]
//!
//! ## Previous Learnings
//! These patterns were discovered in previous iterations:
//! - Pattern: Always run typecheck before commit
//! - Gotcha: Remember to update imports when moving files
//! - Tip: Use the existing helper in utils.rs
//!
//! ---
//! [Original task prompt follows]
//! ```
use std::path::Path;
use regex::Regex;
use super::context_recovery::{self, ContextRecoveryInfo};
use super::progress_log::{self, Learning};
use super::ManagedTask;
/// Default maximum number of learning entries to inject into prompts.
const DEFAULT_MAX_ENTRIES_INJECTED: usize = 20;
/// Error type for learning injection operations.
#[derive(Debug, thiserror::Error)]
pub enum LearningInjectionError {
#[error("Context recovery error: {0}")]
ContextRecovery(#[from] context_recovery::ContextRecoveryError),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
/// Configuration for learning injection.
#[derive(Debug, Clone)]
pub struct LearningInjector {
/// Maximum number of learning entries to inject into prompts.
pub max_entries_injected: usize,
/// Whether to include context recovery information in the prompt.
pub include_context_recovery: bool,
}
impl Default for LearningInjector {
fn default() -> Self {
Self {
max_entries_injected: DEFAULT_MAX_ENTRIES_INJECTED,
include_context_recovery: true,
}
}
}
impl LearningInjector {
/// Create a new LearningInjector with default settings.
pub fn new() -> Self {
Self::default()
}
/// Set the maximum number of entries to inject.
pub fn with_max_entries(mut self, max_entries: usize) -> Self {
self.max_entries_injected = max_entries;
self
}
/// Set whether to include context recovery.
pub fn with_context_recovery(mut self, include: bool) -> Self {
self.include_context_recovery = include;
self
}
/// Inject learnings and context recovery into a base prompt.
///
/// This function:
/// 1. Prepends context recovery info (if enabled)
/// 2. Prepends recent learnings from progress log
/// 3. Returns the enhanced prompt
///
/// # Arguments
/// * `worktree_path` - Path to the task's worktree directory
/// * `task` - The managed task struct
/// * `base_prompt` - The original task prompt to enhance
///
/// # Returns
/// Enhanced prompt with context and learnings prepended.
pub async fn inject_learnings(
&self,
worktree_path: &Path,
task: &ManagedTask,
base_prompt: &str,
) -> Result<String, LearningInjectionError> {
let mut enhanced_prompt = String::new();
// Add context recovery if enabled
if self.include_context_recovery {
let context_info = context_recovery::build_context_recovery(worktree_path, task).await?;
enhanced_prompt.push_str(&context_info.to_markdown());
enhanced_prompt.push('\n');
}
// Gather learnings from recent progress log entries
let learnings = self.gather_learnings(worktree_path)?;
// Add learnings section if there are any
if !learnings.is_empty() {
enhanced_prompt.push_str(&self.format_learnings_section(&learnings));
enhanced_prompt.push('\n');
}
// Add separator before original prompt (if we added any content)
if !enhanced_prompt.is_empty() {
enhanced_prompt.push_str("---\n\n");
}
// Append the original prompt
enhanced_prompt.push_str(base_prompt);
Ok(enhanced_prompt)
}
/// Gather learnings from recent progress log entries.
///
/// Reads the progress log and extracts unique learnings up to the
/// configured maximum number of entries.
fn gather_learnings(&self, worktree_path: &Path) -> Result<Vec<Learning>, LearningInjectionError> {
// Read enough entries to potentially have max_entries_injected learnings
// Since each entry may have multiple learnings, we read more entries
let entries = progress_log::read_recent_entries(worktree_path, self.max_entries_injected * 2)?;
let mut learnings = Vec::new();
let mut seen_descriptions = std::collections::HashSet::new();
// Iterate in reverse to get most recent learnings first
for entry in entries.iter().rev() {
for learning in &entry.learnings {
// Deduplicate by description
if !seen_descriptions.contains(&learning.description) {
seen_descriptions.insert(learning.description.clone());
learnings.push(learning.clone());
if learnings.len() >= self.max_entries_injected {
break;
}
}
}
if learnings.len() >= self.max_entries_injected {
break;
}
}
Ok(learnings)
}
/// Format the learnings section for prompt injection.
fn format_learnings_section(&self, learnings: &[Learning]) -> String {
let mut section = String::new();
section.push_str("## Previous Learnings\n");
section.push_str("These patterns were discovered in previous iterations:\n");
for learning in learnings {
section.push_str(&format!("- {}: {}\n", learning.kind, learning.description));
}
section
}
}
/// Extract learnings from Claude output text.
///
/// Parses Claude output looking for learning patterns marked with:
/// - LEARNING: Description of what was learned
/// - PATTERN: A reusable pattern discovered
/// - GOTCHA: Something to watch out for
/// - TIP: A helpful suggestion
///
/// # Arguments
/// * `output` - The Claude output text to parse
///
/// # Returns
/// Vector of learnings extracted from the output.
pub fn extract_learnings_from_output(output: &str) -> Vec<Learning> {
let mut learnings = Vec::new();
// Patterns to look for in Claude output
// Format: MARKER: description text (until end of line or next marker)
let patterns = [
("LEARNING", "Learning"),
("PATTERN", "Pattern"),
("GOTCHA", "Gotcha"),
("TIP", "Tip"),
];
for line in output.lines() {
let trimmed = line.trim();
for (marker, kind) in &patterns {
// Check for "MARKER:" at start of line (case-insensitive)
let pattern_prefix = format!("{}:", marker);
if trimmed.to_uppercase().starts_with(&pattern_prefix) {
// Extract the description after the marker
let description = trimmed[pattern_prefix.len()..].trim();
if !description.is_empty() {
learnings.push(Learning {
kind: kind.to_string(),
description: description.to_string(),
});
}
}
// Also check for "**MARKER:**" markdown bold format
let bold_prefix = format!("**{}:**", marker);
let bold_prefix_upper = format!("**{}:**", marker.to_uppercase());
if trimmed.starts_with(&bold_prefix) || trimmed.starts_with(&bold_prefix_upper) {
let prefix_len = if trimmed.starts_with(&bold_prefix) {
bold_prefix.len()
} else {
bold_prefix_upper.len()
};
let description = trimmed[prefix_len..].trim().trim_end_matches("**").trim();
if !description.is_empty() {
learnings.push(Learning {
kind: kind.to_string(),
description: description.to_string(),
});
}
}
}
}
// Also look for learnings in code blocks or structured output
// Example: `LEARNING: description` or within markdown bullets
let bullet_regex = Regex::new(r"^[-*]\s*(LEARNING|PATTERN|GOTCHA|TIP):\s*(.+)$").unwrap();
for line in output.lines() {
let trimmed = line.trim();
if let Some(captures) = bullet_regex.captures(trimmed) {
let marker = captures.get(1).map(|m| m.as_str()).unwrap_or("");
let description = captures.get(2).map(|m| m.as_str()).unwrap_or("").trim();
if !description.is_empty() {
let kind = match marker.to_uppercase().as_str() {
"LEARNING" => "Learning",
"PATTERN" => "Pattern",
"GOTCHA" => "Gotcha",
"TIP" => "Tip",
_ => continue,
};
// Check for duplicates before adding
let already_exists = learnings
.iter()
.any(|l| l.kind == kind && l.description == description);
if !already_exists {
learnings.push(Learning {
kind: kind.to_string(),
description: description.to_string(),
});
}
}
}
}
learnings
}
/// Convenience function to inject learnings with default settings.
///
/// This is a simpler interface for common use cases.
pub async fn inject_learnings(
worktree_path: &Path,
task: &ManagedTask,
base_prompt: &str,
) -> Result<String, LearningInjectionError> {
LearningInjector::default()
.inject_learnings(worktree_path, task, base_prompt)
.await
}
/// Convenience function to inject learnings with context recovery info provided.
///
/// Use this when you already have context recovery info computed to avoid
/// recomputing it.
pub fn inject_learnings_with_context(
worktree_path: &Path,
context_info: Option<&ContextRecoveryInfo>,
base_prompt: &str,
max_entries: usize,
) -> Result<String, LearningInjectionError> {
let mut enhanced_prompt = String::new();
// Add context recovery if provided
if let Some(info) = context_info {
enhanced_prompt.push_str(&info.to_markdown());
enhanced_prompt.push('\n');
}
// Gather learnings from recent progress log entries
let entries = progress_log::read_recent_entries(worktree_path, max_entries * 2)?;
let mut learnings = Vec::new();
let mut seen_descriptions = std::collections::HashSet::new();
for entry in entries.iter().rev() {
for learning in &entry.learnings {
if !seen_descriptions.contains(&learning.description) {
seen_descriptions.insert(learning.description.clone());
learnings.push(learning.clone());
if learnings.len() >= max_entries {
break;
}
}
}
if learnings.len() >= max_entries {
break;
}
}
// Add learnings section if there are any
if !learnings.is_empty() {
enhanced_prompt.push_str("## Previous Learnings\n");
enhanced_prompt.push_str("These patterns were discovered in previous iterations:\n");
for learning in &learnings {
enhanced_prompt.push_str(&format!("- {}: {}\n", learning.kind, learning.description));
}
enhanced_prompt.push('\n');
}
// Add separator before original prompt (if we added any content)
if !enhanced_prompt.is_empty() {
enhanced_prompt.push_str("---\n\n");
}
// Append the original prompt
enhanced_prompt.push_str(base_prompt);
Ok(enhanced_prompt)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_learning_injector_default() {
let injector = LearningInjector::default();
assert_eq!(injector.max_entries_injected, DEFAULT_MAX_ENTRIES_INJECTED);
assert!(injector.include_context_recovery);
}
#[test]
fn test_learning_injector_builder() {
let injector = LearningInjector::new()
.with_max_entries(10)
.with_context_recovery(false);
assert_eq!(injector.max_entries_injected, 10);
assert!(!injector.include_context_recovery);
}
#[test]
fn test_extract_learnings_basic() {
let output = r#"
I discovered some useful patterns during this work.
LEARNING: Always check if the file exists before reading
PATTERN: Use async/await for IO operations
GOTCHA: Don't forget to handle error cases
TIP: Use the existing validation helper in utils.rs
"#;
let learnings = extract_learnings_from_output(output);
assert_eq!(learnings.len(), 4);
assert_eq!(learnings[0].kind, "Learning");
assert_eq!(
learnings[0].description,
"Always check if the file exists before reading"
);
assert_eq!(learnings[1].kind, "Pattern");
assert_eq!(learnings[1].description, "Use async/await for IO operations");
assert_eq!(learnings[2].kind, "Gotcha");
assert_eq!(
learnings[2].description,
"Don't forget to handle error cases"
);
assert_eq!(learnings[3].kind, "Tip");
assert_eq!(
learnings[3].description,
"Use the existing validation helper in utils.rs"
);
}
#[test]
fn test_extract_learnings_case_insensitive() {
let output = r#"
learning: This should still be captured
Pattern: Mixed case works
GOTCHA: All caps works too
tip: Lower case as well
"#;
let learnings = extract_learnings_from_output(output);
assert_eq!(learnings.len(), 4);
}
#[test]
fn test_extract_learnings_markdown_bold() {
let output = r#"
**LEARNING:** This is a bold learning
**PATTERN:** Bold pattern text
"#;
let learnings = extract_learnings_from_output(output);
assert_eq!(learnings.len(), 2);
assert_eq!(learnings[0].kind, "Learning");
assert_eq!(learnings[0].description, "This is a bold learning");
}
#[test]
fn test_extract_learnings_bullet_points() {
let output = r#"
Here are some learnings:
- PATTERN: First pattern from bullets
- TIP: A helpful tip
* GOTCHA: Watch out for this
"#;
let learnings = extract_learnings_from_output(output);
assert_eq!(learnings.len(), 3);
}
#[test]
fn test_extract_learnings_empty_description() {
let output = r#"
LEARNING:
PATTERN:
TIP: This one is valid
"#;
let learnings = extract_learnings_from_output(output);
// Only the valid one should be captured
assert_eq!(learnings.len(), 1);
assert_eq!(learnings[0].kind, "Tip");
}
#[test]
fn test_extract_learnings_no_duplicates() {
let output = r#"
PATTERN: Same pattern twice
- PATTERN: Same pattern twice
"#;
let learnings = extract_learnings_from_output(output);
// Should deduplicate
assert_eq!(learnings.len(), 1);
}
#[test]
fn test_format_learnings_section() {
let injector = LearningInjector::default();
let learnings = vec![
Learning::pattern("Use XYZ pattern"),
Learning::gotcha("Watch out for edge cases"),
Learning::tip("Check the documentation"),
];
let section = injector.format_learnings_section(&learnings);
assert!(section.contains("## Previous Learnings"));
assert!(section.contains("These patterns were discovered in previous iterations:"));
assert!(section.contains("- Pattern: Use XYZ pattern"));
assert!(section.contains("- Gotcha: Watch out for edge cases"));
assert!(section.contains("- Tip: Check the documentation"));
}
#[test]
fn test_inject_learnings_with_context_no_entries() {
let temp_dir = std::env::temp_dir().join(format!(
"learning_injection_test_{}",
std::process::id()
));
std::fs::create_dir_all(&temp_dir).unwrap();
let result = inject_learnings_with_context(
&temp_dir,
None,
"Original prompt content",
10,
)
.unwrap();
// With no context and no learnings, should just return the base prompt
assert_eq!(result, "Original prompt content");
std::fs::remove_dir_all(&temp_dir).ok();
}
#[test]
fn test_inject_learnings_with_context_info() {
let temp_dir = std::env::temp_dir().join(format!(
"learning_injection_context_test_{}",
std::process::id()
));
std::fs::create_dir_all(&temp_dir).unwrap();
let context_info = ContextRecoveryInfo {
current_branch: "feature/test".to_string(),
uncommitted_changes_count: 2,
last_checkpoint: None,
current_phase: Some("execute".to_string()),
recent_progress: vec![],
};
let result = inject_learnings_with_context(
&temp_dir,
Some(&context_info),
"Original prompt content",
10,
)
.unwrap();
assert!(result.contains("## Context Recovery"));
assert!(result.contains("feature/test"));
assert!(result.contains("---"));
assert!(result.contains("Original prompt content"));
std::fs::remove_dir_all(&temp_dir).ok();
}
#[test]
fn test_gather_learnings_deduplication() {
let temp_dir = std::env::temp_dir().join(format!(
"learning_dedup_test_{}",
std::process::id()
));
std::fs::create_dir_all(&temp_dir).unwrap();
// Create progress log entries with duplicate learnings
use super::super::progress_log::{append_entry, ProgressLogEntry, TaskCompletionStatus};
let entry1 = ProgressLogEntry::new("task-1", "First task", TaskCompletionStatus::Done)
.with_learnings(vec![
Learning::pattern("Common pattern"),
Learning::tip("First tip"),
]);
append_entry(&temp_dir, &entry1).unwrap();
let entry2 = ProgressLogEntry::new("task-2", "Second task", TaskCompletionStatus::Done)
.with_learnings(vec![
Learning::pattern("Common pattern"), // Duplicate
Learning::gotcha("New gotcha"),
]);
append_entry(&temp_dir, &entry2).unwrap();
let injector = LearningInjector::new().with_max_entries(10);
let learnings = injector.gather_learnings(&temp_dir).unwrap();
// Should have 3 unique learnings (not 4 with duplicate)
assert_eq!(learnings.len(), 3);
// Check that "Common pattern" appears only once
let pattern_count = learnings
.iter()
.filter(|l| l.description == "Common pattern")
.count();
assert_eq!(pattern_count, 1);
std::fs::remove_dir_all(&temp_dir).ok();
}
#[test]
fn test_gather_learnings_max_entries() {
let temp_dir = std::env::temp_dir().join(format!(
"learning_max_test_{}",
std::process::id()
));
std::fs::create_dir_all(&temp_dir).unwrap();
use super::super::progress_log::{append_entry, ProgressLogEntry, TaskCompletionStatus};
// Create an entry with many learnings
let learnings: Vec<Learning> = (0..10)
.map(|i| Learning::pattern(format!("Pattern {}", i)))
.collect();
let entry = ProgressLogEntry::new("task-many", "Many learnings", TaskCompletionStatus::Done)
.with_learnings(learnings);
append_entry(&temp_dir, &entry).unwrap();
// Set max to 5
let injector = LearningInjector::new().with_max_entries(5);
let gathered = injector.gather_learnings(&temp_dir).unwrap();
assert_eq!(gathered.len(), 5);
std::fs::remove_dir_all(&temp_dir).ok();
}
}
|