magi-code 0.96.1

Repository-aware CLI coding agent for terminal work
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
use super::{
    capture::{CHECKPOINT_SCHEMA_VERSION, LedgerRead, SnapshotBlobRef, SnapshotLedgerRecord},
    sanitized_diagnostic,
};
use crate::{
    config::McPaths,
    persistence::{CrossProcessFileLock, atomic_write_with_permissions, sync_parent_dir},
    sessions::SESSION_FILE_MODE,
};
use sha2::{Digest, Sha256};
use std::{
    error::Error,
    fmt, fs,
    io::{ErrorKind, Read, Seek, SeekFrom, Write},
    path::{Path, PathBuf},
};

#[derive(Debug)]
pub(crate) enum CheckpointAppendFailure {
    OutcomeUncertain {
        path: PathBuf,
        source: anyhow::Error,
    },
    CommittedButUndurable {
        path: PathBuf,
        source: anyhow::Error,
    },
}

impl CheckpointAppendFailure {
    fn uncertain(path: &Path, source: anyhow::Error) -> anyhow::Error {
        anyhow::Error::new(Self::OutcomeUncertain {
            path: path.to_path_buf(),
            source,
        })
    }

    fn committed_but_undurable(path: &Path, source: anyhow::Error) -> anyhow::Error {
        anyhow::Error::new(Self::CommittedButUndurable {
            path: path.to_path_buf(),
            source,
        })
    }
}

impl fmt::Display for CheckpointAppendFailure {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (path, outcome) = match self {
            Self::OutcomeUncertain { path, .. } => {
                (path, "append outcome is uncertain; do not retry blindly")
            }
            Self::CommittedButUndurable { path, .. } => (
                path,
                "record is visible but final synchronization failed; do not retry blindly",
            ),
        };
        write!(
            formatter,
            "checkpoint ledger append failed for {}: {outcome}",
            path.display()
        )
    }
}

impl Error for CheckpointAppendFailure {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        let source = match self {
            Self::OutcomeUncertain { source, .. } | Self::CommittedButUndurable { source, .. } => {
                source
            }
        };
        Some(source.as_ref())
    }
}

#[derive(Debug, Default)]
struct LedgerIoMetrics {
    read_bytes: u64,
    write_bytes: u64,
    serialized_record_bytes: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CheckpointStore {
    pub(super) root: PathBuf,
}

impl CheckpointStore {
    pub(crate) fn new(root: PathBuf) -> Self {
        Self { root }
    }

    pub(crate) fn from_paths(paths: &McPaths) -> Self {
        Self::new(paths.checkpoints.clone())
    }

    pub(crate) fn copy_before_turn(
        &self,
        source: &str,
        target: &str,
        turn: u64,
    ) -> anyhow::Result<()> {
        crate::sessions::validate_session_id(source.to_owned())?;
        crate::sessions::validate_session_id(target.to_owned())?;
        let read = self.read_records(source);
        anyhow::ensure!(
            read.diagnostics.is_empty(),
            "cannot copy unreadable file checkpoints"
        );
        for mut record in read
            .records
            .into_iter()
            .filter(|record| record.event.user_turn < turn)
        {
            record.event.session_id = target.to_owned();
            self.append_record(&record)?;
        }
        Ok(())
    }

    pub(super) fn blobs_dir(&self) -> PathBuf {
        self.root.join("blobs")
    }

    pub(super) fn ledgers_dir(&self) -> PathBuf {
        self.root.join("ledgers")
    }

    pub(super) fn ledger_path(&self, session_id: &str) -> PathBuf {
        self.ledgers_dir().join(format!("{session_id}.jsonl"))
    }

    pub(super) fn blob_path(&self, sha256: &str) -> PathBuf {
        self.blobs_dir().join(sha256)
    }

    fn mutation_lock_target(&self) -> PathBuf {
        self.root.with_file_name("checkpoint-store")
    }

    pub(super) fn lock_mutations(&self) -> anyhow::Result<CrossProcessFileLock> {
        CrossProcessFileLock::acquire(&self.mutation_lock_target())
    }

    pub(super) fn write_blob(&self, bytes: &[u8]) -> anyhow::Result<SnapshotBlobRef> {
        let sha256 = sha256_hex(bytes);
        let path = self.blob_path(&sha256);
        if path.exists() {
            return Ok(SnapshotBlobRef {
                sha256,
                bytes: bytes.len() as u64,
            });
        }
        create_private_dir_all(&self.blobs_dir())?;
        atomic_write_with_permissions(&path, bytes, Some(SESSION_FILE_MODE))?;
        Ok(SnapshotBlobRef {
            sha256,
            bytes: bytes.len() as u64,
        })
    }

    pub(super) fn read_blob(&self, blob: &SnapshotBlobRef) -> anyhow::Result<Vec<u8>> {
        let bytes = fs::read(self.blob_path(&blob.sha256))?;
        if sha256_hex(&bytes) != blob.sha256 {
            anyhow::bail!("checkpoint blob hash mismatch");
        }
        Ok(bytes)
    }

    pub(super) fn append_record(&self, record: &SnapshotLedgerRecord) -> anyhow::Result<()> {
        self.append_record_with(
            record,
            None,
            |file| file.sync_all().map_err(anyhow::Error::from),
            sync_parent_dir,
        )
    }

    fn append_record_with(
        &self,
        record: &SnapshotLedgerRecord,
        mut metrics: Option<&mut LedgerIoMetrics>,
        sync_file: impl FnOnce(&fs::File) -> anyhow::Result<()>,
        sync_parent: impl FnOnce(&Path) -> anyhow::Result<()>,
    ) -> anyhow::Result<()> {
        crate::sessions::validate_session_id(record.event.session_id.clone())?;
        let ledger = self.ledger_path(&record.event.session_id);
        if let Some(parent) = ledger.parent() {
            create_private_dir_all(parent)?;
        }
        let mut line = serde_json::to_vec(record)?;
        line.push(b'\n');
        if let Some(metrics) = metrics.as_deref_mut() {
            metrics.serialized_record_bytes += line.len() as u64;
        }

        let _lock = CrossProcessFileLock::acquire(&ledger)?;
        let (mut file, created) = open_ledger_for_append(&ledger)?;
        let pre_append_len = file.metadata()?.len();
        let needs_separator = if pre_append_len == 0 {
            false
        } else {
            file.seek(SeekFrom::End(-1))?;
            let mut tail = [0_u8; 1];
            file.read_exact(&mut tail)?;
            if let Some(metrics) = metrics.as_deref_mut() {
                metrics.read_bytes += 1;
            }
            tail[0] != b'\n'
        };
        if needs_separator {
            line.insert(0, b'\n');
        }
        if let Some(metrics) = metrics {
            metrics.write_bytes += line.len() as u64;
        }

        if let Err(write_error) = file.write_all(&line) {
            let rollback = file.set_len(pre_append_len).and_then(|()| file.sync_all());
            return match rollback {
                Ok(()) => Err(anyhow::Error::new(write_error).context(
                    "checkpoint ledger append failed; partial data was durably rolled back",
                )),
                Err(rollback_error) => Err(CheckpointAppendFailure::uncertain(
                    &ledger,
                    anyhow::anyhow!(
                        "append write failed ({write_error}); rollback failed ({rollback_error})"
                    ),
                )),
            };
        }
        file.flush().map_err(|error| {
            CheckpointAppendFailure::committed_but_undurable(&ledger, error.into())
        })?;
        sync_file(&file)
            .map_err(|error| CheckpointAppendFailure::committed_but_undurable(&ledger, error))?;
        if created {
            let parent = ledger
                .parent()
                .ok_or_else(|| anyhow::anyhow!("checkpoint ledger has no parent"))?;
            sync_parent(parent).map_err(|error| {
                CheckpointAppendFailure::committed_but_undurable(&ledger, error)
            })?;
        }
        Ok(())
    }

    pub(crate) fn read_records(&self, session_id: &str) -> LedgerRead {
        let ledger = self.ledger_path(session_id);
        let mut read = LedgerRead::default();
        let bytes = match fs::read(&ledger) {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == ErrorKind::NotFound => return read,
            Err(error) => {
                read.diagnostics.push(sanitized_diagnostic(format!(
                    "checkpoint ledger read failed: {error}"
                )));
                return read;
            }
        };
        let final_segment = bytes.split(|byte| *byte == b'\n').count().saturating_sub(1);
        let has_terminated_tail = bytes.ends_with(b"\n");
        for (index, line) in bytes.split(|byte| *byte == b'\n').enumerate() {
            if line.iter().all(u8::is_ascii_whitespace) {
                continue;
            }
            match serde_json::from_slice::<SnapshotLedgerRecord>(line) {
                Ok(record) if record.schema_version == CHECKPOINT_SCHEMA_VERSION => {
                    read.records.push(record);
                }
                Ok(_) => read.diagnostics.push(format!(
                    "ignored checkpoint ledger line {}: unsupported_schema_version",
                    index + 1
                )),
                Err(_) if index == final_segment && !has_terminated_tail => {
                    read.diagnostics.push(format!(
                        "ignored checkpoint ledger line {}: incomplete_tail",
                        index + 1
                    ))
                }
                Err(_) => read.diagnostics.push(format!(
                    "ignored checkpoint ledger line {}: malformed_json",
                    index + 1
                )),
            }
        }
        read
    }

    pub(crate) fn prune_session(&self, session_id: &str) -> anyhow::Result<()> {
        if !self.validate_deletion_directories()? {
            return Ok(());
        }
        let _mutation_lock = self.lock_mutations()?;
        if !self.validate_deletion_directories()? {
            return Ok(());
        }
        let ledger = self.ledger_path(session_id);
        if ledger.exists() {
            fs::remove_file(&ledger)?;
        }
        self.prune_unreferenced_blobs_locked()
    }

    pub(crate) fn prune_unreferenced_blobs(&self) -> anyhow::Result<()> {
        if !self.validate_deletion_directories()? {
            return Ok(());
        }
        let _mutation_lock = self.lock_mutations()?;
        if !self.validate_deletion_directories()? {
            return Ok(());
        }
        self.prune_unreferenced_blobs_locked()
    }

    fn validate_deletion_directories(&self) -> anyhow::Result<bool> {
        if !validate_owned_directory(&self.root)? {
            return Ok(false);
        }
        for path in [self.ledgers_dir(), self.blobs_dir()] {
            match fs::symlink_metadata(&path) {
                Ok(_) => {
                    if !validate_owned_directory(&path)? {
                        anyhow::bail!("unsafe checkpoint directory: {}", path.display());
                    }
                }
                Err(error) if error.kind() == ErrorKind::NotFound => {}
                Err(error) => return Err(error.into()),
            }
        }
        Ok(true)
    }

    fn prune_unreferenced_blobs_locked(&self) -> anyhow::Result<()> {
        let mut referenced = std::collections::BTreeSet::new();
        let ledgers = self.ledgers_dir();
        if ledgers.exists() {
            for entry in fs::read_dir(&ledgers)? {
                let entry = entry?;
                let file_type = entry.file_type()?;
                if file_type.is_symlink() {
                    anyhow::bail!("unsafe checkpoint ledger entry");
                }
                if !file_type.is_file() {
                    continue;
                }
                let file_name = entry
                    .file_name()
                    .into_string()
                    .map_err(|_| anyhow::anyhow!("checkpoint ledger name is not UTF-8"))?;
                let Some(session_id) = file_name.strip_suffix(".jsonl") else {
                    continue;
                };
                crate::sessions::validate_session_id(session_id.to_string())?;
                let read = self.read_records(session_id);
                if !read.diagnostics.is_empty() {
                    anyhow::bail!("checkpoint ledger could not be read completely");
                }
                for record in read.records {
                    if let Some(blob) = record.event.pre {
                        referenced.insert(blob.sha256);
                    }
                    if let Some(blob) = record.event.post {
                        referenced.insert(blob.sha256);
                    }
                }
            }
        }
        let blobs = self.blobs_dir();
        if !blobs.exists() {
            return Ok(());
        }
        for entry in fs::read_dir(&blobs)? {
            let entry = entry?;
            if !entry.file_type()?.is_file() {
                continue;
            }
            let name = entry.file_name().to_string_lossy().into_owned();
            if !referenced.contains(&name) {
                fs::remove_file(entry.path())?;
            }
        }
        Ok(())
    }
}

fn open_ledger_for_append(path: &Path) -> anyhow::Result<(fs::File, bool)> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => {
            anyhow::bail!("unsafe checkpoint ledger entry")
        }
        Ok(_) => {
            let file = fs::OpenOptions::new().read(true).append(true).open(path)?;
            ensure_open_ledger_matches_path(&file, path)?;
            Ok((file, false))
        }
        Err(error) if error.kind() == ErrorKind::NotFound => {
            let file = fs::OpenOptions::new()
                .read(true)
                .append(true)
                .create_new(true)
                .open(path)?;
            ensure_open_ledger_matches_path(&file, path)?;
            Ok((file, true))
        }
        Err(error) => Err(error.into()),
    }
}

fn ensure_open_ledger_matches_path(file: &fs::File, path: &Path) -> anyhow::Result<()> {
    let path_metadata = fs::symlink_metadata(path)?;
    let file_metadata = file.metadata()?;
    if path_metadata.file_type().is_symlink()
        || !path_metadata.is_file()
        || !file_metadata.is_file()
    {
        anyhow::bail!("unsafe checkpoint ledger entry");
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if path_metadata.dev() != file_metadata.dev()
            || path_metadata.ino() != file_metadata.ino()
            // SAFETY: geteuid has no preconditions and only reads process identity.
            || file_metadata.uid() != unsafe { libc::geteuid() }
        {
            anyhow::bail!("unsafe checkpoint ledger entry");
        }
    }
    Ok(())
}

/// Creates checkpoint directories owner-only: snapshots may hold `.env` files and credentials.
fn create_private_dir_all(path: &Path) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        fs::DirBuilder::new()
            .recursive(true)
            .mode(crate::sessions::SESSION_ROOT_MODE)
            .create(path)
    }
    #[cfg(not(unix))]
    {
        fs::create_dir_all(path)
    }
}

fn validate_owned_directory(path: &std::path::Path) -> anyhow::Result<bool> {
    let metadata = match fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error.into()),
    };
    if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
        anyhow::bail!("unsafe checkpoint directory: {}", path.display());
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if metadata.uid() != unsafe { libc::geteuid() } {
            anyhow::bail!("checkpoint directory is not owned by the current user");
        }
    }
    Ok(true)
}

pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    crate::hex::lower_hex(digest)
}