agit 1.3.0

AI-native Git wrapper for capturing context alongside code
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
//! Implementation of the agit_log_step MCP tool.
//!
//! This tool allows AI editors to log steps (intents, reasoning) to the
//! AGIT index for later association with commits.
//!
//! Supports both single-entry mode (backward compatible) and batch mode
//! for efficiency in environments with tool authorization popups.

use std::path::Path;

use serde_json::Value;
use tracing::{debug, error, warn};

use crate::core::ensure_sync;
use crate::domain::{Category, IndexEntry, Location, Role};
#[cfg(test)]
use crate::mcp::protocol::ToolContent;
use crate::mcp::protocol::{LocationInput, LogEntry, LogStepParams, ToolCallResult};
use crate::safety::validate_path_is_internal;
use crate::storage::{FileIndexStore, IndexStore};

/// Convert LocationInput (MCP protocol) to Location (domain).
fn convert_location(input: &LocationInput) -> Location {
    Location {
        file: input.file.clone(),
        start_line: input.start_line,
        end_line: input.end_line,
    }
}

/// Convert legacy file_path/line_number to a single Location.
fn legacy_to_location(file_path: &str, line_number: Option<u32>) -> Location {
    Location {
        file: file_path.to_string(),
        start_line: line_number,
        end_line: None,
    }
}

/// Execute the agit_log_step tool.
pub fn execute(agit_dir: &Path, arguments: Option<Value>) -> ToolCallResult {
    // Parse arguments
    let args = match arguments {
        Some(v) => v,
        None => {
            return ToolCallResult::error("Missing arguments for agit_log_step");
        },
    };

    let params: LogStepParams = match serde_json::from_value(args) {
        Ok(p) => p,
        Err(e) => {
            error!("Invalid params for agit_log_step: {}", e);
            return ToolCallResult::error(&format!("Invalid parameters: {}", e));
        },
    };

    // Check if agit is initialized
    if !agit_dir.exists() {
        return ToolCallResult::error("AGIT not initialized. Run 'agit init' first.");
    }

    // Ensure branch sync (derive project root from agit_dir)
    if let Some(project_root) = agit_dir.parent() {
        if let Err(e) = ensure_sync(project_root, agit_dir) {
            warn!("Branch sync failed: {}", e);
            // Continue anyway - sync failure shouldn't block logging
        }
    }

    // Determine if batch or single mode
    if let Some(batch) = params.batch {
        // Batch mode - process multiple entries
        execute_batch(agit_dir, batch)
    } else if let (Some(role), Some(category), Some(content)) =
        (params.role, params.category, params.content)
    {
        // Single mode (backward compatible)
        execute_single(
            agit_dir,
            &role,
            &category,
            &content,
            params.locations.as_ref(),
            params.file_path.as_deref(),
            params.line_number,
        )
    } else {
        ToolCallResult::error(
            "Invalid parameters: provide either 'batch' array or 'role', 'category', 'content'",
        )
    }
}

/// Execute batch logging - multiple entries in one call.
fn execute_batch(agit_dir: &Path, entries: Vec<LogEntry>) -> ToolCallResult {
    if entries.is_empty() {
        return ToolCallResult::text("No entries to log");
    }

    // Derive repo root from agit_dir
    let repo_root = match agit_dir.parent() {
        Some(root) => root,
        None => return ToolCallResult::error("Cannot determine repository root"),
    };

    let index_store = FileIndexStore::new(agit_dir);
    let mut logged = 0;
    let mut errors = Vec::new();
    let mut rejected_paths = Vec::new();

    for entry in &entries {
        // Collect and validate locations (new format or legacy)
        let locations: Vec<Location> = if let Some(ref locs) = entry.locations {
            // New locations array format
            let mut valid_locs = Vec::new();
            for loc in locs {
                if let Err(e) = validate_path_is_internal(repo_root, &loc.file) {
                    rejected_paths.push(format!("{}: {}", loc.file, e));
                    // Continue to check other locations, don't skip entire entry
                } else {
                    valid_locs.push(convert_location(loc));
                }
            }
            valid_locs
        } else if let Some(ref file_path) = entry.file_path {
            // Legacy file_path/line_number format
            if let Err(e) = validate_path_is_internal(repo_root, file_path) {
                rejected_paths.push(format!("{}: {}", file_path, e));
                continue; // Skip this entry entirely for legacy format
            }
            vec![legacy_to_location(file_path, entry.line_number)]
        } else {
            // No locations specified
            vec![]
        };

        // Validate role
        let role = match entry.role.to_lowercase().as_str() {
            "user" => Role::User,
            "ai" => Role::Ai,
            _ => {
                errors.push(format!("Invalid role '{}'", entry.role));
                continue;
            },
        };

        // Validate category
        let category = match entry.category.to_lowercase().as_str() {
            "intent" => Category::Intent,
            "reasoning" => Category::Reasoning,
            "error" => Category::Error,
            _ => {
                errors.push(format!("Invalid category '{}'", entry.category));
                continue;
            },
        };

        // Create and append entry with locations
        let index_entry = IndexEntry::with_locations(role, category, &entry.content, locations);
        if let Err(e) = index_store.append(&index_entry) {
            errors.push(format!("Failed to log: {}", e));
            continue;
        }

        logged += 1;
        debug!(
            "Logged: {}/{} - {}",
            entry.role,
            entry.category,
            truncate(&entry.content, 50)
        );
    }

    // Build response
    if !rejected_paths.is_empty() {
        let rejection_msg = format!(
            "â›” {} entries rejected (outside repository scope):\n{}\n\nAgit is a single-repo tool. Use `cd` to switch to the correct repository before logging context for those files.",
            rejected_paths.len(),
            rejected_paths.join("\n")
        );

        if logged == 0 && errors.is_empty() {
            return ToolCallResult::error(&rejection_msg);
        } else {
            // Some entries logged, but some rejected
            let mut msg = format!("Logged {} entries.", logged);
            if !errors.is_empty() {
                msg.push_str(&format!(" {} errors: {}", errors.len(), errors.join("; ")));
            }
            msg.push_str(&format!("\n{}", rejection_msg));
            return ToolCallResult::text(&msg);
        }
    }

    if errors.is_empty() {
        ToolCallResult::text(&format!("Logged {} entries", logged))
    } else if logged > 0 {
        ToolCallResult::text(&format!(
            "Logged {} entries with {} errors: {}",
            logged,
            errors.len(),
            errors.join("; ")
        ))
    } else {
        ToolCallResult::error(&format!("All entries failed: {}", errors.join("; ")))
    }
}

/// Execute single entry logging (backward compatible).
fn execute_single(
    agit_dir: &Path,
    role: &str,
    category: &str,
    content: &str,
    locations: Option<&Vec<LocationInput>>,
    file_path: Option<&str>,
    line_number: Option<u32>,
) -> ToolCallResult {
    // Derive repo root from agit_dir
    let repo_root = match agit_dir.parent() {
        Some(root) => root,
        None => return ToolCallResult::error("Cannot determine repository root"),
    };

    // Collect and validate locations (new format or legacy)
    let mut rejected_paths = Vec::new();
    let validated_locations: Vec<Location> = if let Some(locs) = locations {
        // New locations array format
        let mut valid_locs = Vec::new();
        for loc in locs {
            if let Err(e) = validate_path_is_internal(repo_root, &loc.file) {
                rejected_paths.push(format!("{}: {}", loc.file, e));
            } else {
                valid_locs.push(convert_location(loc));
            }
        }
        valid_locs
    } else if let Some(fp) = file_path {
        // Legacy file_path/line_number format
        if let Err(e) = validate_path_is_internal(repo_root, fp) {
            return ToolCallResult::error(&format!(
                "â›” Path rejected: {}\n\nAgit is a single-repo tool. Use `cd` to switch to the correct repository before logging context for external files.",
                e
            ));
        }
        vec![legacy_to_location(fp, line_number)]
    } else {
        // No locations specified
        vec![]
    };

    // Warn about rejected paths (but continue if some are valid)
    if !rejected_paths.is_empty() && validated_locations.is_empty() {
        return ToolCallResult::error(&format!(
            "â›” All paths rejected:\n{}\n\nAgit is a single-repo tool.",
            rejected_paths.join("\n")
        ));
    }

    // Validate role
    let role_enum = match role.to_lowercase().as_str() {
        "user" => Role::User,
        "ai" => Role::Ai,
        _ => {
            return ToolCallResult::error(&format!(
                "Invalid role '{}'. Must be 'user' or 'ai'",
                role
            ));
        },
    };

    // Validate category
    let category_enum = match category.to_lowercase().as_str() {
        "intent" => Category::Intent,
        "reasoning" => Category::Reasoning,
        "error" => Category::Error,
        _ => {
            return ToolCallResult::error(&format!(
                "Invalid category '{}'. Must be 'intent', 'reasoning', or 'error'",
                category
            ));
        },
    };

    // Create and append entry with locations
    let entry = IndexEntry::with_locations(role_enum, category_enum, content, validated_locations);
    let index_store = FileIndexStore::new(agit_dir);

    if let Err(e) = index_store.append(&entry) {
        error!("Failed to append to index: {}", e);
        return ToolCallResult::error(&format!("Failed to log step: {}", e));
    }

    debug!("Logged step: {}/{} - {}", role, category, content);
    ToolCallResult::text(&format!(
        "Logged: [{}/{}] {}",
        role,
        category,
        truncate(content, 50)
    ))
}

/// Truncate a string for display.
fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len - 3])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    /// Extract text from ToolContent for assertions.
    fn get_text(content: &ToolContent) -> &str {
        match content {
            ToolContent::Text { text } => text,
        }
    }

    fn setup_agit_dir() -> TempDir {
        let temp = TempDir::new().unwrap();
        let agit_dir = temp.path().join(".agit");
        std::fs::create_dir_all(&agit_dir).unwrap();
        std::fs::write(agit_dir.join("index"), "").unwrap();
        temp
    }

    #[test]
    fn test_log_step_user_intent() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "role": "user",
            "category": "intent",
            "content": "Fix the authentication bug"
        });

        let result = execute(&agit_dir, Some(args));
        assert!(result.is_error.is_none());
    }

    #[test]
    fn test_log_step_ai_reasoning() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "role": "ai",
            "category": "reasoning",
            "content": "I'll add a try/catch block"
        });

        let result = execute(&agit_dir, Some(args));
        assert!(result.is_error.is_none());
    }

    #[test]
    fn test_log_step_invalid_role() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "role": "invalid",
            "category": "intent",
            "content": "Test"
        });

        let result = execute(&agit_dir, Some(args));
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn test_log_step_not_initialized() {
        let temp = TempDir::new().unwrap();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "role": "user",
            "category": "intent",
            "content": "Test"
        });

        let result = execute(&agit_dir, Some(args));
        assert_eq!(result.is_error, Some(true));
    }

    #[test]
    fn test_log_step_batch_mode() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "batch": [
                {"role": "user", "category": "intent", "content": "Fix the bug"},
                {"role": "ai", "category": "reasoning", "content": "Found the issue"},
                {"role": "ai", "category": "reasoning", "content": "Applied fix"}
            ]
        });

        let result = execute(&agit_dir, Some(args));
        assert!(result.is_error.is_none());
        assert!(get_text(&result.content[0]).contains("3 entries"));
    }

    #[test]
    fn test_log_step_batch_empty() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "batch": []
        });

        let result = execute(&agit_dir, Some(args));
        assert!(result.is_error.is_none());
        assert!(get_text(&result.content[0]).contains("No entries"));
    }

    #[test]
    fn test_log_step_batch_partial_errors() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        let args = json!({
            "batch": [
                {"role": "user", "category": "intent", "content": "Valid entry"},
                {"role": "invalid", "category": "intent", "content": "Invalid role"},
                {"role": "ai", "category": "reasoning", "content": "Another valid"}
            ]
        });

        let result = execute(&agit_dir, Some(args));
        // Should succeed with partial errors
        assert!(result.is_error.is_none());
        let text = get_text(&result.content[0]);
        assert!(text.contains("2 entries"));
        assert!(text.contains("error"));
    }

    #[test]
    fn test_log_step_missing_params() {
        let temp = setup_agit_dir();
        let agit_dir = temp.path().join(".agit");

        // Neither batch nor single-entry params
        let args = json!({
            "role": "user"
        });

        let result = execute(&agit_dir, Some(args));
        assert_eq!(result.is_error, Some(true));
    }
}