enact-core 0.0.2

Core agent runtime for Enact - Graph-Native AI agents
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
//! Progress Journal - Human-readable progress tracking
//!
//! Implements Antfarm-style progress journal:
//! - Discovered codebase patterns
//! - Story-by-story deltas
//! - Test/build snapshots
//! - Key decisions and unresolved risks

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Progress journal entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressEntry {
    /// Timestamp
    pub timestamp: DateTime<Utc>,
    /// Entry type
    pub entry_type: EntryType,
    /// Step ID that produced this entry
    pub step_id: String,
    /// Entry title/summary
    pub title: String,
    /// Entry details
    pub details: String,
    /// Associated metadata
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Types of progress entries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryType {
    /// Story started
    StoryStart,
    /// Story completed
    StoryComplete,
    /// Code pattern discovered
    PatternDiscovered,
    /// Test results
    TestResults,
    /// Build results
    BuildResults,
    /// Decision made
    Decision,
    /// Risk identified
    Risk,
    /// Milestone reached
    Milestone,
    /// Error occurred
    Error,
    /// General info
    Info,
}

/// Codebase pattern discovered during execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodebasePattern {
    /// Pattern name/category
    pub category: String,
    /// Pattern description
    pub description: String,
    /// Example file or location
    pub example: Option<String>,
    /// Whether this pattern should be reused
    pub reusable: bool,
}

/// Test snapshot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestSnapshot {
    /// Test command
    pub command: String,
    /// Test output
    pub output: String,
    /// Whether tests passed
    pub passed: bool,
    /// Failure count (if any)
    #[serde(default)]
    pub failure_count: Option<usize>,
    /// Duration in seconds
    pub duration_secs: f64,
}

/// Build snapshot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildSnapshot {
    /// Build command
    pub command: String,
    /// Build output
    pub output: String,
    /// Whether build succeeded
    pub succeeded: bool,
    /// Errors (if any)
    #[serde(default)]
    pub errors: Vec<String>,
    /// Warnings
    #[serde(default)]
    pub warnings: Vec<String>,
    /// Duration in seconds
    pub duration_secs: f64,
}

/// Key decision record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Decision {
    /// Decision title
    pub title: String,
    /// Context/why this decision was needed
    pub context: String,
    /// Decision made
    pub decision: String,
    /// Consequences
    pub consequences: Vec<String>,
    /// Alternatives considered
    #[serde(default)]
    pub alternatives: Vec<String>,
    /// Whether this decision is reversible
    pub reversible: bool,
}

/// Risk identified
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Risk {
    /// Risk description
    pub description: String,
    /// Risk level
    pub level: RiskLevel,
    /// Mitigation strategy
    pub mitigation: Option<String>,
    /// Whether this risk is resolved
    #[serde(default)]
    pub resolved: bool,
    /// Resolution notes
    #[serde(default)]
    pub resolution_notes: Option<String>,
}

/// Risk levels
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

/// Progress journal for a workflow run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressJournal {
    /// Workflow run ID
    pub run_id: String,
    /// Workflow name
    pub workflow_name: String,
    /// Start time
    pub start_time: DateTime<Utc>,
    /// Last update time
    pub last_update: DateTime<Utc>,
    /// Task description
    pub task: String,
    /// Repository path
    pub repo: Option<String>,
    /// Branch name
    pub branch: Option<String>,
    /// All progress entries
    pub entries: Vec<ProgressEntry>,
    /// Discovered codebase patterns
    #[serde(default)]
    pub patterns: Vec<CodebasePattern>,
    /// Key decisions
    #[serde(default)]
    pub decisions: Vec<Decision>,
    /// Identified risks
    #[serde(default)]
    pub risks: Vec<Risk>,
    /// Test snapshots
    #[serde(default)]
    pub test_snapshots: Vec<TestSnapshot>,
    /// Build snapshots
    #[serde(default)]
    pub build_snapshots: Vec<BuildSnapshot>,
    /// Custom sections
    #[serde(default)]
    pub sections: HashMap<String, String>,
}

impl ProgressJournal {
    /// Create a new progress journal
    pub fn new(run_id: String, workflow_name: String, task: String) -> Self {
        let now = Utc::now();
        Self {
            run_id,
            workflow_name,
            start_time: now,
            last_update: now,
            task,
            repo: None,
            branch: None,
            entries: vec![],
            patterns: vec![],
            decisions: vec![],
            risks: vec![],
            test_snapshots: vec![],
            build_snapshots: vec![],
            sections: HashMap::new(),
        }
    }

    /// Add a progress entry
    pub fn add_entry(&mut self, entry_type: EntryType, step_id: &str, title: &str, details: &str) {
        self.entries.push(ProgressEntry {
            timestamp: Utc::now(),
            entry_type,
            step_id: step_id.to_string(),
            title: title.to_string(),
            details: details.to_string(),
            metadata: HashMap::new(),
        });
        self.last_update = Utc::now();
    }

    /// Add a codebase pattern
    pub fn add_pattern(
        &mut self,
        category: &str,
        description: &str,
        example: Option<&str>,
        reusable: bool,
    ) {
        self.patterns.push(CodebasePattern {
            category: category.to_string(),
            description: description.to_string(),
            example: example.map(|s| s.to_string()),
            reusable,
        });
    }

    /// Add a decision
    pub fn add_decision(
        &mut self,
        title: &str,
        context: &str,
        decision: &str,
        consequences: Vec<String>,
        reversible: bool,
    ) {
        self.decisions.push(Decision {
            title: title.to_string(),
            context: context.to_string(),
            decision: decision.to_string(),
            consequences,
            alternatives: vec![],
            reversible,
        });
    }

    /// Add a risk
    pub fn add_risk(&mut self, description: &str, level: RiskLevel, mitigation: Option<&str>) {
        self.risks.push(Risk {
            description: description.to_string(),
            level,
            mitigation: mitigation.map(|s| s.to_string()),
            resolved: false,
            resolution_notes: None,
        });
    }

    /// Mark a risk as resolved
    pub fn resolve_risk(&mut self, description: &str, notes: &str) {
        if let Some(risk) = self.risks.iter_mut().find(|r| r.description == description) {
            risk.resolved = true;
            risk.resolution_notes = Some(notes.to_string());
        }
    }

    /// Add a test snapshot
    pub fn add_test_snapshot(
        &mut self,
        command: &str,
        output: &str,
        passed: bool,
        duration_secs: f64,
    ) {
        self.test_snapshots.push(TestSnapshot {
            command: command.to_string(),
            output: output.to_string(),
            passed,
            failure_count: None,
            duration_secs,
        });
    }

    /// Add a build snapshot
    pub fn add_build_snapshot(
        &mut self,
        command: &str,
        output: &str,
        succeeded: bool,
        duration_secs: f64,
    ) {
        self.build_snapshots.push(BuildSnapshot {
            command: command.to_string(),
            output: output.to_string(),
            succeeded,
            errors: vec![],
            warnings: vec![],
            duration_secs,
        });
    }

    /// Set a custom section
    pub fn set_section(&mut self, name: &str, content: &str) {
        self.sections.insert(name.to_string(), content.to_string());
    }

    /// Get entries by type
    pub fn entries_by_type(&self, entry_type: EntryType) -> Vec<&ProgressEntry> {
        self.entries
            .iter()
            .filter(|e| {
                std::mem::discriminant(&e.entry_type) == std::mem::discriminant(&entry_type)
            })
            .collect()
    }

    /// Serialize to JSON
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string_pretty(self).context("Failed to serialize progress journal")
    }

    /// Serialize to markdown (human-readable)
    pub fn to_markdown(&self) -> String {
        let mut md = String::new();

        // Header
        md.push_str(&format!("# Progress Journal: {}\n\n", self.workflow_name));
        md.push_str(&format!("**Run ID:** {}\n\n", self.run_id));
        md.push_str(&format!(
            "**Started:** {}\n\n",
            self.start_time.format("%Y-%m-%d %H:%M:%S UTC")
        ));
        md.push_str(&format!(
            "**Last Update:** {}\n\n",
            self.last_update.format("%Y-%m-%d %H:%M:%S UTC")
        ));

        // Task
        md.push_str("## Task\n\n");
        md.push_str(&self.task);
        md.push_str("\n\n");

        // Repository info
        if let Some(repo) = &self.repo {
            md.push_str("## Repository\n\n");
            md.push_str(&format!("- **Path:** {}\n", repo));
            if let Some(branch) = &self.branch {
                md.push_str(&format!("- **Branch:** {}\n", branch));
            }
            md.push('\n');
        }

        // Codebase Patterns
        if !self.patterns.is_empty() {
            md.push_str("## Codebase Patterns\n\n");
            for pattern in &self.patterns {
                md.push_str(&format!("### {}\n\n", pattern.category));
                md.push_str(&format!("{}\n\n", pattern.description));
                if let Some(example) = &pattern.example {
                    md.push_str(&format!("**Example:** `{}`\n\n", example));
                }
                md.push_str(&format!(
                    "**Reusable:** {}\n\n",
                    if pattern.reusable { "Yes" } else { "No" }
                ));
            }
        }

        // Test Results
        if !self.test_snapshots.is_empty() {
            md.push_str("## Test Results\n\n");
            for snapshot in &self.test_snapshots {
                let status = if snapshot.passed {
                    "✅ PASS"
                } else {
                    "❌ FAIL"
                };
                md.push_str(&format!("- **{}** ({}s)\n", status, snapshot.duration_secs));
                md.push_str(&format!("  - Command: `{}`\n", snapshot.command));
            }
            md.push('\n');
        }

        // Build Results
        if !self.build_snapshots.is_empty() {
            md.push_str("## Build Results\n\n");
            for snapshot in &self.build_snapshots {
                let status = if snapshot.succeeded {
                    "✅ SUCCESS"
                } else {
                    "❌ FAILED"
                };
                md.push_str(&format!("- **{}** ({}s)\n", status, snapshot.duration_secs));
                md.push_str(&format!("  - Command: `{}`\n", snapshot.command));
            }
            md.push('\n');
        }

        // Decisions
        if !self.decisions.is_empty() {
            md.push_str("## Decisions\n\n");
            for decision in &self.decisions {
                md.push_str(&format!("### {}\n\n", decision.title));
                md.push_str(&format!("**Context:** {}\n\n", decision.context));
                md.push_str(&format!("**Decision:** {}\n\n", decision.decision));
                if !decision.consequences.is_empty() {
                    md.push_str("**Consequences:**\n");
                    for consequence in &decision.consequences {
                        md.push_str(&format!("- {}\n", consequence));
                    }
                    md.push('\n');
                }
                md.push_str(&format!(
                    "**Reversible:** {}\n\n",
                    if decision.reversible { "Yes" } else { "No" }
                ));
            }
        }

        // Risks
        if !self.risks.is_empty() {
            md.push_str("## Risks\n\n");
            for risk in &self.risks {
                let level_icon = match risk.level {
                    RiskLevel::Low => "🟢",
                    RiskLevel::Medium => "🟡",
                    RiskLevel::High => "🔴",
                    RiskLevel::Critical => "⚠️",
                };
                let status = if risk.resolved {
                    "✅ Resolved"
                } else {
                    "⏳ Open"
                };

                md.push_str(&format!("### {} {}\n\n", level_icon, status));
                md.push_str(&format!("{}\n\n", risk.description));

                if let Some(mitigation) = &risk.mitigation {
                    md.push_str(&format!("**Mitigation:** {}\n\n", mitigation));
                }

                if let Some(notes) = &risk.resolution_notes {
                    md.push_str(&format!("**Resolution:** {}\n\n", notes));
                }
            }
        }

        // Timeline
        if !self.entries.is_empty() {
            md.push_str("## Timeline\n\n");
            for entry in &self.entries {
                let entry_type_str = format!("{:?}", entry.entry_type);
                md.push_str(&format!(
                    "**{}** [{}] *{}*\n\n",
                    entry.timestamp.format("%H:%M:%S"),
                    entry_type_str,
                    entry.step_id
                ));
                md.push_str(&format!("**{}**\n\n", entry.title));
                md.push_str(&format!("{}\n\n", entry.details));
            }
        }

        // Custom sections
        for (name, content) in &self.sections {
            md.push_str(&format!("## {}\n\n", name));
            md.push_str(content);
            md.push_str("\n\n");
        }

        md
    }

    /// Save to file
    pub async fn save_to_file(&self, path: &Path) -> Result<()> {
        let markdown = self.to_markdown();
        tokio::fs::write(path, markdown)
            .await
            .context("Failed to write progress journal")?;
        Ok(())
    }

    /// Load from JSON file
    pub async fn load_from_file(path: &Path) -> Result<Self> {
        let content = tokio::fs::read_to_string(path)
            .await
            .context("Failed to read progress journal file")?;

        serde_json::from_str(&content).context("Failed to parse progress journal JSON")
    }
}

/// Progress journal writer for tracking execution
pub struct ProgressJournalWriter {
    journal: ProgressJournal,
}

impl ProgressJournalWriter {
    /// Create a new writer
    pub fn new(run_id: String, workflow_name: String, task: String) -> Self {
        Self {
            journal: ProgressJournal::new(run_id, workflow_name, task),
        }
    }

    /// Get mutable reference to journal
    pub fn journal_mut(&mut self) -> &mut ProgressJournal {
        &mut self.journal
    }

    /// Log story start
    pub fn log_story_start(&mut self, step_id: &str, story_id: &str, story_title: &str) {
        self.journal.add_entry(
            EntryType::StoryStart,
            step_id,
            &format!("Starting story: {}", story_title),
            &format!("Story ID: {}", story_id),
        );
    }

    /// Log story completion
    pub fn log_story_complete(
        &mut self,
        step_id: &str,
        story_id: &str,
        story_title: &str,
        changes: &str,
    ) {
        self.journal.add_entry(
            EntryType::StoryComplete,
            step_id,
            &format!("Completed story: {}", story_title),
            &format!("Story ID: {}\n\nChanges:\n{}", story_id, changes),
        );
    }

    /// Log pattern discovery
    pub fn log_pattern(
        &mut self,
        step_id: &str,
        category: &str,
        description: &str,
        example: Option<&str>,
    ) {
        self.journal
            .add_pattern(category, description, example, true);
        self.journal.add_entry(
            EntryType::PatternDiscovered,
            step_id,
            &format!("Discovered pattern: {}", category),
            description,
        );
    }

    /// Log test results
    pub fn log_test_results(
        &mut self,
        step_id: &str,
        command: &str,
        output: &str,
        passed: bool,
        duration_secs: f64,
    ) {
        self.journal
            .add_test_snapshot(command, output, passed, duration_secs);
        self.journal.add_entry(
            EntryType::TestResults,
            step_id,
            if passed {
                "Tests passed"
            } else {
                "Tests failed"
            },
            &format!("Command: {}\n\nDuration: {:.2}s", command, duration_secs),
        );
    }

    /// Log build results
    pub fn log_build_results(
        &mut self,
        step_id: &str,
        command: &str,
        output: &str,
        succeeded: bool,
        duration_secs: f64,
    ) {
        self.journal
            .add_build_snapshot(command, output, succeeded, duration_secs);
        self.journal.add_entry(
            EntryType::BuildResults,
            step_id,
            if succeeded {
                "Build succeeded"
            } else {
                "Build failed"
            },
            &format!("Command: {}\n\nDuration: {:.2}s", command, duration_secs),
        );
    }

    /// Log a decision
    pub fn log_decision(&mut self, step_id: &str, title: &str, context: &str, decision: &str) {
        self.journal
            .add_decision(title, context, decision, vec![], false);
        self.journal.add_entry(
            EntryType::Decision,
            step_id,
            &format!("Decision: {}", title),
            decision,
        );
    }

    /// Log a risk
    pub fn log_risk(&mut self, step_id: &str, description: &str, level: RiskLevel) {
        self.journal.add_risk(description, level, None);
        self.journal.add_entry(
            EntryType::Risk,
            step_id,
            &format!("Risk identified: {:?}", level),
            description,
        );
    }

    /// Get the final journal
    pub fn into_journal(self) -> ProgressJournal {
        self.journal
    }
}

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

    #[test]
    fn test_progress_journal() {
        let mut journal = ProgressJournal::new(
            "run-123".to_string(),
            "feature-dev".to_string(),
            "Implement new auth system".to_string(),
        );

        journal.repo = Some("/path/to/repo".to_string());
        journal.branch = Some("feature/auth".to_string());

        journal.add_pattern(
            "Error Handling",
            "Use Result<T, E> for all fallible operations",
            Some("src/error.rs:42"),
            true,
        );

        journal.add_decision(
            "Auth Library",
            "Need to choose authentication library",
            "Use JWT with jsonwebtoken crate",
            vec!["Simpler than OAuth2 for our use case".to_string()],
            true,
        );

        journal.add_risk(
            "Token expiration edge cases",
            RiskLevel::Medium,
            Some("Add comprehensive tests"),
        );

        assert_eq!(journal.patterns.len(), 1);
        assert_eq!(journal.decisions.len(), 1);
        assert_eq!(journal.risks.len(), 1);
    }

    #[test]
    fn test_to_markdown() {
        let mut journal = ProgressJournal::new(
            "run-123".to_string(),
            "feature-dev".to_string(),
            "Test task".to_string(),
        );

        journal.add_pattern("Test Pattern", "A test pattern", None, true);

        let markdown = journal.to_markdown();
        assert!(markdown.contains("# Progress Journal: feature-dev"));
        assert!(markdown.contains("Test task"));
        assert!(markdown.contains("Test Pattern"));
    }
}