Skip to main content

vtcode_core/subagents/matrix/
mod.rs

1//! Local matrix orchestration beside the subagent runtime. Canonical snapshots
2//! are acknowledged before launch and before exposing completion.
3mod fingerprint;
4mod projection;
5mod worker;
6
7use super::SubagentController;
8use crate::exec::events::matrix::*;
9use anyhow::{Context, Result, bail, ensure};
10use futures::future::BoxFuture;
11use parking_lot::RwLock;
12use serde_json::{Value, json};
13use std::collections::BTreeMap;
14use std::sync::{
15    Arc,
16    atomic::{AtomicBool, Ordering},
17};
18use tokio::sync::{Mutex, Notify};
19use tokio::task::JoinSet;
20use tokio_util::sync::CancellationToken;
21use vtcode_memory::matrix::MatrixState;
22use vtcode_utility_tool_specs::report_outcome;
23
24/// Access to the existing authoritative drain, not a second persisted store.
25#[derive(Clone)]
26pub struct MatrixPersistence {
27    pub persist: Arc<dyn Fn(MatrixSnapshot) -> BoxFuture<'static, Result<()>> + Send + Sync>,
28    pub load: Arc<dyn Fn() -> BoxFuture<'static, Result<Vec<MatrixSnapshot>>> + Send + Sync>,
29}
30
31#[derive(Default)]
32pub(super) struct MatrixRuntime {
33    #[cfg(test)]
34    executor_override: RwLock<Option<TestExecutor>>,
35    persistence: RwLock<Option<MatrixPersistence>>,
36    updated_at: RwLock<chrono::DateTime<chrono::Utc>>,
37    state: Mutex<Option<MatrixState>>,
38    driver_active: AtomicBool,
39    pub(super) executing: AtomicBool,
40    notify: Notify,
41    pub(super) cancellation: RwLock<CancellationToken>,
42    error: RwLock<Option<String>>,
43    completion: parking_lot::Mutex<Option<MatrixSnapshot>>,
44}
45
46#[cfg(test)]
47type TestExecutor = Arc<
48    dyn Fn(MatrixAssignment, MatrixTaskSpec, CancellationToken) -> BoxFuture<'static, worker::WorkerResult>
49        + Send
50        + Sync,
51>;
52
53/// Only the runtime can bind this capability to a worker registry.
54#[derive(Clone)]
55pub(crate) struct MatrixWorkerContext {
56    pub assignment: MatrixAssignment,
57    report: Arc<parking_lot::Mutex<Option<Value>>>,
58}
59impl MatrixWorkerContext {
60    fn new(assignment: MatrixAssignment) -> Self {
61        Self {
62            assignment,
63            report: Arc::new(parking_lot::Mutex::new(None)),
64        }
65    }
66    pub(crate) fn reported_outcome(&self) -> Option<MatrixOutcome> {
67        self.report
68            .lock()
69            .as_ref()
70            .and_then(|report| report.get("outcome").and_then(Value::as_str))
71            .and_then(|outcome| match outcome {
72                report_outcome::EXECUTED => Some(MatrixOutcome::Success),
73                report_outcome::FAILED => Some(MatrixOutcome::Failed),
74                report_outcome::PERMISSION_DENIED => Some(MatrixOutcome::PermissionDenied),
75                report_outcome::BUDGET_EXHAUSTED => Some(MatrixOutcome::BudgetExhausted),
76                report_outcome::INTERRUPTED => Some(MatrixOutcome::Interrupted),
77                report_outcome::TIMED_OUT => Some(MatrixOutcome::TimedOut),
78                _ => None,
79            })
80    }
81    pub(crate) fn report(&self, args: Value) -> Result<Value> {
82        ensure!(args.get("action").and_then(Value::as_str) == Some("report"), "matrix workers may only report");
83        ensure!(
84            args.get("matrix_id").is_none()
85                && args.get("task_id").is_none()
86                && args.get("attempt_id").is_none()
87                && args.get("worker_id").is_none(),
88            "worker report identity is runtime-owned"
89        );
90        let outcome = args
91            .get("outcome")
92            .and_then(Value::as_str)
93            .context("matrix report requires outcome")?;
94        ensure!(report_outcome::ALL.contains(&outcome), "invalid matrix report outcome");
95        let mut report = self.report.lock();
96        ensure!(report.is_none(), "duplicate matrix report");
97        *report = Some(args);
98        Ok(
99            json!({"accepted":true,"task_id":self.assignment.task_id,"attempt_id":self.assignment.attempt_id,"final_success":false}),
100        )
101    }
102}
103
104impl SubagentController {
105    /// Coalesced notification projection; lifecycle authority stays in events.
106    pub fn take_matrix_completion(&self) -> Option<MatrixSnapshot> {
107        self.matrix.completion.lock().take()
108    }
109    /// Idle wakeups inspect readiness without consuming the outer loop's result.
110    pub fn has_matrix_completion(&self) -> bool {
111        self.matrix.completion.lock().is_some()
112    }
113    pub async fn set_matrix_persistence(&self, persistence: MatrixPersistence) -> Result<()> {
114        let mut guard = self.matrix.state.lock().await;
115        *self.matrix.persistence.write() = Some(persistence.clone());
116        if guard.is_some() {
117            return Ok(());
118        }
119        // Admission stays closed until replay and its reconciliation checkpoint
120        // have been acknowledged. A failed load must never enable discovery.
121        self.matrix.executing.store(true, Ordering::Release);
122        let mut retained = (persistence.load)().await?.into_iter().filter(|snapshot| {
123            !matches!(snapshot.lifecycle, MatrixLifecycle::Cancelled | MatrixLifecycle::Succeeded)
124                || snapshot
125                    .tasks
126                    .iter()
127                    .flat_map(|task| &task.attempts)
128                    .any(|attempt| !attempt.cleanup_confirmed)
129        });
130        let snapshot = retained.next();
131        ensure!(retained.next().is_none(), "multiple unreconciled matrices in one local session");
132        if let Some(snapshot) = snapshot {
133            let mut restored = MatrixState::from_snapshot(snapshot)?;
134            self.matrix.recover(&mut restored).await?;
135            self.matrix.update_execution_admission(&restored);
136            *guard = Some(restored);
137        } else {
138            self.matrix.executing.store(false, Ordering::Release);
139        }
140        Ok(())
141    }
142    pub fn matrix_is_executing(&self) -> bool {
143        self.matrix.executing.load(Ordering::Acquire)
144    }
145    pub(super) fn ensure_ordinary_delegation_allowed(&self) -> Result<()> {
146        ensure!(!self.matrix_is_executing(), "active matrix execution must use scheduler-owned workers");
147        Ok(())
148    }
149    pub(crate) fn matrix_is_driving(&self) -> bool {
150        self.matrix.driver_active.load(Ordering::Acquire)
151    }
152    pub(crate) fn request_matrix_stop(&self) {
153        self.matrix.cancellation.read().cancel();
154        self.matrix.notify.notify_one();
155    }
156    pub(crate) async fn matrix_snapshot(&self) -> Option<MatrixSnapshot> {
157        self.matrix.state.lock().await.as_ref().map(|state| state.snapshot().clone())
158    }
159    /// Headless completion keeps the canonical sink alive until admitted work stops.
160    pub(crate) async fn wait_matrix_idle(&self) -> Option<MatrixSnapshot> {
161        loop {
162            let notified = self.background_completion_notify.notified();
163            if !self.matrix.driver_active.load(Ordering::Acquire) {
164                return self.matrix_snapshot().await;
165            }
166            tokio::select! {
167                () = notified => {}
168                () = tokio::time::sleep(std::time::Duration::from_millis(250)) => {}
169            }
170        }
171    }
172    pub async fn cancel_matrix(&self) -> Result<()> {
173        // Stopping owned work cannot depend on a functioning persistence sink.
174        self.request_matrix_stop();
175        let mut guard = self.matrix.state.lock().await;
176        if let Some(state) = guard.as_ref()
177            && !matches!(state.snapshot().lifecycle, MatrixLifecycle::Cancelled | MatrixLifecycle::Succeeded)
178        {
179            let mut next = state.clone();
180            next.cancel()?;
181            self.matrix.persist(&next).await?;
182            self.matrix.update_execution_admission(&next);
183            *guard = Some(next);
184        }
185        Ok(())
186    }
187    pub async fn matrix_control(&self, args: Value) -> Result<Value> {
188        let action = args.get("action").and_then(Value::as_str).context("matrix requires action")?;
189        ensure!(action != "report", "matrix report is worker-only");
190        if ["start", "resume", "retry"].contains(&action) {
191            ensure!(
192                self.config.depth == 0
193                    && self.config.vt_cfg.subagents.enabled
194                    && self.config.vt_cfg.subagents.max_concurrent > 0
195                    && self.config.vt_cfg.subagents.max_depth > 0,
196                "matrix requires root-session enabled subagents with positive capacity and depth"
197            );
198            ensure!(!self.matrix.cancellation.read().is_cancelled(), "user cancellation prevents matrix continuation");
199        }
200        let requested_id = args.get("matrix_id").and_then(Value::as_str);
201        let mut guard = self.matrix.state.lock().await;
202        if guard.is_none() && action != "create" {
203            let persistence = self
204                .matrix
205                .persistence
206                .read()
207                .clone()
208                .context("canonical matrix persistence unavailable")?;
209            let snapshots = (persistence.load)().await?;
210            let snapshot = snapshots
211                .into_iter()
212                .find(|snapshot| Some(snapshot.spec.id.as_str()) == requested_id)
213                .context("unknown matrix; provide matrix_id")?;
214            let mut restored = MatrixState::from_snapshot(snapshot)?;
215            self.matrix.update_execution_admission(&restored);
216            self.matrix.recover(&mut restored).await?;
217            *guard = Some(restored);
218        }
219        if action == "create" {
220            ensure!(!self.matrix.driver_active.load(Ordering::Acquire), "matrix driver is still cleaning up");
221            if let Some(state) = guard.as_ref() {
222                ensure!(
223                    matches!(state.snapshot().lifecycle, MatrixLifecycle::Cancelled | MatrixLifecycle::Succeeded)
224                        && state.active_assignments().is_empty(),
225                    "one local matrix may be active at a time"
226                );
227            }
228            let spec: MatrixSpec =
229                serde_json::from_value(args.get("spec").cloned().context("matrix create requires spec")?)?;
230            ensure!(requested_id.is_none_or(|id| id == spec.id), "matrix_id does not match specification");
231            let persistence = self
232                .matrix
233                .persistence
234                .read()
235                .clone()
236                .context("canonical matrix persistence unavailable")?;
237            let existing = (persistence.load)().await?;
238            ensure!(
239                existing.iter().all(|snapshot| matches!(
240                    snapshot.lifecycle,
241                    MatrixLifecycle::Cancelled | MatrixLifecycle::Succeeded
242                ) && snapshot
243                    .tasks
244                    .iter()
245                    .flat_map(|task| &task.attempts)
246                    .all(|attempt| attempt.cleanup_confirmed)),
247                "resume the existing matrix and reconcile owned cleanup before creating another"
248            );
249            ensure!(
250                !existing.iter().any(|snapshot| snapshot.spec.id == spec.id),
251                "matrix ID already exists; use a new ID"
252            );
253            let state = MatrixState::create(spec, &self.config.workspace_root)?;
254            self.matrix.persist(&state).await?;
255            self.matrix.update_execution_admission(&state);
256            *guard = Some(state);
257            *self.matrix.cancellation.write() = CancellationToken::new();
258            *self.matrix.error.write() = None;
259        } else if action != "status" {
260            let mut state = guard.as_ref().context("matrix is unavailable")?.clone();
261            ensure!(requested_id == Some(state.snapshot().spec.id.as_str()), "matrix_id does not match active matrix");
262            if ["start", "resume", "retry"].contains(&action) && !self.matrix_is_driving() {
263                self.matrix.recover(&mut state).await?;
264                self.matrix.update_execution_admission(&state);
265                *guard = Some(state.clone());
266            }
267            let mut next = state.clone();
268            match action {
269                "start" => {
270                    ensure!(
271                        self.config.vt_cfg.subagents.enabled && self.config.vt_cfg.subagents.max_concurrent > 0,
272                        "matrix requires enabled subagents with positive concurrency"
273                    );
274                    vtcode_memory::matrix::validate_workspace(&next.snapshot().spec, &self.config.workspace_root)?;
275                    fingerprint::fingerprint(&self.config.workspace_root, &next.snapshot().spec).await?;
276                    next.start()?;
277                }
278                "pause" => next.pause()?,
279                "resume" => {
280                    if next.snapshot().lifecycle == MatrixLifecycle::Paused {
281                        next.resume()?;
282                    } else {
283                        ensure!(
284                            matches!(next.snapshot().lifecycle, MatrixLifecycle::Running | MatrixLifecycle::Verifying),
285                            "matrix needs a coordinator retry or confirmed owned cleanup"
286                        );
287                    }
288                }
289                "retry" => {
290                    next.retry(args.get("task_id").and_then(Value::as_str).context("retry requires task_id")?)?
291                }
292                "cancel" => {
293                    self.matrix.cancellation.read().cancel();
294                    next.cancel()?;
295                }
296                _ => bail!("unknown matrix action {action}"),
297            }
298            if ["start", "resume", "retry"].contains(&action) && !self.matrix.driver_active.load(Ordering::Acquire) {
299                // Block new discovery before inspecting its reserved permits,
300                // including when restoring a matrix into a warm session.
301                self.matrix.executing.store(true, Ordering::Release);
302                if self.admission.available_permits()
303                    != self
304                        .config
305                        .vt_cfg
306                        .subagents
307                        .max_concurrent
308                        .min(vtcode_config::subagents::SUBAGENT_HARD_CONCURRENCY_LIMIT)
309                {
310                    self.matrix.update_execution_admission(&state);
311                    bail!("wait for discovery workers to stop before matrix dispatch");
312                }
313            }
314            if next.snapshot() != state.snapshot()
315                && let Err(error) = self.matrix.persist(&next).await
316            {
317                self.matrix.update_execution_admission(&state);
318                return Err(error);
319            }
320            self.matrix.update_execution_admission(&next);
321            *guard = Some(next);
322            if action == "cancel" {
323                self.matrix.cancellation.read().cancel();
324            }
325        }
326        let snapshot = guard.as_ref().context("matrix unavailable")?.snapshot().clone();
327        if let Some(id) = requested_id {
328            ensure!(id == snapshot.spec.id, "matrix_id does not match active matrix");
329        }
330        drop(guard);
331        self.matrix.notify.notify_one();
332        if ["start", "resume", "retry"].contains(&action) && !self.matrix.driver_active.swap(true, Ordering::AcqRel) {
333            self.matrix.executing.store(true, Ordering::Release);
334            *self.matrix.error.write() = None;
335            let driver_cancel = self.matrix.cancellation.read().child_token();
336            let controller = self.clone();
337            tokio::spawn(async move {
338                if let Err(error) = controller.matrix_drive(&driver_cancel).await {
339                    *controller.matrix.error.write() = Some(format!("{error:#}"));
340                    // Stop this driver's owned work without turning an internal
341                    // failure into the user's terminal cancellation decision.
342                    driver_cancel.cancel();
343                }
344                // Cleanup-uncertain state keeps the coordinator restricted.
345                let state = controller.matrix.state.lock().await;
346                if let Some(state) = state.as_ref()
347                    && matches!(state.snapshot().lifecycle, MatrixLifecycle::Succeeded | MatrixLifecycle::Blocked)
348                {
349                    *controller.matrix.completion.lock() = Some(state.snapshot().clone());
350                }
351                if let Some(state) = state.as_ref() {
352                    controller.matrix.update_execution_admission(state);
353                }
354                drop(state);
355                controller.matrix.driver_active.store(false, Ordering::Release);
356                controller.background_completion_notify.notify_one();
357            });
358        }
359        let mut result = projection::tracker_result(&snapshot);
360        result["matrix"] = json!(snapshot);
361        result["persistence_error"] = json!(self.matrix.error.read().clone());
362        Ok(result)
363    }
364
365    async fn matrix_drive(&self, driver_cancel: &CancellationToken) -> Result<()> {
366        let mut workers = JoinSet::new();
367        let mut pending = BTreeMap::<String, worker::WorkerResult>::new();
368        loop {
369            let mut guard = self.matrix.state.lock().await;
370            let state = guard.as_ref().context("matrix disappeared")?;
371            let mut next = state.clone();
372            if self.matrix.cancellation.read().is_cancelled()
373                && !matches!(next.snapshot().lifecycle, MatrixLifecycle::Cancelled | MatrixLifecycle::Succeeded)
374            {
375                next.cancel()?;
376            }
377            if workers.is_empty() && !pending.is_empty() {
378                for (_, result) in std::mem::take(&mut pending) {
379                    next.report(
380                        &result.assignment.attempt_id,
381                        &result.assignment.worker_id,
382                        result.outcome,
383                        result.evidence,
384                        result.cleanup_confirmed,
385                    )?;
386                }
387                // Preserve stopped-work results even if inputs became unavailable.
388                self.matrix.persist(&next).await?;
389                *guard = Some(next.clone());
390                if next.snapshot().lifecycle != MatrixLifecycle::Cancelled {
391                    let current = fingerprint::fingerprint(&self.config.workspace_root, &next.snapshot().spec).await?;
392                    let generation_changed = next
393                        .snapshot()
394                        .generation
395                        .as_deref()
396                        .is_some_and(|generation| generation != current);
397                    if generation_changed
398                        && next.active_assignments().is_empty()
399                        && matches!(next.snapshot().lifecycle, MatrixLifecycle::Verifying | MatrixLifecycle::Paused)
400                    {
401                        next.invalidate_verification(current)?;
402                    }
403                }
404            }
405            if workers.is_empty()
406                && next.snapshot().lifecycle == MatrixLifecycle::Running
407                && next
408                    .snapshot()
409                    .tasks
410                    .iter()
411                    .all(|task| task.status == MatrixTaskStatus::Executed)
412            {
413                let generation = fingerprint::fingerprint(&self.config.workspace_root, &next.snapshot().spec).await?;
414                next.begin_verification(generation)?;
415            }
416            if workers.is_empty()
417                && next.snapshot().lifecycle == MatrixLifecycle::Verifying
418                && next
419                    .snapshot()
420                    .tasks
421                    .iter()
422                    .all(|task| task.status == MatrixTaskStatus::Verified)
423            {
424                let generation = fingerprint::fingerprint(&self.config.workspace_root, &next.snapshot().spec).await?;
425                if next.snapshot().generation.as_deref() != Some(generation.as_str()) {
426                    next.invalidate_verification(generation)?;
427                } else {
428                    next.finalize_verification(&generation)?;
429                }
430            }
431            let available = self.admission.available_permits();
432            let active = next.active_assignments().len();
433            if matches!(next.snapshot().lifecycle, MatrixLifecycle::Running | MatrixLifecycle::Verifying) {
434                vtcode_memory::matrix::validate_workspace(&next.snapshot().spec, &self.config.workspace_root)?;
435            }
436            let assignments =
437                next.reserve_ready((active + available).min(self.config.vt_cfg.subagents.max_concurrent).min(5))?;
438            let mut launches = Vec::new();
439            for assignment in assignments {
440                match Arc::clone(&self.admission).try_acquire_owned() {
441                    Ok(permit) => {
442                        let task = next
443                            .snapshot()
444                            .spec
445                            .tasks
446                            .iter()
447                            .find(|task| task.id == assignment.task_id)
448                            .context("unknown assigned task")?
449                            .clone();
450                        launches.push((assignment, task, permit));
451                    }
452                    Err(_) => next.rollback_launch(&assignment.attempt_id)?,
453                }
454            }
455            if next.snapshot() != guard.as_ref().context("matrix unavailable")?.snapshot() {
456                self.matrix.persist(&next).await?;
457                *guard = Some(next);
458                self.background_completion_notify.notify_one();
459            }
460            if !launches.is_empty() {
461                let mut launching = guard.as_ref().context("matrix unavailable")?.clone();
462                for (assignment, _, _) in &launches {
463                    launching.mark_launch_requested(&assignment.attempt_id)?;
464                }
465                self.matrix.persist(&launching).await?;
466                *guard = Some(launching);
467            }
468            let lifecycle = guard.as_ref().context("matrix unavailable")?.snapshot().lifecycle;
469            drop(guard);
470            for (assignment, task, permit) in launches {
471                let controller = self.clone();
472                let cancel = driver_cancel.child_token();
473                #[cfg(test)]
474                let executor = self.matrix.executor_override.read().clone();
475                workers.spawn(async move {
476                    let _permit = permit;
477                    #[cfg(test)]
478                    if let Some(executor) = executor {
479                        return executor(assignment, task, cancel).await;
480                    }
481                    Box::pin(worker::execute(&controller, assignment, task, cancel)).await
482                });
483            }
484            if workers.is_empty() && !matches!(lifecycle, MatrixLifecycle::Running | MatrixLifecycle::Verifying) {
485                return Ok(());
486            }
487            if workers.is_empty() && lifecycle == MatrixLifecycle::Verifying {
488                continue;
489            }
490            tokio::select! {
491                result = workers.join_next(), if !workers.is_empty() => {
492                    let result = result.context("matrix worker missing")?.context("matrix worker panicked; cleanup ownership uncertain")?;
493                    if result.assignment.phase == MatrixPhase::Verify {
494                        pending.insert(result.assignment.attempt_id.clone(), result);
495                    } else {
496                        let mut guard = self.matrix.state.lock().await;
497                        let mut next = guard.as_ref().context("matrix unavailable")?.clone();
498                        next.report(&result.assignment.attempt_id, &result.assignment.worker_id, result.outcome, result.evidence, result.cleanup_confirmed)?;
499                        self.matrix.persist(&next).await?;
500                        *guard = Some(next);
501                        self.background_completion_notify.notify_one();
502                    }
503                }
504                () = self.matrix.notify.notified() => {}
505                () = tokio::time::sleep(std::time::Duration::from_millis(250)) => {}
506            }
507        }
508    }
509}
510impl MatrixRuntime {
511    async fn recover(&self, state: &mut MatrixState) -> Result<()> {
512        let previous = state.snapshot().clone();
513        state.recover()?;
514        if state.snapshot() != &previous {
515            self.persist(state).await?;
516        }
517        Ok(())
518    }
519
520    fn update_execution_admission(&self, state: &MatrixState) {
521        let held = !state.active_assignments().is_empty()
522            || !matches!(
523                state.snapshot().lifecycle,
524                MatrixLifecycle::Created | MatrixLifecycle::Succeeded | MatrixLifecycle::Cancelled
525            );
526        self.executing.store(held, Ordering::Release);
527    }
528
529    async fn persist(&self, state: &MatrixState) -> Result<()> {
530        let persistence = self
531            .persistence
532            .read()
533            .clone()
534            .context("canonical matrix persistence unavailable")?;
535        (persistence.persist)(state.snapshot().clone()).await?;
536        *self.updated_at.write() = chrono::Utc::now();
537        Ok(())
538    }
539}
540
541#[cfg(test)]
542mod tests;