ryo-app 0.1.0

[preview] Application layer for RYO - Project management, Intent handling, API
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
//! Verification layer for spec-based testing
//!
//! Provides verification points that can be checked after each phase.

use thiserror::Error;

use super::types::VerificationPointSpec;

/// Verification error
#[derive(Debug, Clone, Error)]
pub enum VerificationError {
    #[error("Module not found: {0}")]
    ModuleNotFound(String),

    #[error("Type not found: {0}")]
    TypeNotFound(String),

    #[error("Missing derive on {ty}: {derive}")]
    MissingDerive { ty: String, derive: String },

    #[error("Missing field on {ty}: {field}")]
    MissingField { ty: String, field: String },

    #[error("Method not found: {ty}::{method}")]
    MethodNotFound { ty: String, method: String },

    #[error("Compilation failed: {0}")]
    CompilationFailed(String),

    #[error("Warning detected: {0}")]
    WarningDetected(String),
}

/// Verification point abstraction
#[derive(Debug, Clone)]
pub enum VerificationPoint {
    /// Check that a module exists
    ModuleExists(Vec<String>),

    /// Check that types exist
    TypeExists(Vec<String>),

    /// Check that a type has specific derives
    HasDerive { ty: String, derives: Vec<String> },

    /// Check that a struct has a specific field
    HasField {
        ty: String,
        field: String,
        field_type: String,
    },

    /// Check that a type has a specific method
    MethodExists { ty: String, method: String },

    /// Check that code compiles
    Compiles,

    /// Check for no warnings (with allowed list)
    NoWarnings { allowed: Vec<String> },
}

impl From<VerificationPointSpec> for VerificationPoint {
    fn from(spec: VerificationPointSpec) -> Self {
        match spec {
            VerificationPointSpec::ModuleExists { paths } => VerificationPoint::ModuleExists(paths),
            VerificationPointSpec::TypeExists { types } => VerificationPoint::TypeExists(types),
            VerificationPointSpec::HasDerive { ty, derives } => {
                VerificationPoint::HasDerive { ty, derives }
            }
            VerificationPointSpec::HasField {
                ty,
                field,
                field_type,
            } => VerificationPoint::HasField {
                ty,
                field,
                field_type,
            },
            VerificationPointSpec::MethodExists { ty, method } => {
                VerificationPoint::MethodExists { ty, method }
            }
            VerificationPointSpec::Compiles => VerificationPoint::Compiles,
            VerificationPointSpec::NoWarnings { allowed } => {
                VerificationPoint::NoWarnings { allowed }
            }
        }
    }
}

/// Result of running a verification
#[derive(Debug, Clone)]
pub struct VerificationResult {
    /// Phase name
    pub phase: String,

    /// Total points checked
    pub total: usize,

    /// Passed points
    pub passed: usize,

    /// Failed points with errors
    pub failures: Vec<(VerificationPoint, VerificationError)>,
}

impl VerificationResult {
    /// Check if all verifications passed
    pub fn all_passed(&self) -> bool {
        self.failures.is_empty()
    }
}

/// Verification runner
pub struct VerificationRunner {
    /// Project root path
    project_root: std::path::PathBuf,
}

impl VerificationRunner {
    /// Create a new verification runner
    pub fn new(project_root: impl Into<std::path::PathBuf>) -> Self {
        Self {
            project_root: project_root.into(),
        }
    }

    /// Run verifications for a phase
    pub fn run(&self, phase: &str, points: &[VerificationPoint]) -> VerificationResult {
        let mut passed = 0;
        let mut failures = Vec::new();

        for point in points {
            match self.verify_point(point) {
                Ok(()) => passed += 1,
                Err(e) => failures.push((point.clone(), e)),
            }
        }

        VerificationResult {
            phase: phase.to_string(),
            total: points.len(),
            passed,
            failures,
        }
    }

    /// Verify a single point
    fn verify_point(&self, point: &VerificationPoint) -> Result<(), VerificationError> {
        match point {
            VerificationPoint::ModuleExists(paths) => {
                for path in paths {
                    self.check_module_exists(path)?;
                }
                Ok(())
            }
            VerificationPoint::TypeExists(types) => {
                for ty in types {
                    self.check_type_exists(ty)?;
                }
                Ok(())
            }
            VerificationPoint::HasDerive { ty, derives } => {
                for derive in derives {
                    self.check_has_derive(ty, derive)?;
                }
                Ok(())
            }
            VerificationPoint::HasField {
                ty,
                field,
                field_type,
            } => self.check_has_field(ty, field, field_type),
            VerificationPoint::MethodExists { ty, method } => self.check_method_exists(ty, method),
            VerificationPoint::Compiles => self.check_compiles(),
            VerificationPoint::NoWarnings { allowed } => self.check_no_warnings(allowed),
        }
    }

    /// Check if a module exists
    fn check_module_exists(&self, path: &str) -> Result<(), VerificationError> {
        // Convert module path to file path
        let file_path = if path.contains("::") {
            let parts: Vec<&str> = path.split("::").collect();
            format!("src/{}.rs", parts.join("/"))
        } else {
            format!("src/{}.rs", path)
        };

        let full_path = self.project_root.join(&file_path);

        // Also check for mod.rs pattern
        let mod_path = if path.contains("::") {
            let parts: Vec<&str> = path.split("::").collect();
            format!("src/{}/mod.rs", parts.join("/"))
        } else {
            format!("src/{}/mod.rs", path)
        };

        let full_mod_path = self.project_root.join(&mod_path);

        if full_path.exists() || full_mod_path.exists() {
            Ok(())
        } else {
            Err(VerificationError::ModuleNotFound(path.to_string()))
        }
    }

    /// Check if a type exists (basic file-based check)
    fn check_type_exists(&self, ty: &str) -> Result<(), VerificationError> {
        // This would use ryo-analysis in a full implementation
        // For now, we just check that the type name appears in the source
        let src_path = self.project_root.join("src");

        if !src_path.exists() {
            return Err(VerificationError::TypeNotFound(ty.to_string()));
        }

        // Simple grep for the type definition
        // In production, use SymbolRegistry
        for entry in walkdir::WalkDir::new(&src_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
        {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                // Check for struct or enum definition
                let patterns = [
                    format!("struct {} ", ty),
                    format!("struct {}(", ty),
                    format!("struct {} {{", ty),
                    format!("enum {} ", ty),
                    format!("enum {} {{", ty),
                ];

                for pattern in &patterns {
                    if content.contains(pattern) {
                        return Ok(());
                    }
                }
            }
        }

        Err(VerificationError::TypeNotFound(ty.to_string()))
    }

    /// Check if a type has a derive
    fn check_has_derive(&self, ty: &str, derive: &str) -> Result<(), VerificationError> {
        // Would use ryo-analysis in full implementation
        let src_path = self.project_root.join("src");

        for entry in walkdir::WalkDir::new(&src_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
        {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                // Find type definition and check preceding derive
                if let Some(pos) = content.find(&format!("struct {}", ty)) {
                    let before = &content[..pos];
                    if let Some(derive_pos) = before.rfind("#[derive(") {
                        let derive_block = &before[derive_pos..];
                        if derive_block.contains(derive) {
                            return Ok(());
                        }
                    }
                }

                if let Some(pos) = content.find(&format!("enum {}", ty)) {
                    let before = &content[..pos];
                    if let Some(derive_pos) = before.rfind("#[derive(") {
                        let derive_block = &before[derive_pos..];
                        if derive_block.contains(derive) {
                            return Ok(());
                        }
                    }
                }
            }
        }

        Err(VerificationError::MissingDerive {
            ty: ty.to_string(),
            derive: derive.to_string(),
        })
    }

    /// Check if a struct has a field
    fn check_has_field(
        &self,
        ty: &str,
        field: &str,
        _field_type: &str,
    ) -> Result<(), VerificationError> {
        // Would use ryo-analysis in full implementation
        let src_path = self.project_root.join("src");

        for entry in walkdir::WalkDir::new(&src_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
        {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                // Find struct definition
                if let Some(pos) = content.find(&format!("struct {} {{", ty)) {
                    // Find the closing brace
                    if let Some(end) = content[pos..].find('}') {
                        let struct_body = &content[pos..pos + end];
                        if struct_body.contains(&field.to_string()) {
                            return Ok(());
                        }
                    }
                }
            }
        }

        Err(VerificationError::MissingField {
            ty: ty.to_string(),
            field: field.to_string(),
        })
    }

    /// Check if a type has a method
    fn check_method_exists(&self, ty: &str, method: &str) -> Result<(), VerificationError> {
        // Would use ryo-analysis in full implementation
        let src_path = self.project_root.join("src");

        for entry in walkdir::WalkDir::new(&src_path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
        {
            if let Ok(content) = std::fs::read_to_string(entry.path()) {
                // Find impl block for the type
                if content.contains(&format!("impl {}", ty))
                    && content.contains(&format!("fn {}(", method))
                {
                    return Ok(());
                }
            }
        }

        Err(VerificationError::MethodNotFound {
            ty: ty.to_string(),
            method: method.to_string(),
        })
    }

    /// Check that code compiles
    fn check_compiles(&self) -> Result<(), VerificationError> {
        let output = std::process::Command::new("cargo")
            .arg("check")
            .current_dir(&self.project_root)
            .output();

        match output {
            Ok(out) if out.status.success() => Ok(()),
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);
                Err(VerificationError::CompilationFailed(stderr.to_string()))
            }
            Err(e) => Err(VerificationError::CompilationFailed(e.to_string())),
        }
    }

    /// Check for no warnings
    fn check_no_warnings(&self, allowed: &[String]) -> Result<(), VerificationError> {
        let output = std::process::Command::new("cargo")
            .args(["check", "--message-format=short"])
            .current_dir(&self.project_root)
            .output();

        match output {
            Ok(out) => {
                let stderr = String::from_utf8_lossy(&out.stderr);

                // Filter out allowed warnings
                for line in stderr.lines() {
                    if line.contains("warning:") {
                        let is_allowed = allowed.iter().any(|a| line.contains(a));
                        if !is_allowed {
                            return Err(VerificationError::WarningDetected(line.to_string()));
                        }
                    }
                }

                Ok(())
            }
            Err(e) => Err(VerificationError::CompilationFailed(e.to_string())),
        }
    }
}

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

    #[test]
    fn test_verification_result() {
        let result = VerificationResult {
            phase: "test".to_string(),
            total: 3,
            passed: 3,
            failures: vec![],
        };

        assert!(result.all_passed());
    }

    #[test]
    fn test_verification_point_from_spec() {
        let spec = VerificationPointSpec::ModuleExists {
            paths: vec!["user".to_string(), "product".to_string()],
        };

        let point: VerificationPoint = spec.into();

        if let VerificationPoint::ModuleExists(paths) = point {
            assert_eq!(paths.len(), 2);
        } else {
            panic!("Expected ModuleExists");
        }
    }
}