magi-code 0.96.2

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
#[cfg(unix)]
mod archive;
#[cfg(unix)]
mod discovery;
use super::manager::{Session, SessionManager};
#[cfg(unix)]
use super::{
    read::validate_session_id,
    store::{
        SESSION_FILE_MODE, open_existing_named, open_existing_primary, primary_path,
        validate_session_root,
    },
};
use crate::cancellation::AgentCancellation;
#[cfg(unix)]
use crate::persistence::CrossProcessFileLock;
#[cfg(unix)]
use crate::subagents::SubagentsOutput;
#[cfg(unix)]
use crate::{hex::lower_hex, output::sanitize_display_text};
#[cfg(unix)]
use archive::validate_destination;
#[cfg(unix)]
use archive::write_archive;
#[cfg(unix)]
use discovery::add_member;
#[cfg(unix)]
use discovery::add_optional_member;
#[cfg(unix)]
use discovery::checked_source_length;
#[cfg(unix)]
use discovery::collect_child;
#[cfg(unix)]
use discovery::collect_history;
#[cfg(unix)]
use discovery::discover_children;
#[cfg(unix)]
use serde::Serialize;
#[cfg(unix)]
use serde_json::Value;
#[cfg(unix)]
use sha2::{Digest, Sha256};
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::{
    collections::BTreeSet,
    fs::{self, File, OpenOptions},
    io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write},
    sync::atomic::{AtomicU64, Ordering},
};
#[cfg(unix)]
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};

#[cfg(unix)]
pub(crate) const SESSION_EXPORT_MAX_MEMBERS: usize = 10_000;
#[cfg(unix)]
pub(crate) const SESSION_EXPORT_MAX_SOURCE_BYTES: u64 = 1024 * 1024 * 1024;
#[cfg(unix)]
const SESSION_EXPORT_MAX_WARNINGS: usize = 64;
#[cfg(unix)]
const SESSION_EXPORT_MAX_WARNING_CHARS: usize = 500;
#[cfg(unix)]
const SESSION_EXPORT_MAX_DISCOVERY_LINE_BYTES: usize = 8 * 1024 * 1024;
#[cfg(unix)]
const SESSION_EXPORT_TEMP_ATTEMPTS: usize = 32;
#[cfg(unix)]
static NEXT_EXPORT_TEMP: AtomicU64 = AtomicU64::new(1);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SessionExportReport {
    pub(crate) destination: PathBuf,
    pub(crate) member_count: usize,
    pub(crate) source_bytes: u64,
    pub(crate) warnings: Vec<String>,
}

#[cfg(unix)]
struct ExportManifest {
    root_session_id: String,
    members: Vec<SourceMember>,
    relationships: BTreeSet<ExportRelationship>,
    source_bytes: u64,
    warnings: WarningCollector,
    locks: Vec<CrossProcessFileLock>,
    graph_nodes: usize,
}

#[cfg(unix)]
const SESSION_EXPORT_MAX_LOCKS: usize = 64;

#[cfg(unix)]
impl ExportManifest {
    fn charge_graph_node(&mut self) -> anyhow::Result<()> {
        self.graph_nodes = self.graph_nodes.saturating_add(1);
        if self.graph_nodes > SESSION_EXPORT_MAX_MEMBERS {
            anyhow::bail!(
                "session export graph limit exceeded: maximum {SESSION_EXPORT_MAX_MEMBERS} nodes"
            )
        }
        Ok(())
    }

    fn reserve_lock(&self, count: usize) -> anyhow::Result<()> {
        if self.locks.len().saturating_add(count) > SESSION_EXPORT_MAX_LOCKS {
            anyhow::bail!(
                "session export lock limit exceeded: maximum {SESSION_EXPORT_MAX_LOCKS} locks"
            )
        }
        Ok(())
    }

    fn lock_session(
        &mut self,
        path: &Path,
        cancellation: &AgentCancellation,
    ) -> anyhow::Result<()> {
        self.reserve_lock(2)?;
        validate_lock_target(path)?;
        let active = super::manager::active_lease_target(path);
        let deadline = std::time::Instant::now() + crate::persistence::LOCK_WAIT_TIMEOUT;
        self.locks
            .push(CrossProcessFileLock::acquire_until_cancellable(
                &active,
                deadline,
                || cancellation.is_canceled(),
            )?);
        cancellation.check()?;
        let deadline = std::time::Instant::now() + crate::persistence::LOCK_WAIT_TIMEOUT;
        self.locks
            .push(CrossProcessFileLock::acquire_until_cancellable(
                path,
                deadline,
                || cancellation.is_canceled(),
            )?);
        validate_lock_target(path)?;
        Ok(())
    }

    fn lock_jsonl(&mut self, path: &Path, cancellation: &AgentCancellation) -> anyhow::Result<()> {
        self.reserve_lock(1)?;
        validate_lock_target(path)?;
        let deadline = std::time::Instant::now() + crate::persistence::LOCK_WAIT_TIMEOUT;
        self.locks
            .push(CrossProcessFileLock::acquire_until_cancellable(
                path,
                deadline,
                || cancellation.is_canceled(),
            )?);
        validate_lock_target(path)?;
        Ok(())
    }
}

#[cfg(unix)]
fn validate_lock_target(path: &Path) -> anyhow::Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
        anyhow::bail!("session export source is unsafe or not a regular file")
    }
    Ok(())
}

#[cfg(unix)]
struct SourceMember {
    archive_name: String,
    file: File,
    length: u64,
    sha256: String,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[cfg(unix)]
struct ExportRelationship {
    #[serde(rename = "type")]
    relationship_type: &'static str,
    parent_session_id: String,
    child_session_id: String,
}

#[derive(Serialize)]
#[cfg(unix)]
struct ExportManifestDocument {
    schema: &'static str,
    schema_version: u8,
    root_session_id: String,
    member_count: usize,
    source_bytes: u64,
    members: Vec<ExportManifestMember>,
    relationships: Vec<ExportRelationship>,
    completeness: ExportCompleteness,
}

#[derive(Serialize)]
#[cfg(unix)]
struct ExportManifestMember {
    path: String,
    bytes: u64,
    sha256: String,
}

#[derive(Serialize)]
#[cfg(unix)]
struct ExportCompleteness {
    complete: bool,
    omissions: Vec<String>,
}

#[derive(Default, Clone)]
#[cfg(unix)]
struct WarningCollector {
    warnings: Vec<String>,
    omitted: usize,
}

#[cfg(unix)]
impl WarningCollector {
    fn push(&mut self, message: impl AsRef<str>) {
        let message = bounded_warning(message.as_ref());
        if self.warnings.len() < SESSION_EXPORT_MAX_WARNINGS {
            self.warnings.push(message);
        } else {
            self.omitted = self.omitted.saturating_add(1);
        }
    }

    fn finish(&mut self) -> Vec<String> {
        if self.omitted > 0 {
            let omitted = bounded_warning(&format!(
                "omitted {} additional session export warnings",
                self.omitted
            ));
            if self.warnings.len() == SESSION_EXPORT_MAX_WARNINGS {
                self.warnings.pop();
            }
            self.warnings.push(omitted);
            self.omitted = 0;
        }
        std::mem::take(&mut self.warnings)
    }
}

#[cfg(unix)]
fn bounded_warning(message: &str) -> String {
    let sanitized = sanitize_display_text(message);
    let mut chars = sanitized.chars();
    let mut bounded = chars
        .by_ref()
        .take(SESSION_EXPORT_MAX_WARNING_CHARS)
        .collect::<String>();
    if chars.next().is_some() {
        bounded.push('…');
    }
    bounded
}

/// Export one persisted session and its referenced child sessions without invoking a provider.
///
pub(crate) fn export_session(
    manager: &SessionManager,
    session: &Session,
    destination: &Path,
) -> anyhow::Result<SessionExportReport> {
    export_session_with_cancellation(manager, session, destination, &AgentCancellation::default())
}

pub(crate) fn export_session_with_cancellation(
    manager: &SessionManager,
    session: &Session,
    destination: &Path,
    cancellation: &AgentCancellation,
) -> anyhow::Result<SessionExportReport> {
    #[cfg(not(unix))]
    {
        let _ = (manager, session, destination, cancellation);
        anyhow::bail!(
            "session export is Unix-only because private permissions cannot be guaranteed"
        )
    }
    #[cfg(unix)]
    {
        cancellation.check()?;
        let root = &manager.root;
        validate_session_root(root)?;
        validate_session_id(session.id.clone())?;
        let expected_primary = primary_path(root, &session.id)?;
        if session.path != expected_primary {
            anyhow::bail!("session has an unexpected primary path")
        }
        let destination = validate_destination(destination)?;
        let mut manifest = ExportManifest {
            root_session_id: session.id.clone(),
            members: Vec::new(),
            relationships: BTreeSet::new(),
            source_bytes: 0,
            warnings: WarningCollector::default(),
            locks: Vec::new(),
            graph_nodes: 0,
        };
        session.ensure_active_lease()?;
        manifest.lock_jsonl(&expected_primary, cancellation)?;
        let primary = open_existing_primary(root, &session.id)?
            .ok_or_else(|| anyhow::anyhow!("session JSONL is missing"))?;
        let primary_length = checked_source_length(primary.metadata()?.len())?;
        let primary_children = discover_children(
            &primary,
            primary_length,
            root,
            &session.id,
            &mut manifest,
            cancellation,
        )?;
        add_member(
            &mut manifest,
            format!("{}.jsonl", session.id),
            primary,
            cancellation,
        )?;
        add_optional_member(
            &mut manifest,
            root,
            &format!("{}.metadata.json", session.id),
            format!("{}.metadata.json", session.id),
            true,
            cancellation,
        )?;
        let history_children = collect_history(
            &mut manifest,
            root,
            &session.id,
            ".history",
            true,
            cancellation,
        )?;
        let child_root = root.join("subagents");
        let mut pending = primary_children;
        pending.extend(history_children);
        let mut processed = BTreeSet::new();
        while let Some(child_id) = pending.pop_first() {
            cancellation.check()?;
            manifest.charge_graph_node()?;
            if !processed.insert(child_id.clone()) {
                continue;
            }
            let Some(child_children) =
                collect_child(&mut manifest, &child_root, root, &child_id, cancellation)?
            else {
                continue;
            };
            pending.extend(child_children);
        }
        cancellation.check()?;
        let member_count = manifest.members.len();
        let source_bytes = manifest.source_bytes;
        let mut warnings = manifest.warnings.finish();
        write_archive(
            &mut manifest,
            &warnings.clone(),
            &destination,
            cancellation,
            &mut warnings,
        )?;
        Ok(SessionExportReport {
            destination: destination.path,
            member_count,
            source_bytes,
            warnings,
        })
    }
}

pub(crate) fn export_destination(root: &Path, session_id: &str) -> anyhow::Result<PathBuf> {
    #[cfg(not(unix))]
    {
        let _ = (root, session_id);
        anyhow::bail!(
            "session export is Unix-only because private permissions cannot be guaranteed"
        )
    }
    #[cfg(unix)]
    {
        validate_session_id(session_id.to_string())?;
        let directory = prepare_export_directory(root)?;
        let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
        for suffix in 0..SESSION_EXPORT_TEMP_ATTEMPTS {
            let name = if suffix == 0 {
                format!("{session_id}-{stamp}.zip")
            } else {
                format!("{session_id}-{stamp}-{suffix}.zip")
            };
            let path = directory.join(name);
            if !path.exists() {
                return Ok(path);
            }
        }
        anyhow::bail!("could not allocate a unique session export destination")
    }
}

/// Prepare the private directory used for session exports.
///
/// The storage root may retain its existing non-writable-to-others mode (the
/// runtime historically creates it before the session store), but the export
/// directory itself is always owner-private. Existing unsafe directories are
/// rejected rather than repaired implicitly.
#[cfg(unix)]
pub(crate) fn prepare_export_directory(root: &Path) -> anyhow::Result<PathBuf> {
    ensure_export_root(root)?;
    let exports = root.join("exports");
    match fs::symlink_metadata(&exports) {
        Ok(_) => validate_export_directory(&exports)?,
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            use std::os::unix::fs::DirBuilderExt;
            let mut builder = fs::DirBuilder::new();
            builder.mode(0o700);
            builder.create(&exports)?;
            validate_export_directory(&exports)?;
        }
        Err(error) => return Err(error.into()),
    }
    Ok(exports)
}
#[cfg(unix)]
fn ensure_export_root(root: &Path) -> anyhow::Result<()> {
    match fs::symlink_metadata(root) {
        Ok(_) => {}
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            fs::create_dir_all(root)?;
        }
        Err(error) => return Err(error.into()),
    }
    let metadata = fs::symlink_metadata(root)?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
        anyhow::bail!("session export storage root must be a non-symlink directory")
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        // SAFETY: geteuid has no preconditions and only reads process identity.
        let user_id = unsafe { libc::geteuid() };
        if metadata.uid() != user_id {
            anyhow::bail!("session export storage root owner is not current user")
        }
        if metadata.mode() & 0o022 != 0 {
            anyhow::bail!("session export storage root is writable by group or other users")
        }
    }
    Ok(())
}

#[cfg(unix)]
fn validate_export_directory(path: &Path) -> anyhow::Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() {
        anyhow::bail!("session export directory must be a non-symlink directory")
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        // SAFETY: geteuid has no preconditions and only reads process identity.
        let user_id = unsafe { libc::geteuid() };
        if metadata.uid() != user_id {
            anyhow::bail!("session export directory owner is not current user")
        }
        if metadata.mode() & 0o077 != 0 {
            anyhow::bail!("session export directory permissions are not owner-private")
        }
    }
    Ok(())
}