rpi-cli 0.35.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
//! Non-owning plugin cleanup evidence for one CLI preparation and its reloads.
//! This ledger grants nothing and is not proof of process/worker cleanup by itself.
use rpi_extensions::{PluginCleanupReceipt, PluginCleanupStatus, PluginDiagnostics};
use std::sync::{Arc, Mutex};

/// Collect user-facing diagnostics for one load attempt while preserving its
/// cleanup receipts in the session ledger.
pub(crate) struct PluginLoadDiagnostics {
    cleanup: Arc<PluginCleanupLedger>,
    messages: Mutex<(Vec<String>, usize)>,
}

impl PluginLoadDiagnostics {
    pub(crate) fn new(cleanup: Arc<PluginCleanupLedger>) -> Arc<Self> {
        Arc::new(Self {
            cleanup,
            messages: Mutex::default(),
        })
    }

    fn push(&self, message: &str) {
        let mut messages = self.messages.lock().unwrap_or_else(|e| e.into_inner());
        if messages.0.len() >= 32 {
            messages.1 = messages.1.saturating_add(1);
        } else {
            let mut limit = 2048.min(message.len());
            while !message.is_char_boundary(limit) {
                limit -= 1;
            }
            let mut line: String = message[..limit]
                .chars()
                .map(|ch| if ch.is_control() { ' ' } else { ch })
                .collect();
            if limit < message.len() {
                line.push('…');
            }
            messages.0.push(format!("extension: {line}"));
        }
    }

    pub(crate) fn take(&self) -> Vec<String> {
        let (mut messages, suppressed) =
            std::mem::take(&mut *self.messages.lock().unwrap_or_else(|e| e.into_inner()));
        if suppressed != 0 {
            messages.push(format!(
                "extension: {suppressed} additional warnings suppressed"
            ));
        }
        messages
    }
}

impl PluginDiagnostics for PluginLoadDiagnostics {
    fn warn(&self, message: &str) {
        self.push(message);
    }

    fn unsupported(&self, message: &str) {
        self.push(message);
    }

    fn track_cleanup(&self, receipt: PluginCleanupReceipt) {
        self.cleanup.track_cleanup(receipt);
    }
}

const MAX_PENDING_RECEIPTS: usize = 1024;
#[derive(Default)]
struct State {
    receipts: Vec<PluginCleanupReceipt>,
    sealed: bool,
    unknown: bool,
}
#[derive(Default)]
pub(crate) struct PluginCleanupLedger {
    state: Mutex<State>,
}
impl PluginCleanupLedger {
    pub(crate) fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }
    // Staged resource owner will await this AFTER relinquishing every generation's
    // executable references. Call only under its admission/retirement barrier.
    #[allow(dead_code)]
    pub(super) async fn wait_plugins_released(
        &self,
    ) -> Result<(), super::in_process::InProcessError> {
        let receipts = {
            let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
            state.sealed = true;
            if state.unknown {
                return Err(super::in_process::InProcessError::Unsettled);
            }
            state.receipts.clone()
        };
        for receipt in receipts {
            if receipt.wait().await != PluginCleanupStatus::Released {
                return Err(super::in_process::InProcessError::Unsettled);
            }
        }
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        if state.unknown {
            return Err(super::in_process::InProcessError::Unsettled);
        }
        state.receipts.clear();
        Ok(())
    }
}
impl PluginDiagnostics for PluginCleanupLedger {
    // Preserve the CLI's existing NullDiagnostics rendering policy.
    fn warn(&self, _: &str) {}
    fn unsupported(&self, _: &str) {}
    fn track_cleanup(&self, receipt: PluginCleanupReceipt) {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        // Released observations may be compacted, never Pending/Retained ones.
        state
            .receipts
            .retain(|r| r.status() != PluginCleanupStatus::Released);
        if state.sealed || state.receipts.len() >= MAX_PENDING_RECEIPTS {
            // Never silently lose evidence or claim an already-sealed set covers
            // a late load. Unknown is sticky, including after cancelled waiters.
            state.unknown = true;
        }
        if state.receipts.len() < MAX_PENDING_RECEIPTS {
            state.receipts.push(receipt);
        }
    }
}

#[cfg(test)]
pub(super) mod tests;