magi-cli 0.281.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
//! Windows process-tree containment and file locking (kernel32 job objects).
//!
//! Native job objects close the whole Windows process tree when their owner
//! exits, even involuntarily. The launch gate stays closed until assignment.

use std::ffi::c_void;

type Handle = *mut c_void;
#[repr(C)]
#[derive(Default)]
struct Overlapped {
    internal: usize,
    internal_high: usize,
    offset: u32,
    offset_high: u32,
    event: Handle,
}
#[repr(C)]
#[derive(Default)]
struct BasicLimits {
    process_time: i64,
    job_time: i64,
    flags: u32,
    min_working_set: usize,
    max_working_set: usize,
    active_processes: u32,
    affinity: usize,
    priority: u32,
    scheduling: u32,
}
#[repr(C)]
#[derive(Default)]
struct ExtendedLimits {
    basic: BasicLimits,
    io: [u64; 6],
    process_memory: usize,
    job_memory: usize,
    peak_process_memory: usize,
    peak_job_memory: usize,
}
#[repr(C)]
#[derive(Default)]
struct ThreadEntry {
    size: u32,
    usage: u32,
    id: u32,
    owner: u32,
    base_priority: i32,
    delta_priority: i32,
    flags: u32,
}
#[repr(C)]
#[derive(Default)]
struct Accounting {
    times: [i64; 4],
    faults: u32,
    total: u32,
    active: u32,
    terminated: u32,
}
#[link(name = "kernel32")]
unsafe extern "system" {
    fn LockFileEx(
        file: Handle,
        flags: u32,
        reserved: u32,
        bytes: u32,
        bytes_high: u32,
        overlapped: *mut Overlapped,
    ) -> i32;
    fn CreateJobObjectW(attributes: Handle, name: *const u16) -> Handle;
    fn SetInformationJobObject(job: Handle, class: i32, info: *const c_void, size: u32) -> i32;
    fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
    fn TerminateJobObject(job: Handle, code: u32) -> i32;
    fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> Handle;
    fn Thread32First(snapshot: Handle, entry: *mut ThreadEntry) -> i32;
    fn Thread32Next(snapshot: Handle, entry: *mut ThreadEntry) -> i32;
    fn OpenThread(access: u32, inherit: i32, id: u32) -> Handle;
    fn ResumeThread(thread: Handle) -> u32;
    fn CloseHandle(handle: Handle) -> i32;
    fn GetCurrentProcess() -> Handle;
    fn IsProcessInJob(process: Handle, job: Handle, result: *mut i32) -> i32;
    fn QueryInformationJobObject(
        job: Handle,
        class: i32,
        info: *mut c_void,
        size: u32,
        returned: *mut u32,
    ) -> i32;
}
pub(crate) fn lock_file_mode(
    file: Handle,
    immediate: bool,
    exclusive: bool,
) -> std::io::Result<bool> {
    let mut overlapped = Overlapped::default();
    let flags = (if exclusive { 2 } else { 0 }) | u32::from(immediate);
    if unsafe { LockFileEx(file, flags, 0, 1, 0, &mut overlapped) } != 0 {
        return Ok(true);
    }
    let error = std::io::Error::last_os_error();
    if immediate && error.raw_os_error() == Some(33) {
        return Ok(false);
    }
    Err(error)
}
/// Detach from the console and request breakaway only when the host allows
/// it. An external ancestor job can still contain and terminate workers.
pub(crate) fn detached_flags() -> std::io::Result<u32> {
    let mut in_job = 0;
    if unsafe { IsProcessInJob(GetCurrentProcess(), std::ptr::null_mut(), &mut in_job) } == 0 {
        return Err(std::io::Error::last_os_error());
    }
    if in_job == 0 {
        return Ok(0x0000_0008 | 0x0000_0200);
    }
    let mut limits = BasicLimits::default();
    if unsafe {
        QueryInformationJobObject(
            std::ptr::null_mut(),
            2,
            std::ptr::from_mut(&mut limits).cast(),
            std::mem::size_of::<BasicLimits>() as u32,
            std::ptr::null_mut(),
        )
    } == 0
    {
        return Err(std::io::Error::last_os_error());
    }
    let detached = 0x0000_0008 | 0x0000_0200;
    if limits.flags & 0x1000 != 0 {
        return Ok(detached);
    } // SILENT_BREAKAWAY_OK
    if limits.flags & 0x0800 != 0 {
        return Ok(detached | 0x0100_0000);
    } // BREAKAWAY_OK
    // Inheriting an external job does not tie a child to this launcher's
    // lifetime. Do not reject nested launches or bypass that job's limits.
    Ok(detached)
}

pub struct Containment(Handle);
// Jobs have no thread affinity; the owned handle moves to the cleanup thread.
unsafe impl Send for Containment {}
impl Containment {
    pub(crate) fn assign_handle(process: Handle) -> std::io::Result<Self> {
        unsafe {
            let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
            if handle.is_null() {
                return Err(std::io::Error::last_os_error());
            }
            let job = Self(handle);
            let mut limits = ExtendedLimits::default();
            limits.basic.flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
            if SetInformationJobObject(
                handle,
                9,
                std::ptr::from_ref(&limits).cast(),
                std::mem::size_of::<ExtendedLimits>() as u32,
            ) == 0
                || AssignProcessToJobObject(handle, process) == 0
            {
                return Err(std::io::Error::last_os_error());
            }
            Ok(job)
        }
    }

    pub(crate) fn resume_suspended(&self, pid: u32) -> std::io::Result<()> {
        use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
        // The suspended process cannot yet create additional threads.
        unsafe {
            let snapshot = CreateToolhelp32Snapshot(4, 0); // TH32CS_SNAPTHREAD
            if snapshot as isize == -1 {
                return Err(std::io::Error::last_os_error());
            }
            let snapshot = OwnedHandle::from_raw_handle(snapshot);
            let mut entry = ThreadEntry {
                size: std::mem::size_of::<ThreadEntry>() as u32,
                ..ThreadEntry::default()
            };
            let mut found = Thread32First(snapshot.as_raw_handle(), &mut entry);
            while found != 0 {
                if entry.owner == pid {
                    let thread = OpenThread(2, 0, entry.id); // THREAD_SUSPEND_RESUME
                    if thread.is_null() {
                        return Err(std::io::Error::last_os_error());
                    }
                    let thread = OwnedHandle::from_raw_handle(thread);
                    return match ResumeThread(thread.as_raw_handle()) {
                        1 => Ok(()),
                        u32::MAX => Err(std::io::Error::last_os_error()),
                        _ => Err(std::io::Error::other("unexpected process suspend count")),
                    };
                }
                entry.size = std::mem::size_of::<ThreadEntry>() as u32;
                found = Thread32Next(snapshot.as_raw_handle(), &mut entry);
            }
        }
        Err(std::io::Error::other("primary thread not found"))
    }

    pub(crate) fn stop_and_wait(&self) {
        let mut info = Accounting::default();
        loop {
            // Failure is unknown, so retain the output leases and retry.
            unsafe {
                TerminateJobObject(self.0, 1);
                if QueryInformationJobObject(
                    self.0,
                    1,
                    std::ptr::from_mut(&mut info).cast(),
                    std::mem::size_of::<Accounting>() as u32,
                    std::ptr::null_mut(),
                ) != 0
                    && info.active == 0
                {
                    return;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
    }
}
impl Drop for Containment {
    fn drop(&mut self) {
        unsafe {
            CloseHandle(self.0);
        }
    }
}