terraphim_agent 1.16.30

Terraphim AI Agent CLI - Command-line interface with interactive REPL and ASCII graph visualization
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
use std::process::Command;
use std::time::Duration;

use thiserror::Error;
use tracing::info;

use crate::shared_learning::types::SharedLearning;

/// Errors that can occur during wiki sync
#[derive(Error, Debug, Clone)]
pub enum WikiSyncError {
    #[error("gitea-robot command failed: {0}")]
    GiteaRobot(String),
    #[error("wiki page already exists: {0}")]
    AlreadyExists(String),
    #[error("wiki page not found: {0}")]
    NotFound(String),
    #[error("network error: {0}")]
    Network(String),
    #[error("invalid response: {0}")]
    InvalidResponse(String),
    #[error("configuration error: {0}")]
    Config(String),
}

/// Configuration for Gitea wiki client
#[derive(Debug, Clone)]
pub struct GiteaWikiConfig {
    /// Gitea instance URL
    pub gitea_url: String,
    /// Gitea API token
    pub token: String,
    /// Repository owner
    pub owner: String,
    /// Repository name
    pub repo: String,
    /// Path to gitea-robot binary
    pub robot_path: String,
    /// Request timeout
    pub timeout: Duration,
}

impl Default for GiteaWikiConfig {
    fn default() -> Self {
        Self {
            gitea_url: std::env::var("GITEA_URL")
                .unwrap_or_else(|_| "https://git.terraphim.cloud".to_string()),
            token: std::env::var("GITEA_TOKEN").unwrap_or_default(),
            owner: "terraphim".to_string(),
            repo: "terraphim-ai".to_string(),
            robot_path: "/home/alex/go/bin/gitea-robot".to_string(),
            timeout: Duration::from_secs(30),
        }
    }
}

impl GiteaWikiConfig {
    /// Create config from environment variables
    pub fn from_env() -> Result<Self, WikiSyncError> {
        let config = Self::default();

        if config.token.is_empty() {
            return Err(WikiSyncError::Config(
                "GITEA_TOKEN environment variable not set".to_string(),
            ));
        }

        Ok(config)
    }

    /// Set custom gitea-robot path
    pub fn with_robot_path(mut self, path: &str) -> Self {
        self.robot_path = path.to_string();
        self
    }

    /// Set custom owner/repo
    pub fn with_repo(mut self, owner: &str, repo: &str) -> Self {
        self.owner = owner.to_string();
        self.repo = repo.to_string();
        self
    }
}

/// Client for Gitea wiki operations
pub struct GiteaWikiClient {
    config: GiteaWikiConfig,
}

/// Result of a wiki sync operation
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SyncResult {
    /// Created new wiki page
    Created(String), // Page name
    /// Updated existing wiki page
    Updated(String), // Page name
    /// Skipped (learning not eligible for sync)
    Skipped(String), // Reason
}

impl GiteaWikiClient {
    /// Create new wiki client
    pub fn new(config: GiteaWikiConfig) -> Self {
        Self { config }
    }

    /// Create or update a wiki page for a learning
    pub async fn sync_learning(
        &self,
        learning: &SharedLearning,
    ) -> Result<SyncResult, WikiSyncError> {
        // Only sync L2 and L3 learnings
        if !learning.should_sync_to_wiki() {
            return Ok(SyncResult::Skipped(format!(
                "Trust level {} does not allow wiki sync",
                learning.trust_level
            )));
        }

        let page_name = learning
            .wiki_page_name
            .clone()
            .unwrap_or_else(|| learning.generate_wiki_page_name());

        // Check if page exists
        let exists = self.page_exists(&page_name).await?;

        let content = learning.to_wiki_markdown();

        if exists {
            // Update existing page
            self.update_wiki_page(&page_name, &content).await?;
            info!(
                "Updated wiki page for learning {}: {}",
                learning.id, page_name
            );
            Ok(SyncResult::Updated(page_name))
        } else {
            // Create new page
            self.create_wiki_page(&page_name, &content).await?;
            info!(
                "Created wiki page for learning {}: {}",
                learning.id, page_name
            );
            Ok(SyncResult::Created(page_name))
        }
    }

    /// Check if a wiki page exists
    async fn page_exists(&self, page_name: &str) -> Result<bool, WikiSyncError> {
        let output = Command::new(&self.config.robot_path)
            .env("GITEA_URL", &self.config.gitea_url)
            .env("GITEA_TOKEN", &self.config.token)
            .args([
                "wiki-get",
                "--owner",
                &self.config.owner,
                "--repo",
                &self.config.repo,
                "--name",
                page_name,
            ])
            .output()
            .map_err(|e| {
                WikiSyncError::GiteaRobot(format!("Failed to execute gitea-robot: {}", e))
            })?;

        if output.status.success() {
            Ok(true)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("not found") || stderr.contains("404") {
                Ok(false)
            } else {
                Err(WikiSyncError::GiteaRobot(stderr.to_string()))
            }
        }
    }

    /// Create a new wiki page
    async fn create_wiki_page(&self, page_name: &str, content: &str) -> Result<(), WikiSyncError> {
        let output = Command::new(&self.config.robot_path)
            .env("GITEA_URL", &self.config.gitea_url)
            .env("GITEA_TOKEN", &self.config.token)
            .args([
                "wiki-create",
                "--owner",
                &self.config.owner,
                "--repo",
                &self.config.repo,
                "--title",
                page_name,
                "--content",
                content,
                "--message",
                &format!("Add shared learning: {}", page_name),
            ])
            .output()
            .map_err(|e| {
                WikiSyncError::GiteaRobot(format!("Failed to execute gitea-robot: {}", e))
            })?;

        if output.status.success() {
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("already exists") {
                Err(WikiSyncError::AlreadyExists(page_name.to_string()))
            } else {
                Err(WikiSyncError::GiteaRobot(stderr.to_string()))
            }
        }
    }

    /// Update an existing wiki page
    async fn update_wiki_page(&self, page_name: &str, content: &str) -> Result<(), WikiSyncError> {
        let output = Command::new(&self.config.robot_path)
            .env("GITEA_URL", &self.config.gitea_url)
            .env("GITEA_TOKEN", &self.config.token)
            .args([
                "wiki-update",
                "--owner",
                &self.config.owner,
                "--repo",
                &self.config.repo,
                "--name",
                page_name,
                "--content",
                content,
                "--message",
                &format!("Update shared learning: {}", page_name),
            ])
            .output()
            .map_err(|e| {
                WikiSyncError::GiteaRobot(format!("Failed to execute gitea-robot: {}", e))
            })?;

        if output.status.success() {
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("not found") || stderr.contains("404") {
                Err(WikiSyncError::NotFound(page_name.to_string()))
            } else {
                Err(WikiSyncError::GiteaRobot(stderr.to_string()))
            }
        }
    }

    /// Delete a wiki page
    pub async fn delete_wiki_page(&self, page_name: &str) -> Result<(), WikiSyncError> {
        let output = Command::new(&self.config.robot_path)
            .env("GITEA_URL", &self.config.gitea_url)
            .env("GITEA_TOKEN", &self.config.token)
            .args([
                "wiki-delete",
                "--owner",
                &self.config.owner,
                "--repo",
                &self.config.repo,
                "--name",
                page_name,
            ])
            .output()
            .map_err(|e| {
                WikiSyncError::GiteaRobot(format!("Failed to execute gitea-robot: {}", e))
            })?;

        if output.status.success() {
            info!("Deleted wiki page: {}", page_name);
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(WikiSyncError::GiteaRobot(stderr.to_string()))
        }
    }

    /// Sync all L2/L3 learnings to wiki
    pub async fn sync_all_learnings(
        &self,
        learnings: &[SharedLearning],
    ) -> Vec<(String, Result<SyncResult, WikiSyncError>)> {
        let mut results = Vec::new();

        for learning in learnings {
            if learning.should_sync_to_wiki() {
                let result = self.sync_learning(learning).await;
                results.push((learning.id.clone(), result));
            }
        }

        results
    }

    /// List all wiki pages
    pub async fn list_wiki_pages(&self) -> Result<Vec<String>, WikiSyncError> {
        let output = Command::new(&self.config.robot_path)
            .env("GITEA_URL", &self.config.gitea_url)
            .env("GITEA_TOKEN", &self.config.token)
            .args([
                "wiki-list",
                "--owner",
                &self.config.owner,
                "--repo",
                &self.config.repo,
            ])
            .output()
            .map_err(|e| {
                WikiSyncError::GiteaRobot(format!("Failed to execute gitea-robot: {}", e))
            })?;

        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let pages: Vec<String> = stdout
                .lines()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            Ok(pages)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(WikiSyncError::GiteaRobot(stderr.to_string()))
        }
    }
}

/// Sync service that periodically syncs learnings to Gitea wiki
#[allow(dead_code)]
pub struct WikiSyncService {
    client: GiteaWikiClient,
}

#[allow(dead_code)]
impl WikiSyncService {
    /// Create new sync service
    pub fn new(client: GiteaWikiClient) -> Self {
        Self { client }
    }

    /// Sync a batch of learnings
    pub async fn sync_batch(&self, learnings: &[SharedLearning]) -> WikiSyncReport {
        let results = self.client.sync_all_learnings(learnings).await;

        let mut created = 0;
        let mut updated = 0;
        let mut skipped = 0;
        let mut failed = 0;

        for (_, result) in &results {
            match result {
                Ok(SyncResult::Created(_)) => created += 1,
                Ok(SyncResult::Updated(_)) => updated += 1,
                Ok(SyncResult::Skipped(_)) => skipped += 1,
                Err(_) => failed += 1,
            }
        }

        WikiSyncReport {
            created,
            updated,
            skipped,
            failed,
            total: results.len(),
            results,
        }
    }
}

/// Report of a wiki sync operation
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct WikiSyncReport {
    pub created: usize,
    pub updated: usize,
    pub skipped: usize,
    pub failed: usize,
    pub total: usize,
    pub results: Vec<(String, Result<SyncResult, WikiSyncError>)>,
}

#[allow(dead_code)]
impl WikiSyncReport {
    /// Check if all operations were successful
    pub fn all_success(&self) -> bool {
        self.failed == 0
    }

    /// Get success rate as percentage
    pub fn success_rate(&self) -> f64 {
        if self.total == 0 {
            return 100.0;
        }
        let success = self.total - self.failed;
        (success as f64 / self.total as f64) * 100.0
    }
}

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

    #[test]
    fn test_gitea_wiki_config_default() {
        let config = GiteaWikiConfig::default();
        assert_eq!(config.owner, "terraphim");
        assert_eq!(config.repo, "terraphim-ai");
        assert_eq!(config.robot_path, "/home/alex/go/bin/gitea-robot");
    }

    #[test]
    fn test_gitea_wiki_config_from_env() {
        // This test assumes GITEA_TOKEN is set in environment
        // Skip if not set
        if std::env::var("GITEA_TOKEN").is_err() {
            return;
        }

        let config = GiteaWikiConfig::from_env().unwrap();
        assert!(!config.token.is_empty());
    }

    #[test]
    fn test_sync_result_display() {
        let created = SyncResult::Created("test-page".to_string());
        let updated = SyncResult::Updated("test-page".to_string());
        let skipped = SyncResult::Skipped("not eligible".to_string());

        match created {
            SyncResult::Created(name) => assert_eq!(name, "test-page"),
            _ => panic!("Expected Created"),
        }

        match updated {
            SyncResult::Updated(name) => assert_eq!(name, "test-page"),
            _ => panic!("Expected Updated"),
        }

        match skipped {
            SyncResult::Skipped(reason) => assert_eq!(reason, "not eligible"),
            _ => panic!("Expected Skipped"),
        }
    }

    #[test]
    fn test_wiki_sync_report() {
        let report = WikiSyncReport {
            created: 5,
            updated: 3,
            skipped: 2,
            failed: 0,
            total: 10,
            results: vec![],
        };

        assert!(report.all_success());
        assert_eq!(report.success_rate(), 100.0);

        let report_with_failures = WikiSyncReport {
            created: 5,
            updated: 3,
            skipped: 1,
            failed: 1,
            total: 10,
            results: vec![],
        };

        assert!(!report_with_failures.all_success());
        assert_eq!(report_with_failures.success_rate(), 90.0);
    }

    #[tokio::test]
    async fn test_sync_learning_skips_l1() {
        // Create a mock config (won't actually connect to Gitea)
        let config = GiteaWikiConfig {
            gitea_url: "http://localhost".to_string(),
            token: "test".to_string(),
            owner: "test".to_string(),
            repo: "test".to_string(),
            robot_path: "/bin/true".to_string(),
            timeout: Duration::from_secs(5),
        };

        let client = GiteaWikiClient::new(config);
        let learning = SharedLearning::new(
            "Test".to_string(),
            "Content".to_string(),
            crate::shared_learning::types::LearningSource::Manual,
            "agent".to_string(),
        );

        // L1 learning should be skipped
        let result = client.sync_learning(&learning).await.unwrap();
        assert!(matches!(result, SyncResult::Skipped(_)));
    }

    #[tokio::test]
    async fn test_sync_learning_syncs_l2() {
        let config = GiteaWikiConfig {
            gitea_url: "http://localhost".to_string(),
            token: "test".to_string(),
            owner: "test".to_string(),
            repo: "test".to_string(),
            robot_path: "/bin/false".to_string(), // Will fail, but that's ok for this test
            timeout: Duration::from_secs(5),
        };

        let client = GiteaWikiClient::new(config);
        let mut learning = SharedLearning::new(
            "Test".to_string(),
            "Content".to_string(),
            crate::shared_learning::types::LearningSource::Manual,
            "agent".to_string(),
        );
        learning.promote_to_l2();

        // L2 learning should attempt sync (will fail due to /bin/false)
        let result = client.sync_learning(&learning).await;
        assert!(result.is_err() || matches!(result, Ok(SyncResult::Skipped(_))));
    }
}