airl-project 0.1.0

Project and workspace management for AIRL: history, queries, projections
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
//! AIRL Project - Project state management, patch history, queries.
//!
//! Manages the lifecycle of an AIRL project: creating from IR,
//! applying patches with undo history, querying functions/types,
//! constraint checking, text projections, and multi-module workspaces.
//!
//! # Modules
//!
//! - [`constraints`] — enforce architectural invariants (complexity, purity, forbidden calls)
//! - [`diff`] — compare two modules semantically
//! - [`projection`] — render IR as TypeScript or Python source
//! - [`queries`] — richer analyses: dead code, builtin usage, effect surface
//! - [`workspace`] — load and link multiple modules

#![deny(missing_docs)]

pub mod constraints;
pub mod diff;
pub mod projection;
pub mod queries;
pub mod workspace;

use airl_ir::module::Module;
use airl_ir::node::Node;
use airl_ir::version::VersionId;
use airl_patch::{self, Impact, Patch};
use airl_typecheck::{self, TypeCheckResult};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Errors arising from [`Project`] operations.
#[derive(Debug, Error)]
pub enum ProjectError {
    /// No module has been loaded into the project.
    #[error("no module loaded")]
    NoModule,
    /// A semantic patch failed to apply.
    #[error("patch error: {0}")]
    PatchError(#[from] airl_patch::PatchError),
    /// `undo_last` was called on an empty history.
    #[error("no patches to undo")]
    NothingToUndo,
    /// JSON serialization or deserialization failed.
    #[error("JSON error: {0}")]
    JsonError(#[from] serde_json::Error),
}

/// A history entry tracking an applied patch and its inverse.
///
/// Stored on the [`Project`] so `undo_last` can reverse the last patch exactly.
#[derive(Clone, Debug)]
pub struct HistoryEntry {
    /// The module version hash before the patch was applied.
    pub previous_version: String,
    /// The patch that was applied.
    pub patch: Patch,
    /// The inverse patch computed before application.
    pub inverse: Patch,
}

/// Summary of a function in the module, suitable for API responses.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FuncSummary {
    /// Function ID (unique within the module).
    pub id: String,
    /// Function name.
    pub name: String,
    /// List of parameter summaries.
    pub params: Vec<ParamSummary>,
    /// Return type as a string.
    pub returns: String,
    /// Declared effects as strings.
    pub effects: Vec<String>,
    /// Number of IR nodes in the function body.
    pub node_count: usize,
}

/// Summary of a function parameter, suitable for API responses.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ParamSummary {
    /// Parameter name.
    pub name: String,
    /// Parameter type as a string.
    pub param_type: String,
}

/// An edge in a static call graph: `from` calls `to`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CallEdge {
    /// Name of the calling function.
    pub from: String,
    /// Name of the target function (user-defined or builtin).
    pub to: String,
}

/// Effect summary for a single function.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EffectSummary {
    /// Function name.
    pub func_name: String,
    /// Declared effects as strings.
    pub declared_effects: Vec<String>,
}

/// An AIRL project holding module state, history, and metadata.
///
/// The `Project` is the high-level unit of work for the API. It wraps a
/// [`Module`] with:
/// - Content-addressable versioning (updated on each patch)
/// - Patch history with exact undo
/// - Convenience methods for typechecking, queries, projections, constraints
pub struct Project {
    /// Project name (user-provided).
    pub name: String,
    /// The current module state.
    pub module: Module,
    /// Content-addressed version hash of the current module.
    pub version: String,
    /// Stack of applied patches and their inverses (for undo).
    pub history: Vec<HistoryEntry>,
}

impl Project {
    /// Create a new project from a module.
    pub fn new(name: impl Into<String>, module: Module) -> Self {
        let version = VersionId::compute(&module).to_hex();
        Self {
            name: name.into(),
            module,
            version,
            history: Vec::new(),
        }
    }

    /// Create a project from a JSON IR string.
    pub fn from_json(name: impl Into<String>, json: &str) -> Result<Self, ProjectError> {
        let module: Module = serde_json::from_str(json)?;
        Ok(Self::new(name, module))
    }

    /// Apply a patch to the project. Records history for undo.
    pub fn apply_patch(&mut self, patch: &Patch) -> Result<PatchApplyResult, ProjectError> {
        // Generate inverse BEFORE applying
        let inverse = airl_patch::invert_patch(&self.module, patch)?;
        let old_version = self.version.clone();

        // Apply
        let result = airl_patch::apply_patch(&self.module, patch)?;

        // Record history
        self.history.push(HistoryEntry {
            previous_version: old_version,
            patch: patch.clone(),
            inverse,
        });

        // Update project state
        self.module = result.new_module;
        self.version = result.new_version.clone();

        Ok(PatchApplyResult {
            new_version: result.new_version,
            impact: result.impact,
        })
    }

    /// Preview a patch without applying it.
    pub fn preview_patch(&self, patch: &Patch) -> Result<PatchPreviewResult, ProjectError> {
        // Validate
        let validation = airl_patch::validate_patch(&self.module, patch);
        let valid = validation.is_ok();
        let validation_error = validation.err().map(|e| e.to_string());

        // Try to apply to a clone to check types
        let mut type_errors = Vec::new();
        let mut impact = Impact::default();

        if valid {
            if let Ok(result) = airl_patch::apply_patch(&self.module, patch) {
                impact = result.impact;
                let tc = airl_typecheck::typecheck(&result.new_module);
                type_errors = tc.errors.iter().map(|e| e.message.clone()).collect();
            }
        }

        Ok(PatchPreviewResult {
            would_succeed: valid && type_errors.is_empty(),
            validation_error,
            type_errors,
            impact,
        })
    }

    /// Undo the last patch.
    pub fn undo_last(&mut self) -> Result<PatchApplyResult, ProjectError> {
        let entry = self.history.pop().ok_or(ProjectError::NothingToUndo)?;

        let result = airl_patch::apply_patch(&self.module, &entry.inverse)?;
        self.module = result.new_module;
        self.version = result.new_version.clone();

        Ok(PatchApplyResult {
            new_version: result.new_version,
            impact: result.impact,
        })
    }

    /// Run type checker on the current module.
    pub fn typecheck(&self) -> TypeCheckResult {
        airl_typecheck::typecheck(&self.module)
    }

    /// Check the module against a set of constraints.
    pub fn check_constraints(
        &self,
        constraints: &[constraints::Constraint],
    ) -> constraints::ConstraintReport {
        constraints::check_all(constraints, &self.module)
    }

    /// Find functions matching a name pattern (simple substring match).
    pub fn find_functions(&self, pattern: &str) -> Vec<FuncSummary> {
        self.module
            .functions()
            .iter()
            .filter(|f| pattern.is_empty() || f.name.contains(pattern))
            .map(|f| FuncSummary {
                id: f.id.to_string(),
                name: f.name.clone(),
                params: f
                    .params
                    .iter()
                    .map(|p| ParamSummary {
                        name: p.name.clone(),
                        param_type: p.param_type.to_type_str(),
                    })
                    .collect(),
                returns: f.returns.to_type_str(),
                effects: f.effects.iter().map(|e| e.to_effect_str()).collect(),
                node_count: count_nodes(&f.body),
            })
            .collect()
    }

    /// Get call graph edges for a function.
    pub fn get_call_graph(&self, func_name: &str) -> Vec<CallEdge> {
        let mut edges = Vec::new();
        if let Some(func) = self.module.find_function(func_name) {
            collect_calls(&func.body, &func.name, &mut edges);
        }
        edges
    }

    /// Get effect summary for a function.
    pub fn get_effect_summary(&self, func_name: &str) -> Option<EffectSummary> {
        self.module.find_function(func_name).map(|f| EffectSummary {
            func_name: f.name.clone(),
            declared_effects: f.effects.iter().map(|e| e.to_effect_str()).collect(),
        })
    }
}

/// Result of successfully applying a patch via [`Project::apply_patch`].
#[derive(Clone, Debug, Serialize)]
pub struct PatchApplyResult {
    /// The new content-addressed version hash after the patch.
    pub new_version: String,
    /// Which functions/modules were affected by the patch.
    pub impact: Impact,
}

/// Result of previewing a patch via [`Project::preview_patch`].
#[derive(Clone, Debug, Serialize)]
pub struct PatchPreviewResult {
    /// True if the patch would succeed (validation passes and types check).
    pub would_succeed: bool,
    /// Validation error message if the patch cannot be applied structurally.
    pub validation_error: Option<String>,
    /// Type errors that would arise after applying the patch.
    pub type_errors: Vec<String>,
    /// Which functions/modules would be affected.
    pub impact: Impact,
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn count_nodes(node: &Node) -> usize {
    1 + match node {
        Node::Literal { .. } | Node::Param { .. } | Node::Error { .. } => 0,
        Node::Let { value, body, .. } => count_nodes(value) + count_nodes(body),
        Node::If {
            cond,
            then_branch,
            else_branch,
            ..
        } => count_nodes(cond) + count_nodes(then_branch) + count_nodes(else_branch),
        Node::Call { args, .. } => args.iter().map(count_nodes).sum(),
        Node::Return { value, .. } => count_nodes(value),
        Node::BinOp { lhs, rhs, .. } => count_nodes(lhs) + count_nodes(rhs),
        Node::UnaryOp { operand, .. } => count_nodes(operand),
        Node::Block {
            statements, result, ..
        } => statements.iter().map(count_nodes).sum::<usize>() + count_nodes(result),
        Node::Loop { body, .. } => count_nodes(body),
        Node::Match {
            scrutinee, arms, ..
        } => count_nodes(scrutinee) + arms.iter().map(|a| count_nodes(&a.body)).sum::<usize>(),
        Node::StructLiteral { fields, .. } => fields.iter().map(|(_, n)| count_nodes(n)).sum(),
        Node::FieldAccess { object, .. } => count_nodes(object),
        Node::ArrayLiteral { elements, .. } => elements.iter().map(count_nodes).sum(),
        Node::IndexAccess { array, index, .. } => count_nodes(array) + count_nodes(index),
    }
}

fn collect_calls(node: &Node, current_func: &str, edges: &mut Vec<CallEdge>) {
    match node {
        Node::Call { target, args, .. } => {
            edges.push(CallEdge {
                from: current_func.to_string(),
                to: target.clone(),
            });
            for arg in args {
                collect_calls(arg, current_func, edges);
            }
        }
        Node::Let { value, body, .. } => {
            collect_calls(value, current_func, edges);
            collect_calls(body, current_func, edges);
        }
        Node::If {
            cond,
            then_branch,
            else_branch,
            ..
        } => {
            collect_calls(cond, current_func, edges);
            collect_calls(then_branch, current_func, edges);
            collect_calls(else_branch, current_func, edges);
        }
        Node::BinOp { lhs, rhs, .. } => {
            collect_calls(lhs, current_func, edges);
            collect_calls(rhs, current_func, edges);
        }
        Node::UnaryOp { operand, .. } => collect_calls(operand, current_func, edges),
        Node::Return { value, .. } => collect_calls(value, current_func, edges),
        Node::Block {
            statements, result, ..
        } => {
            for s in statements {
                collect_calls(s, current_func, edges);
            }
            collect_calls(result, current_func, edges);
        }
        Node::Match {
            scrutinee, arms, ..
        } => {
            collect_calls(scrutinee, current_func, edges);
            for arm in arms {
                collect_calls(&arm.body, current_func, edges);
            }
        }
        _ => {}
    }
}

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

    fn hello_json() -> &'static str {
        r#"{
            "format_version": "0.1.0",
            "module": {
                "id": "mod_main", "name": "main",
                "metadata": {"version": "1.0.0", "description": "", "author": "", "created_at": ""},
                "imports": [{"module": "std::io", "items": ["println"]}],
                "exports": [], "types": [],
                "functions": [{
                    "id": "f_main", "name": "main", "params": [], "returns": "Unit",
                    "effects": ["IO"],
                    "body": {"id": "n_1", "kind": "Call", "type": "Unit",
                        "target": "std::io::println",
                        "args": [{"id": "n_2", "kind": "Literal", "type": "String", "value": "hello"}]
                    }
                }]
            }
        }"#
    }

    #[test]
    fn test_create_project() {
        let project = Project::from_json("test", hello_json()).unwrap();
        assert_eq!(project.name, "test");
        assert!(!project.version.is_empty());
        assert_eq!(project.module.functions().len(), 1);
    }

    #[test]
    fn test_apply_and_undo_patch() {
        let mut project = Project::from_json("test", hello_json()).unwrap();
        let v1 = project.version.clone();

        let patch = Patch {
            id: "p1".to_string(),
            parent_version: v1.clone(),
            operations: vec![airl_patch::PatchOp::ReplaceNode {
                target: airl_ir::NodeId::new("n_2"),
                replacement: airl_ir::node::Node::Literal {
                    id: airl_ir::NodeId::new("n_2"),
                    node_type: airl_ir::types::Type::String,
                    value: airl_ir::node::LiteralValue::Str("changed".to_string()),
                },
            }],
            rationale: "test".to_string(),
            author: "agent".to_string(),
        };

        let result = project.apply_patch(&patch).unwrap();
        assert_ne!(result.new_version, v1);
        assert_eq!(project.history.len(), 1);

        // Undo
        project.undo_last().unwrap();
        assert_eq!(project.version, v1);
        assert_eq!(project.history.len(), 0);
    }

    #[test]
    fn test_preview_patch() {
        let project = Project::from_json("test", hello_json()).unwrap();
        let patch = Patch {
            id: "p1".to_string(),
            parent_version: String::new(),
            operations: vec![airl_patch::PatchOp::ReplaceNode {
                target: airl_ir::NodeId::new("n_2"),
                replacement: airl_ir::node::Node::Literal {
                    id: airl_ir::NodeId::new("n_2"),
                    node_type: airl_ir::types::Type::String,
                    value: airl_ir::node::LiteralValue::Str("preview".to_string()),
                },
            }],
            rationale: "test".to_string(),
            author: "agent".to_string(),
        };

        let preview = project.preview_patch(&patch).unwrap();
        assert!(preview.would_succeed);
    }

    #[test]
    fn test_find_functions() {
        let project = Project::from_json("test", hello_json()).unwrap();
        let funcs = project.find_functions("main");
        assert_eq!(funcs.len(), 1);
        assert_eq!(funcs[0].name, "main");
    }

    #[test]
    fn test_get_call_graph() {
        let project = Project::from_json("test", hello_json()).unwrap();
        let edges = project.get_call_graph("main");
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].to, "std::io::println");
    }

    #[test]
    fn test_get_effect_summary() {
        let project = Project::from_json("test", hello_json()).unwrap();
        let summary = project.get_effect_summary("main").unwrap();
        assert!(summary.declared_effects.contains(&"IO".to_string()));
    }

    #[test]
    fn test_typecheck() {
        let project = Project::from_json("test", hello_json()).unwrap();
        let result = project.typecheck();
        assert!(result.is_ok());
    }

    #[test]
    fn test_undo_empty_fails() {
        let mut project = Project::from_json("test", hello_json()).unwrap();
        assert!(project.undo_last().is_err());
    }
}