mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
//! The analyze tool's cancel action: it stops one of the calling session's dispatched quick
//! analysis rounds, named by the job id its acknowledgement carried, and durably discards its
//! result. The cancel-signal registry lives in [`crate::round_cancel`].
//!
//! Ownership: a round is the caller's while its `jobs` row (or, before that row is written, its
//! in-process cancel-signal entry) does, or while its produced result waits in `pending_jobs`.
//! Anything else — a delivered, an already-cancelled and a never-dispatched id alike — is
//! answered as nothing of the caller's by that name.
//!
//! The stop is durable because the round's OWN rows are deleted, never merely signalled: a
//! surviving `kind='analyze'` row would be resumed at the next start and a surviving
//! `pending_jobs` row replayed by the boot replay. The dispatch's own row write is refused by a
//! gate inside its transaction ([`crate::jobs::spawn_job`]) once the cancellation fired, so a
//! failed deletion is the only way a row outlives the stop — and the caller is then told the
//! cancellation did not happen. An in-tx gate in
//! [`crate::jobs::complete_job_with_envelope`] rolls back a cancelled round's completion and
//! [`crate::tools::SyncDurableCore::stopped_by_cancel`] refuses the route, so a
//! produced-but-undelivered result is never handed over; a copy already on the caller's live
//! channel cannot be recalled — the one accepted race.
//!
//! Only this round's own id is deleted (never by target), its agents stop as a group via
//! [`ParentKey::AnalyzeRound`], and its sessions are left as a completed round's are. A `deep`
//! investigation, a worker round, another agent's round and an id that names nothing are refused
//! by the `kind = 'analyze'` filter and left alone. A repeat cancel of a still-unwinding round
//! answers as stopped again while its invocation is registered — except a round resumed at boot,
//! whose entry records no dispatching session.

use crate::agent::message_router::MessageKind;
use crate::agent::registry::ParentKey;
use crate::db::Connection;

#[derive(Debug)]
pub(crate) enum Cancelled {
    /// The round was live and has been stopped.
    Stopped,
    /// The round had already produced its result: it was discarded and the round is gone.
    Discarded,
    /// Nothing of the caller's by that name — the id is not one of its live rounds.
    NotMine,
}

/// Stop `caller`'s round `job_id` and durably discard its result. Ownership, durability and the
/// accepted race are the module doc's.
pub(crate) async fn cancel_round(job_id: &str, caller: &str) -> anyhow::Result<Cancelled> {
    let conn = &crate::session::store().conn;
    let Some((outcome, place)) = locate(conn, job_id, caller)
        .await
        .map_err(|e| e.context(not_located(job_id)))?
    else {
        return Ok(Cancelled::NotMine);
    };
    // The signal is fired BEFORE any row is deleted: a completion, a delivery or a spawn racing
    // this cancel then sees the signal and refuses.
    crate::round_cancel::cancel(job_id);
    // The round's agents stop as a group, and its consolidation call is cancelled with them.
    crate::agent::registry::AGENT_REGISTRY
        .cancel_by_parent_key(&ParentKey::AnalyzeRound(job_id.to_string()));
    crate::agent::registry::NON_AGENT_CALLS
        .remove_by_parent_key(&ParentKey::AnalyzeRound(job_id.to_string()));
    // The row removal is what makes the stop durable, so a failure here means the cancellation
    // did not happen.
    crate::jobs::delete_round_rows(conn, job_id)
        .await
        .map_err(|e| e.context(not_discarded(job_id)))?;
    // A cancelled round never resumes, so its placed engine goes now — by path, since the rows
    // naming it are gone.
    if let Some(dir) = place {
        crate::tools::delegation::release_placed_engine(&dir);
    }
    tracing::info!(job = %job_id, ?outcome, "Analyze round cancelled");
    Ok(outcome)
}

/// The refusal for a cancel whose round could not be looked up: nothing was changed.
fn not_located(job_id: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "the cancellation of analysis job {job_id} could not be put in place — \
         the round was not touched and carries on"
    )
}

/// The refusal for a cancel whose durable discard could not be committed: the caller is told the
/// cancellation did not happen.
fn not_discarded(job_id: &str) -> anyhow::Error {
    anyhow::anyhow!(
        "the cancellation of analysis job {job_id} could not be put in place — its rows could \
         not be removed, so this round's live run delivers nothing but a later start of the \
         product may still deliver its result"
    )
}

/// Find the caller's round in the durable state, in the order that state decides: the live `jobs`
/// row, then a queued result, then the in-process entry.
async fn locate(
    conn: &Connection,
    job_id: &str,
    caller: &str,
) -> anyhow::Result<Option<(Cancelled, Option<String>)>> {
    // The live round: the row's own delivery address is the ownership proof.
    if let Some(round) = crate::jobs::analyze_round_owned_by(conn, job_id, caller).await? {
        return Ok(Some((Cancelled::Stopped, round.exec_dir)));
    }
    if let Some(envelope) = crate::jobs::pending_envelope(conn, job_id).await? {
        // A queued analyze result addressed to the caller: its round is over and the result was
        // never delivered.
        if envelope.kind == MessageKind::AnalyzeToolResult
            && crate::jobs::envelope_target(&envelope) == caller
        {
            return Ok(Some((Cancelled::Discarded, None)));
        }
    }
    // A round whose row is not written yet, or whose row this very cancel just removed.
    Ok(
        (crate::round_cancel::registered_caller(job_id).as_deref() == Some(caller))
            .then_some((Cancelled::Stopped, None)),
    )
}

/// The cancel action's answer to its caller — one plain line per outcome.
#[must_use]
pub(crate) fn answer(outcome: &Cancelled, job_id: &str) -> String {
    match outcome {
        Cancelled::Stopped => format!(
            "Cancelled the analysis round (job {job_id}): its analysts stop and its result will \
             not be delivered to this session."
        ),
        Cancelled::Discarded => format!(
            "Analysis round (job {job_id}) had already produced its result — the result was \
             discarded and will not be delivered to this session."
        ),
        Cancelled::NotMine => format!(
            "No analysis round of this session to cancel for job {job_id}: this action stops \
             only the quick analysis rounds this session dispatched, and nothing was changed."
        ),
    }
}