Skip to main content

perspt_agent/toolloop/
mod.rs

1//! The SRBN tool loop (PSP-9 system 6) — Paper II Appendix A Algorithm 1
2//! with tool calls substituted for bundle generation.
3//!
4//! Every model-issued tool call becomes a Paper III proposal; the
5//! deterministic admissibility kernel decides whether it may affect the
6//! candidate; the gate is evaluated on the re-measured candidate, never on
7//! the model's account of it (Paper I Definition 12.2); and every descent
8//! and rejection consumes the stated budget (Paper II Lemma 1).
9//!
10//! The loop is written against `dyn ModelTransport` and cannot name a vendor
11//! type or credential — that is Gate S. Executor and measurer are ports too,
12//! so the whole loop runs in tests against scripted fixtures without a
13//! network.
14
15use anyhow::{Context, Result};
16use perspt_sdk::{
17    AcceptedTrajectory, BarrierEvaluator, CandidateStateWitness, CandidateTransition, Capability,
18    ContextCheckpoint, ContractEvaluator, ControlFrame, Conversation, CorrectionDirection,
19    EffectProposal, FailureKind, FullAdmissibilityWitness, GateDecision, KernelState, ModelId,
20    ModelTransport, NodeTerminalOutcome, ProviderToolCall, RecoveryCascade, ResidualEvent,
21    StaticCatalog, ToolCatalog, ToolChoicePolicy, ToolEntry, TurnOutput, VerificationCadence,
22    check_full_admissibility, classify_failure,
23};
24use serde::{Deserialize, Serialize};
25use std::collections::BTreeSet;
26
27use crate::realize::ProjectionMismatch;
28
29mod artifact;
30mod batch;
31mod binding;
32mod context;
33mod contract;
34mod effects;
35pub mod envelope;
36mod proposal;
37mod resident;
38use binding::PromptBinding;
39pub use contract::*;
40pub use envelope::{DecodedLoopEvent, decode_tool_loop};
41pub use proposal::candidate_mutating_effect;
42pub use resident::ResidentReserves;
43
44use context::LoopContext;
45pub(crate) use context::refold_session_context;
46use proposal::{promote_matching_capability, proposal_from, proposal_scope, uncertified_reason};
47
48/// The loop's finite budgets (PSP-9 system 6).
49#[derive(Debug, Clone)]
50pub struct LoopBudgets {
51    /// `N`: maximum model turns.
52    pub max_turns: u32,
53    /// `M`: maximum tool calls honored in one turn.
54    pub max_calls_per_turn: u32,
55    /// `B`: Paper II's rejection budget (descents do not consume it).
56    pub rejection_budget: u32,
57    /// `ρ_gate`: the measured descent tolerance.
58    pub rho_gate: f64,
59    /// The domain's declared energy floor, if any.
60    pub declared_energy_floor: Option<f64>,
61    /// Provider-neutral context projection threshold. The live route's
62    /// declared context size may lower this bound.
63    pub context_soft_limit_chars: usize,
64    /// Paper III's one non-replenishing recovery pool for this node.
65    pub recovery_budget: u32,
66    /// Per-model-call wall-clock deadline in seconds; a finite turn count
67    /// alone never bounds wall time.
68    pub turn_deadline_secs: u64,
69    /// Definition 6 reserves and working-set bounds (`[context]`).
70    pub resident: resident::ResidentReserves,
71}
72
73impl LoopBudgets {
74    /// A configuration permitting an unbounded unchecked interval is
75    /// rejected at startup (Paper II Theorem 3).
76    pub fn validate(&self, cadence: &VerificationCadence) -> Result<()> {
77        anyhow::ensure!(self.max_turns > 0, "turn budget N must be at least 1");
78        anyhow::ensure!(
79            self.max_calls_per_turn > 0,
80            "per-turn call budget M must be at least 1"
81        );
82        anyhow::ensure!(
83            self.rho_gate.is_finite() && self.rho_gate > 0.0,
84            "descent tolerance rho_gate must be positive and finite"
85        );
86        anyhow::ensure!(
87            self.context_soft_limit_chars > 0,
88            "context soft limit must be finite and nonzero"
89        );
90        cadence.validate().map_err(|e| anyhow::anyhow!("{e}"))?;
91        Ok(())
92    }
93}
94
95/// The assembled tool loop for one node generation.
96pub struct ToolLoop<'a> {
97    pub transport: &'a dyn ModelTransport,
98    pub model: ModelId,
99    /// Sticky failover chain. A route is consumed only after an observed
100    /// transport failure and never selected per turn.
101    pub fallback_models: Vec<ModelId>,
102    pub catalog: &'a StaticCatalog,
103    pub capabilities: Vec<Capability>,
104    pub contract: Option<&'a dyn ContractEvaluator>,
105    pub barrier: Option<&'a dyn BarrierEvaluator>,
106    /// The capability contract's ceiling on one certified increment.
107    pub c_c_max: f64,
108    pub executor: &'a dyn EffectExecutor,
109    pub measurer: &'a dyn CandidateMeasurer,
110    pub budgets: LoopBudgets,
111    pub cadence: VerificationCadence,
112    pub kernel_state: KernelState,
113    pub node_id: String,
114    pub generation: u32,
115    /// The composed platform envelope for this actor (PSP-10 Phase 5). The
116    /// runtime composes it from the section library and records its
117    /// provenance; the loop seeds the text and stamps the digests into
118    /// every control frame.
119    pub system_prompt: PromptEnvelope,
120    pub recorder: Option<&'a dyn LoopRecorder>,
121    /// The partial-checkpoint root this loop was seeded from (a branch
122    /// continuing a partial); enters the resident dependency environment.
123    pub partial_seed_root: Option<String>,
124    /// Birth dependencies restored from a durable checkpoint, parallel to
125    /// the resumed conversation (Gate AF): pages keep their birth roots.
126    pub resumed_birth_deps: Vec<perspt_sdk::prompt::StateDependency>,
127    /// The forest's shared budget when this loop is a search branch: every
128    /// model turn and verifier run reserves first (Gate AC); `None` outside.
129    pub search_budget: Option<perspt_sdk::search::SharedSearchBudget>,
130}
131
132/// Where the last context checkpoint left off, so each new checkpoint covers
133/// exactly the log since the previous one instead of claiming the whole
134/// history from zero.
135#[derive(Debug, Default)]
136struct CompactionCursor {
137    parent: Option<String>,
138    next_from: u64,
139}
140
141fn finish(
142    outcome: NodeTerminalOutcome,
143    trajectory: AcceptedTrajectory,
144    log: EventLog,
145    projection: ProjectionMismatch,
146    turns_used: u32,
147    recovery_spent: u32,
148) -> LoopOutcome {
149    LoopOutcome {
150        outcome,
151        trajectory,
152        events: log.into_events(),
153        projection,
154        turns_used,
155        recovery_spent,
156        contained_by_transport: false,
157    }
158}
159
160/// Loop-lifetime mutable state threaded through every turn.
161struct TurnState {
162    log: EventLog,
163    projection: ProjectionMismatch,
164    recovery: RecoveryCascade,
165    cursor: CompactionCursor,
166    accepted_checkpoint: CandidateCheckpoint,
167    trajectory: AcceptedTrajectory,
168    /// `N_gate` computed at node entry; the loop refuses the
169    /// `(N_gate + 1)`-th gate submission (Gate X).
170    decision_bound: u64,
171    /// Monotone per-(node, generation) candidate counter (PSP-10 Phase 2).
172    candidate_seq: u64,
173    /// The candidate identity shared by the current measurement, gate
174    /// decision, and durable checkpoint (Proposition 2 keys by it).
175    current_candidate: String,
176    turns_used: u32,
177    /// The prompt binding of the most recent compile (PSP-10 Gate Z): the
178    /// tool-surface hash and route it was compiled for, plus its digests.
179    prompt: PromptBinding,
180}
181
182impl TurnState {
183    fn finish(self, outcome: NodeTerminalOutcome) -> LoopOutcome {
184        finish(
185            outcome,
186            self.trajectory,
187            self.log,
188            self.projection,
189            self.turns_used,
190            self.recovery.spent,
191        )
192    }
193
194    /// Mint the next candidate identity `"{node}/{gen}/c{seq}"`. Held for
195    /// the measurement → gate → durable-checkpoint triple.
196    fn next_candidate(&mut self, node_id: &str, generation: u32) -> String {
197        let id = format!("{node_id}/{generation}/c{}", self.candidate_seq);
198        self.candidate_seq += 1;
199        self.current_candidate = id.clone();
200        id
201    }
202}
203
204/// Turn-scoped accounting shared by top-level and nested calls.
205struct TurnBudget {
206    calls_seen: u32,
207    mutations: u32,
208    immediate_boundary: bool,
209    max_mutations: u32,
210}
211
212impl TurnBudget {
213    fn new(max_mutations: u32) -> Self {
214        Self {
215            calls_seen: 0,
216            mutations: 0,
217            immediate_boundary: false,
218            max_mutations,
219        }
220    }
221}
222
223/// Marker error: the transport recovery chain is exhausted (no retry or
224/// eligible fallback absorbed a provider failure). Containment caused by
225/// this error is an infrastructure outcome, not a governance anomaly, and
226/// preserves the session's authority so `perspt resume` stays viable.
227#[derive(Debug)]
228pub(crate) struct TransportExhausted {
229    detail: String,
230}
231
232impl std::fmt::Display for TransportExhausted {
233    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        formatter.write_str(&self.detail)
235    }
236}
237
238impl std::error::Error for TransportExhausted {}
239
240/// Whether an error chain bottoms out in exhausted transport recovery.
241pub(crate) fn is_transport_exhaustion(error: &anyhow::Error) -> bool {
242    error
243        .chain()
244        .any(|cause| cause.downcast_ref::<TransportExhausted>().is_some())
245}
246
247/// One loop iteration's verdict after a gate boundary.
248enum BoundaryStep {
249    Terminal(NodeTerminalOutcome),
250    Continue,
251    Exhausted,
252}
253
254impl ToolLoop<'_> {
255    /// Run the loop to a classified terminal state (Paper II Lemma 1).
256    pub async fn run(self, goal: &str) -> Result<LoopOutcome> {
257        self.run_inner(goal, None, Vec::new(), false).await
258    }
259
260    /// Run at least one model turn before allowing `baseline_terminal`
261    /// short-circuit (used after human `RequestCorrection` feedback).
262    pub async fn run_requiring_turn(self, goal: &str) -> Result<LoopOutcome> {
263        self.run_inner(goal, None, Vec::new(), true).await
264    }
265
266    /// Re-enter from a durable provider-neutral conversation projection. The
267    /// runtime restores candidate state and budgets; this method restores only
268    /// model context and deferred tool activation.
269    pub async fn run_with_conversation(
270        self,
271        goal: &str,
272        resumed: Option<Conversation>,
273        restored_activated_tools: Vec<String>,
274    ) -> Result<LoopOutcome> {
275        self.run_inner(goal, resumed, restored_activated_tools, false)
276            .await
277    }
278
279    async fn run_inner(
280        mut self,
281        goal: &str,
282        resumed: Option<Conversation>,
283        restored_activated_tools: Vec<String>,
284        require_turn: bool,
285    ) -> Result<LoopOutcome> {
286        self.budgets.validate(&self.cadence)?;
287        let (baseline, mut state) = self.open_turn_state().await?;
288        if !require_turn && let Some(outcome) = self.baseline_terminal(&baseline) {
289            return Ok(state.finish(outcome));
290        }
291        // The first call carries the measured baseline diagnostics: the
292        // model starts from evidence, not from a blind read of the tree.
293        let seeded_goal = goal_with_baseline(goal, &baseline);
294        let was_resumed = resumed.is_some();
295        let mut context =
296            self.open_context(&seeded_goal, resumed, restored_activated_tools, &mut state)?;
297        context.stamp_after_open(
298            was_resumed,
299            self.partial_seed_root.as_deref(),
300            &state.accepted_checkpoint.witness.state_root,
301            &self.resumed_birth_deps,
302        );
303
304        let mut mutations_since_boundary = 0u32;
305        for turn in 1..=self.budgets.max_turns {
306            state.turns_used = turn;
307            let turn_result = self
308                .model_turn(turn, mutations_since_boundary, &mut context, &mut state)
309                .await;
310            let (output, mutations, immediate_boundary) = match turn_result {
311                Ok(result) => result,
312                Err(error) => {
313                    let transport = is_transport_exhaustion(&error);
314                    let outcome = self
315                        .contain(&error, &state.accepted_checkpoint, &mut state.log)
316                        .await?;
317                    let mut contained = state.finish(outcome);
318                    contained.contained_by_transport = transport;
319                    return Ok(contained);
320                }
321            };
322            mutations_since_boundary = mutations_since_boundary.saturating_add(mutations);
323            if !self.boundary_due(&output, immediate_boundary, mutations_since_boundary, turn) {
324                continue;
325            }
326            mutations_since_boundary = 0;
327
328            match self
329                .boundary_step(goal, turn, &mut state, &mut context)
330                .await?
331            {
332                BoundaryStep::Terminal(outcome) => return Ok(state.finish(outcome)),
333                BoundaryStep::Exhausted => break,
334                BoundaryStep::Continue => {}
335            }
336        }
337
338        let outcome = NodeTerminalOutcome::Escalated {
339            certificate_id: uuid::Uuid::new_v4().to_string(),
340        };
341        Ok(state.finish(outcome))
342    }
343
344    /// Measure the baseline and open the loop's turn state around its real
345    /// restore point.
346    async fn open_turn_state(&mut self) -> Result<(Measured, TurnState)> {
347        let mut log = EventLog::new(self.recorder.is_none());
348        let accepted_checkpoint = self.executor.checkpoint(&[]).await?;
349        let (baseline, trajectory) = self.measured_baseline(&mut log).await?;
350        let decision_bound = loop_decision_bound(baseline.energy, &self.budgets)?;
351        let state = TurnState {
352            log,
353            projection: ProjectionMismatch::default(),
354            recovery: RecoveryCascade::new(self.budgets.recovery_budget),
355            cursor: CompactionCursor::default(),
356            accepted_checkpoint,
357            trajectory,
358            decision_bound,
359            candidate_seq: 1,
360            current_candidate: format!("{}/{}/c0", self.node_id, self.generation),
361            turns_used: 0,
362            prompt: PromptBinding::seed(&self.system_prompt, &self.model),
363        };
364        Ok((baseline, state))
365    }
366
367    /// Seed a fresh model context or re-enter a resumed one.
368    fn open_context(
369        &self,
370        goal: &str,
371        resumed: Option<Conversation>,
372        restored_activated_tools: Vec<String>,
373        state: &mut TurnState,
374    ) -> Result<LoopContext> {
375        let mut restored_tools = restored_activated_tools;
376        if let Some(conversation) = resumed.as_ref() {
377            restored_tools.extend(activated_tools_from_conversation(conversation));
378        }
379        match resumed {
380            Some(conversation) => {
381                LoopContext::resume(conversation, restored_tools, self.recorder, &mut state.log)
382            }
383            None => LoopContext::seed(
384                &self.system_prompt.text,
385                goal,
386                self.recorder,
387                &mut state.log,
388            ),
389        }
390    }
391
392    /// Unconditional containment: restore the last accepted state and
393    /// escalate (Theorem 6's terminal class for an unrecoverable turn).
394    async fn contain(
395        &self,
396        error: &anyhow::Error,
397        accepted_checkpoint: &CandidateCheckpoint,
398        log: &mut EventLog,
399    ) -> Result<NodeTerminalOutcome> {
400        self.executor.restore(accepted_checkpoint).await?;
401        emit(
402            self.recorder,
403            log,
404            LoopEvent::RecoveryContained {
405                reason: error.to_string(),
406                restored_checkpoint_id: accepted_checkpoint.id.clone(),
407            },
408        )?;
409        Ok(NodeTerminalOutcome::Escalated {
410            certificate_id: uuid::Uuid::new_v4().to_string(),
411        })
412    }
413
414    /// Measure the baseline candidate and open the accepted trajectory.
415    async fn measured_baseline(
416        &mut self,
417        log: &mut EventLog,
418    ) -> Result<(Measured, AcceptedTrajectory)> {
419        self.reserve_verifier_action(log)?;
420        let baseline = self.measurer.measure().await?;
421        emit(
422            self.recorder,
423            log,
424            LoopEvent::CandidateMeasured {
425                node_id: self.node_id.clone(),
426                generation: self.generation,
427                candidate_id: format!("{}/{}/c0", self.node_id, self.generation),
428                energy: baseline.energy,
429                hard_pass: baseline.hard_pass,
430                residuals: baseline.residuals.clone(),
431            },
432        )?;
433        let trajectory = AcceptedTrajectory::new(
434            self.node_id.clone(),
435            self.generation,
436            baseline.energy,
437            self.budgets.rho_gate,
438            self.budgets.rejection_budget,
439        )?;
440        Ok((baseline, trajectory))
441    }
442
443    /// Gate the measured candidate: accept (new checkpoint), restore on
444    /// rejection, classify terminals, and otherwise steer the next turn with
445    /// a directed correction (Lemma 1: descent and rejection are
446    /// non-terminal).
447    async fn boundary_step(
448        &mut self,
449        goal: &str,
450        turn: u32,
451        state: &mut TurnState,
452        context: &mut LoopContext,
453    ) -> Result<BoundaryStep> {
454        if self.refuse_past_bound(state)? {
455            return Ok(BoundaryStep::Exhausted);
456        }
457        let candidate_id = state.next_candidate(&self.node_id, self.generation);
458        let (measured, decision) = self
459            .measure_and_gate(&candidate_id, &mut state.trajectory, &mut state.log)
460            .await?;
461
462        let accepted = decision.is_accepted();
463        if accepted {
464            state.accepted_checkpoint = self.executor.checkpoint(&[]).await?;
465            // New pages depend on the new root; older root-dependent pages
466            // are now stale as optionals (still pinned/recallable).
467            context.set_state_dependency(perspt_sdk::prompt::StateDependency::AcceptedRoot(
468                state.accepted_checkpoint.witness.state_root.clone(),
469            ));
470        } else if !matches!(decision, GateDecision::StoppedAtDeclaredFloor) {
471            self.executor.restore(&state.accepted_checkpoint).await?;
472            emit(
473                self.recorder,
474                &mut state.log,
475                LoopEvent::CandidateRestored {
476                    checkpoint_id: state.accepted_checkpoint.id.clone(),
477                },
478            )?;
479        }
480
481        if let Some(outcome) = self.classify_decision(&decision, &measured) {
482            if accepted {
483                self.durable_checkpoint(goal, turn, &measured, state, context)
484                    .await?;
485            }
486            return Ok(BoundaryStep::Terminal(outcome));
487        }
488        push_correction(context, &measured, accepted, self.recorder, &mut state.log)?;
489        self.maybe_compact(goal, turn, &measured, state, context)?;
490        if accepted {
491            self.durable_checkpoint(goal, turn, &measured, state, context)
492                .await?;
493        } else {
494            if state.trajectory.budget_exhausted() {
495                return Ok(BoundaryStep::Exhausted);
496            }
497            let granted = state
498                .recovery
499                .grant(classify_failure(FailureKind::GateRejection));
500            emit(
501                self.recorder,
502                &mut state.log,
503                LoopEvent::RecoveryControlGranted {
504                    failure: FailureKind::GateRejection,
505                    level: granted.level,
506                    forced_escalation: granted.forced_escalation,
507                    model: self.model.clone(),
508                },
509            )?;
510            if granted.level > perspt_sdk::CascadeLevel::Retry {
511                return Ok(BoundaryStep::Exhausted);
512            }
513        }
514        Ok(BoundaryStep::Continue)
515    }
516
517    /// Gate X: the finite-decision bound is enforced, not advisory. Once the
518    /// bound is reached the loop refuses to submit — the refusal appends no
519    /// gate decision and routes through the ordinary exhaustion terminal.
520    fn refuse_past_bound(&self, state: &mut TurnState) -> Result<bool> {
521        let decisions_used = state.trajectory.gate_decisions.len() as u64;
522        if decisions_used < state.decision_bound {
523            return Ok(false);
524        }
525        emit(
526            self.recorder,
527            &mut state.log,
528            LoopEvent::DecisionBoundRefused {
529                node_id: self.node_id.clone(),
530                generation: self.generation,
531                bound: state.decision_bound,
532                decisions_used,
533            },
534        )?;
535        Ok(true)
536    }
537
538    /// Send the conversation, consuming the sticky failover chain on observed
539    /// transport failures (a route is never selected per turn).
540    async fn chat_with_failover(
541        &mut self,
542        conversation: &Conversation,
543        specs: &[perspt_sdk::ToolSpec],
544        recovery: &mut RecoveryCascade,
545        log: &mut EventLog,
546    ) -> Result<TurnOutput> {
547        loop {
548            match crate::turn::chat_turn_with_deadline(
549                self.transport,
550                &self.model,
551                conversation,
552                specs,
553                ToolChoicePolicy::Auto,
554                self.budgets.turn_deadline_secs,
555            )
556            .await
557            {
558                Ok(output) => return Ok(output),
559                Err(error) => {
560                    let cause = error.to_string();
561                    // One shared failure taxonomy for every actor (PSP-10
562                    // system 27).
563                    let failure = crate::turn::transport_failure_kind(&cause);
564                    let granted = recovery.grant(classify_failure(failure));
565                    emit(
566                        self.recorder,
567                        log,
568                        LoopEvent::RecoveryControlGranted {
569                            failure,
570                            level: granted.level,
571                            forced_escalation: granted.forced_escalation,
572                            model: self.model.clone(),
573                        },
574                    )?;
575                    if granted.level != perspt_sdk::CascadeLevel::Fallback || granted.terminal {
576                        return Err(anyhow::Error::new(TransportExhausted {
577                            detail: format!(
578                                "transport recovery reached {:?}: {cause}",
579                                granted.level
580                            ),
581                        }));
582                    }
583                    let Some(next) = self.fallback_models.first().cloned() else {
584                        return Err(anyhow::Error::new(TransportExhausted {
585                            detail: format!("transport recovery has no eligible fallback: {cause}"),
586                        }));
587                    };
588                    self.fallback_models.remove(0);
589                    let previous = std::mem::replace(&mut self.model, next.clone());
590                    emit(
591                        self.recorder,
592                        log,
593                        LoopEvent::RouteFailover {
594                            from_model: previous,
595                            to_model: next,
596                            cause,
597                        },
598                    )?;
599                }
600            }
601        }
602    }
603
604    /// Measure boundary: text turn, cadence bound `H`, or turn budget.
605    fn boundary_due(
606        &self,
607        output: &TurnOutput,
608        immediate_boundary: bool,
609        mutations_since_boundary: u32,
610        turn: u32,
611    ) -> bool {
612        matches!(output, TurnOutput::Text(_))
613            || immediate_boundary
614            || mutations_since_boundary >= self.cadence.max_mutations_between_checks
615            || turn == self.budgets.max_turns
616    }
617
618    /// One model turn: send the conversation, record the observation, and
619    /// route every returned call through the kernel. `mutations_so_far` is
620    /// the count since the last boundary; the cadence bound `H` caps what
621    /// this turn may add.
622    async fn model_turn(
623        &mut self,
624        turn: u32,
625        mutations_so_far: u32,
626        context: &mut LoopContext,
627        state: &mut TurnState,
628    ) -> Result<(TurnOutput, u32, bool)> {
629        let specs =
630            self.catalog
631                .deferred_specs_for(&self.capabilities, context.activated_tools(), false);
632        // Definition 6, transport half: the model sees the resident view
633        // (evictions tombstoned, recallable) and the composed request is
634        // verified against the allowance and dialect byte limit before any
635        // transport call; the whole projection stays the backing store.
636        let assembled = self.assemble_resident_context(turn, &specs, context, state)?;
637        let conversation = self.fit_composed_request(turn, &specs, context, assembled, state)?;
638        self.bind_prompt_program(turn, &specs, state)?;
639        // Gate AC: reserve the worst case before transport, settle actuals
640        // after; both sides snapshot so a crash never refills the turn.
641        let turn_reservation = self.reserve_model_turn(&conversation)?;
642        self.snapshot_search_usage(&mut state.log)?;
643        let output = self
644            .chat_with_failover(&conversation, &specs, &mut state.recovery, &mut state.log)
645            .await?;
646        // R2: record the observation before inspecting it.
647        emit(
648            self.recorder,
649            &mut state.log,
650            LoopEvent::TurnObserved {
651                turn,
652                actor: "worker".into(),
653                output: output.clone(),
654            },
655        )?;
656        let max_mutations = self
657            .cadence
658            .max_mutations_between_checks
659            .saturating_sub(mutations_so_far)
660            .max(1);
661        let (mutations, immediate_boundary) = self
662            .execute_turn(
663                &output,
664                turn,
665                max_mutations,
666                context,
667                &mut state.log,
668                &mut state.projection,
669            )
670            .await?;
671        self.settle_model_turn(turn_reservation, &output, mutations)?;
672        self.snapshot_search_usage(&mut state.log)?;
673        Ok((output, mutations, immediate_boundary))
674    }
675
676    /// Make a gate acceptance durably resumable (PSP-9 phase 6): export the
677    /// accepted candidate's mutated contents as content-addressed artifacts
678    /// and ledger them with the exact control frame, so a crashed loop can be
679    /// continued from this acceptance instead of restarted.
680    async fn durable_checkpoint(
681        &self,
682        goal: &str,
683        turn: u32,
684        measured: &Measured,
685        state: &mut TurnState,
686        context: &LoopContext,
687    ) -> Result<()> {
688        let Some(recorder) = self.recorder else {
689            return Ok(());
690        };
691        let authority_epoch = self
692            .kernel_state
693            .witnesses
694            .get("__authority_epoch")
695            .map(String::as_str)
696            .and_then(|value| value.parse().ok())
697            .unwrap_or(0);
698        let control = self.control_frame(goal, turn, measured, state, context, authority_epoch);
699        let exported = self.executor.export_accepted().await?;
700        let mut files = Vec::new();
701        for seed in exported {
702            let content_artifact = seed
703                .content
704                .as_deref()
705                .map(|bytes| recorder.record_artifact(bytes, "application/octet-stream"))
706                .transpose()?;
707            let source_preimage_artifact = seed
708                .source_preimage
709                .as_deref()
710                .map(|bytes| recorder.record_artifact(bytes, "application/octet-stream"))
711                .transpose()?;
712            files.push(DurableSeedFile {
713                path: seed.path,
714                content_artifact,
715                source_preimage_artifact,
716            });
717        }
718        emit(
719            self.recorder,
720            &mut state.log,
721            LoopEvent::DurableCandidateCheckpoint {
722                candidate_id: state.current_candidate.clone(),
723                state_root: state.accepted_checkpoint.witness.state_root.clone(),
724                control,
725                conversation: context.conversation().clone(),
726                birth_deps: context.birth_deps().to_vec(),
727                canonical_scope: state.accepted_checkpoint.witness.canonical_scope.clone(),
728                files,
729            },
730        )
731    }
732
733    /// The verbatim control frame a compaction must preserve (resolved
734    /// design decision 3): goal, accepted state binding, live authority, and
735    /// exact remaining budgets.
736    fn control_frame(
737        &self,
738        goal: &str,
739        turn: u32,
740        measured: &Measured,
741        state: &TurnState,
742        context: &LoopContext,
743        authority_epoch: u64,
744    ) -> ControlFrame {
745        ControlFrame {
746            projection_digest: context.digest().to_string(),
747            event_schema_version: perspt_sdk::CONVERSATION_EVENT_SCHEMA_VERSION,
748            prompt_invocation_digest: if state.prompt.invocation_digest.is_empty() {
749                self.system_prompt.invocation_digest.clone()
750            } else {
751                state.prompt.invocation_digest.clone()
752            },
753            prompt_manifest_digest: self.system_prompt.manifest_digest.clone(),
754            resident_context_digest: state.prompt.resident_digest.clone(),
755            node_id: self.node_id.clone(),
756            goal: goal.to_string(),
757            node_generation: self.generation,
758            accepted_state_root: state.accepted_checkpoint.witness.state_root.clone(),
759            graph_revision: state.accepted_checkpoint.witness.graph_revision.clone(),
760            capability_ids: self
761                .capabilities
762                .iter()
763                .map(|capability| capability.capability_id.clone())
764                .collect(),
765            authority_epoch,
766            remaining_rejection_budget: state
767                .trajectory
768                .rejection_budget
769                .saturating_sub(state.trajectory.rejections_used.max(state.recovery.spent)),
770            remaining_turns: self.budgets.max_turns.saturating_sub(turn),
771            active_model: self.model.clone(),
772            remaining_fallback_models: self.fallback_models.clone(),
773            activated_tools: context.activated_tools().iter().cloned().collect(),
774            unresolved_call_ids: context.conversation().unresolved_call_ids(),
775            residual_summary: measured
776                .residuals
777                .iter()
778                .map(|residual| (format!("{:?}", residual.class), residual.score))
779                .collect(),
780        }
781    }
782
783    fn maybe_compact(
784        &self,
785        goal: &str,
786        turn: u32,
787        measured: &Measured,
788        state: &mut TurnState,
789        context: &mut LoopContext,
790    ) -> Result<()> {
791        let route_limit = self.transport.capabilities(&self.model).max_context_tokens;
792        let route_chars = usize::try_from(route_limit)
793            .unwrap_or(usize::MAX)
794            .saturating_mul(3);
795        let threshold = if route_chars == 0 {
796            self.budgets.context_soft_limit_chars
797        } else {
798            self.budgets.context_soft_limit_chars.min(route_chars)
799        };
800        if context.conversation().estimated_chars() <= threshold {
801            return Ok(());
802        }
803
804        let authority_epoch = self
805            .kernel_state
806            .witnesses
807            .get("__authority_epoch")
808            .map(String::as_str)
809            .and_then(|value| value.parse().ok())
810            .unwrap_or(0);
811        let control = self.control_frame(goal, turn, measured, state, context, authority_epoch);
812        // The rolling chain root commits to every event so far in O(1); the
813        // cursor makes each checkpoint cover exactly the span since the
814        // previous one instead of claiming the whole history from zero.
815        let covered_root = state.log.chain_root().to_string();
816        let checkpoint = ContextCheckpoint {
817            parent: state.cursor.parent.clone(),
818            covered_from: state.cursor.next_from,
819            covered_to: state.log.count().saturating_sub(1),
820            covered_event_root: covered_root.clone(),
821            control,
822            artifact_refs: vec![state.accepted_checkpoint.witness.state_root.clone()],
823            narrative_observation: None,
824        };
825        checkpoint
826            .validate_against(
827                &state.accepted_checkpoint.witness.state_root,
828                &state.accepted_checkpoint.witness.graph_revision,
829                authority_epoch,
830            )
831            .map_err(|error| anyhow::anyhow!(error.to_string()))?;
832        emit(
833            self.recorder,
834            &mut state.log,
835            LoopEvent::ContextCheckpointCreated {
836                checkpoint: checkpoint.clone(),
837            },
838        )?;
839        self.apply_compaction(state, context, &checkpoint, covered_root)
840    }
841
842    /// Apply one compaction: replace the projection with the verbatim
843    /// control frame and record the eviction (PSP-10 Definition 6:
844    /// compaction moves material to the backing store, never destroys it).
845    fn apply_compaction(
846        &self,
847        state: &mut TurnState,
848        context: &mut LoopContext,
849        checkpoint: &ContextCheckpoint,
850        covered_root: String,
851    ) -> Result<()> {
852        let control_json = serde_json::to_string(&checkpoint.control)?;
853        context.compact(
854            format!("PERSPECTIVE_CONTROL_FRAME_V1\n{control_json}"),
855            self.recorder,
856            &mut state.log,
857        )?;
858        emit(
859            self.recorder,
860            &mut state.log,
861            LoopEvent::ContextCompacted {
862                forest_id: String::new(),
863                branch_id: String::new(),
864                summary_page: covered_root.clone(),
865                source_pages: checkpoint.artifact_refs.clone(),
866            },
867        )?;
868        state.cursor.parent = Some(covered_root);
869        state.cursor.next_from = checkpoint.covered_to.saturating_add(1);
870        Ok(())
871    }
872
873    /// Measure the realized candidate and submit it to the gate. The two
874    /// events share one candidate identity, and the gate event records the
875    /// trajectory's own `GateDecisionRef` fields — never recovered by
876    /// correlation (PSP-10 Phase 2).
877    async fn measure_and_gate(
878        &mut self,
879        candidate_id: &str,
880        trajectory: &mut AcceptedTrajectory,
881        log: &mut EventLog,
882    ) -> Result<(Measured, GateDecision)> {
883        self.reserve_verifier_action(log)?;
884        let measured = self.measurer.measure().await?;
885        emit(
886            self.recorder,
887            log,
888            LoopEvent::CandidateMeasured {
889                node_id: self.node_id.clone(),
890                generation: self.generation,
891                candidate_id: candidate_id.to_string(),
892                energy: measured.energy,
893                hard_pass: measured.hard_pass,
894                residuals: measured.residuals.clone(),
895            },
896        )?;
897        let decision = trajectory.submit_with_floor(
898            measured.hard_pass,
899            measured.energy,
900            self.budgets.declared_energy_floor,
901        )?;
902        let recorded = trajectory
903            .gate_decisions
904            .last()
905            .context("submit_with_floor appended no decision")?;
906        emit(
907            self.recorder,
908            log,
909            LoopEvent::GateDecisionRecorded {
910                node_id: self.node_id.clone(),
911                generation: self.generation,
912                candidate_id: candidate_id.to_string(),
913                decision: decision.clone(),
914                observed_energy: Some(recorded.observed_energy),
915                best_accepted_before: Some(recorded.best_accepted_before),
916            },
917        )?;
918        Ok((measured, decision))
919    }
920
921    /// Terminal classification of the measured baseline, if any.
922    fn baseline_terminal(&self, baseline: &Measured) -> Option<NodeTerminalOutcome> {
923        if baseline.hard_pass {
924            return Some(NodeTerminalOutcome::HardPass);
925        }
926        if let Some(floor) = self.budgets.declared_energy_floor
927            && baseline.energy <= floor
928        {
929            return Some(NodeTerminalOutcome::DeclaredFloor { floor });
930        }
931        None
932    }
933
934    /// Map a gate decision to a terminal outcome, or `None` to continue.
935    fn classify_decision(
936        &self,
937        decision: &GateDecision,
938        measured: &Measured,
939    ) -> Option<NodeTerminalOutcome> {
940        match decision {
941            GateDecision::HardPass => Some(NodeTerminalOutcome::HardPass),
942            GateDecision::StoppedAtDeclaredFloor => {
943                let floor = self
944                    .budgets
945                    .declared_energy_floor
946                    .unwrap_or(measured.energy);
947                Some(NodeTerminalOutcome::DeclaredFloor { floor })
948            }
949            _ => None,
950        }
951    }
952
953    /// Record a denial as evidence: counted in the projection mismatch,
954    /// ledgered with its typed residual class, and returned to the model.
955    fn deny(
956        &self,
957        log: &mut EventLog,
958        projection: &mut ProjectionMismatch,
959        call_id: &str,
960        reason: String,
961        class: perspt_sdk::ResidualClass,
962    ) -> Result<String> {
963        projection.denied_proposals += 1;
964        emit(
965            self.recorder,
966            log,
967            LoopEvent::EffectDenied {
968                call_id: call_id.to_string(),
969                reason: reason.clone(),
970                class,
971            },
972        )?;
973        Ok(format!("denied: {reason}"))
974    }
975
976    /// Per-turn budget denials (Gate J: a call above the budget still gets a
977    /// recorded proposal-and-result pair; it is denied, not silently
978    /// dropped). Returns `None` when the call is within budget.
979    #[allow(clippy::too_many_arguments)]
980    fn budget_denial(
981        &self,
982        ordinal: u32,
983        mutating: bool,
984        mutations: u32,
985        max_mutations: u32,
986    ) -> Option<String> {
987        if ordinal >= self.budgets.max_calls_per_turn {
988            return Some("per-turn tool-call budget exceeded".into());
989        }
990        if mutating && mutations >= max_mutations {
991            return Some("verification boundary required before another mutation".into());
992        }
993        None
994    }
995
996    async fn record_unchecked_proposal(
997        &self,
998        call: &ProviderToolCall,
999        entry: &ToolEntry,
1000        log: &mut EventLog,
1001    ) -> Result<()> {
1002        let before = self.executor.checkpoint(&[]).await?;
1003        let proposal = proposal_from(call, entry, &self.node_id, self.generation, &before.witness);
1004        emit(
1005            self.recorder,
1006            log,
1007            LoopEvent::ProposalObserved {
1008                call_id: call.call_id.clone(),
1009                proposal,
1010            },
1011        )
1012    }
1013
1014    fn high_risk(entry: Option<&ToolEntry>) -> bool {
1015        entry.is_some_and(|entry| {
1016            matches!(
1017                entry.risk,
1018                perspt_sdk::RiskClass::High | perspt_sdk::RiskClass::Critical
1019            )
1020        })
1021    }
1022
1023    /// Evaluate all five clauses for a transition and ledger the witness.
1024    fn certify(
1025        &self,
1026        call_id: &str,
1027        transition: &CandidateTransition,
1028        log: &mut EventLog,
1029    ) -> Result<FullAdmissibilityWitness> {
1030        let witness = check_full_admissibility(
1031            transition,
1032            &self.capabilities,
1033            &self.kernel_state,
1034            self.contract,
1035            self.barrier,
1036            self.c_c_max,
1037        )
1038        .map_err(|e| anyhow::anyhow!("kernel: {e}"))?;
1039        emit(
1040            self.recorder,
1041            log,
1042            LoopEvent::ProposalChecked {
1043                call_id: call_id.to_string(),
1044                proposal: transition.proposal.clone(),
1045                witness: Box::new(witness.clone()),
1046            },
1047        )?;
1048        Ok(witness)
1049    }
1050
1051    /// Kernel check, promote, and execute one call.
1052    ///
1053    /// Both effect classes are certified by exactly one evaluator
1054    /// (`check_full_admissibility`): non-mutating effects on the identity
1055    /// transition before any process launches, mutating effects again on the
1056    /// realized transition after the reversible overlay was touched.
1057    async fn check_and_apply(
1058        &mut self,
1059        call: &ProviderToolCall,
1060        recall: Option<&resident::RecallIndex>,
1061        log: &mut EventLog,
1062        projection: &mut ProjectionMismatch,
1063        mutations: &mut u32,
1064    ) -> Result<String> {
1065        let Some(entry) = self.catalog.lookup(&call.name).cloned() else {
1066            return self.deny(
1067                log,
1068                projection,
1069                &call.call_id,
1070                format!("unknown tool {:?}", call.name),
1071                perspt_sdk::ResidualClass::CapabilityDenied,
1072            );
1073        };
1074        let scope = proposal_scope(call, &entry);
1075        let before = self.executor.checkpoint(&scope).await?;
1076        let proposal = proposal_from(
1077            call,
1078            &entry,
1079            &self.node_id,
1080            self.generation,
1081            &before.witness,
1082        );
1083        emit(
1084            self.recorder,
1085            log,
1086            LoopEvent::ProposalObserved {
1087                call_id: call.call_id.clone(),
1088                proposal: proposal.clone(),
1089            },
1090        )?;
1091        self.kernel_state
1092            .set_witness("__candidate_root", before.witness.state_root.clone());
1093
1094        // Full five-clause certification on the identity transition before
1095        // even the reversible candidate overlay is touched.
1096        let identity = CandidateTransition::new(
1097            proposal.clone(),
1098            before.witness.clone(),
1099            before.witness.clone(),
1100        );
1101        let witness = self.certify(&call.call_id, &identity, log)?;
1102        if let Some(reason) = uncertified_reason(&witness) {
1103            return self.deny(
1104                log,
1105                projection,
1106                &call.call_id,
1107                reason,
1108                perspt_sdk::ResidualClass::CapabilityDenied,
1109            );
1110        }
1111
1112        if !candidate_mutating_effect(entry.effect) {
1113            // Reads and governed verifier processes do not change the logical
1114            // candidate state, so the identity certification above is their
1115            // complete Def. 3.2 witness; no external process launches on a
1116            // partial one.
1117            promote_matching_capability(&mut self.capabilities, &witness)
1118                .map_err(|error| anyhow::anyhow!("promotion: {error}"))?;
1119            return self.execute_non_mutating(call, &entry, recall, log).await;
1120        }
1121
1122        self.apply_mutating(call, &entry, proposal, &before, log, projection, mutations)
1123            .await
1124    }
1125
1126    /// Apply a mutating call to the reversible overlay, certify the realized
1127    /// transition, and either keep it (debiting the capability) or restore.
1128    #[allow(clippy::too_many_arguments)]
1129    async fn apply_mutating(
1130        &mut self,
1131        call: &ProviderToolCall,
1132        entry: &ToolEntry,
1133        proposal: EffectProposal,
1134        before: &CandidateCheckpoint,
1135        log: &mut EventLog,
1136        projection: &mut ProjectionMismatch,
1137        mutations: &mut u32,
1138    ) -> Result<String> {
1139        let bracket_key = self.open_effect_bracket(call, entry)?;
1140        let outcome = self.executor.apply(call, entry).await?;
1141        if outcome.completed
1142            && let (Some(recorder), Some(key)) = (self.recorder, bracket_key.as_deref())
1143        {
1144            recorder.external_result(key, &serde_json::json!({"mutated": outcome.mutated}))?;
1145        }
1146        let after = self.executor.state_witness().await?;
1147        let transition = CandidateTransition::new(proposal, before.witness.clone(), after);
1148        let witness = self.certify(&call.call_id, &transition, log)?;
1149        let output = bounded_model_output(self.recorder, outcome.output)?;
1150
1151        if let Some(reason) = uncertified_reason(&witness) {
1152            self.executor.restore(before).await?;
1153            // Denials are evidence, not errors: returned to the model so the
1154            // loop can adapt, and recorded for the ledger.
1155            return self.deny(
1156                log,
1157                projection,
1158                &call.call_id,
1159                reason,
1160                perspt_sdk::ResidualClass::CapabilityDenied,
1161            );
1162        }
1163
1164        // The debit and the effect stand or fall together: a failed promotion
1165        // restores the overlay and consumes no capability budget.
1166        if let Err(e) = promote_matching_capability(&mut self.capabilities, &witness) {
1167            self.executor.restore(before).await?;
1168            return self.deny(
1169                log,
1170                projection,
1171                &call.call_id,
1172                format!("promotion: {e}"),
1173                perspt_sdk::ResidualClass::CapabilityDenied,
1174            );
1175        }
1176        if outcome.mutated {
1177            *mutations += 1;
1178            self.reserve_verifier_action(log)?;
1179            let boundary = self.measurer.measure_incremental().await?;
1180            emit(
1181                self.recorder,
1182                log,
1183                LoopEvent::EffectBoundaryMeasured {
1184                    call_id: call.call_id.clone(),
1185                    node_id: self.node_id.clone(),
1186                    generation: self.generation,
1187                    energy: boundary.energy,
1188                    hard_pass: boundary.hard_pass,
1189                    residuals: boundary.residuals,
1190                },
1191            )?;
1192        }
1193        emit(
1194            self.recorder,
1195            log,
1196            LoopEvent::EffectApplied {
1197                call_id: call.call_id.clone(),
1198                mutated: outcome.mutated,
1199                output: output.clone(),
1200            },
1201        )?;
1202        Ok(output)
1203    }
1204}
1205
1206const MODEL_OUTPUT_PREVIEW_BYTES: usize = 8 * 1024;
1207
1208fn bounded_model_output(recorder: Option<&dyn LoopRecorder>, output: String) -> Result<String> {
1209    if output.len() <= MODEL_OUTPUT_PREVIEW_BYTES || recorder.is_none() {
1210        return Ok(output);
1211    }
1212    let recorder = recorder.expect("checked above");
1213    let handle = recorder.record_artifact(output.as_bytes(), "text/plain; charset=utf-8")?;
1214    let mut boundary = MODEL_OUTPUT_PREVIEW_BYTES;
1215    while !output.is_char_boundary(boundary) {
1216        boundary -= 1;
1217    }
1218    Ok(format!(
1219        "{}\n[full output: artifact:{handle}; {} bytes]",
1220        &output[..boundary],
1221        output.len()
1222    ))
1223}
1224
1225fn activated_tools_from_conversation(conversation: &Conversation) -> BTreeSet<String> {
1226    let mut search_calls = BTreeSet::new();
1227    let mut activated = BTreeSet::new();
1228    for message in conversation.messages() {
1229        match message {
1230            perspt_sdk::Message::AssistantToolCalls { calls } => {
1231                search_calls.extend(
1232                    calls
1233                        .iter()
1234                        .filter(|call| call.name == "tool_search")
1235                        .map(|call| call.call_id.clone()),
1236                );
1237            }
1238            perspt_sdk::Message::ToolResponse { call_id, content }
1239                if search_calls.contains(call_id) =>
1240            {
1241                if let Ok(specs) = serde_json::from_str::<Vec<perspt_sdk::ToolSpec>>(content) {
1242                    activated.extend(specs.into_iter().map(|spec| spec.name));
1243                }
1244            }
1245            _ => {}
1246        }
1247    }
1248    activated
1249}
1250
1251/// Paths a call names, for the checkpoint scope. An entry that declares
1252/// `proposal_bindings` is authoritative; the conventional `path`/`to`/`from`
1253/// fields cover the builtins, which declare none.
1254fn push_correction(
1255    context: &mut LoopContext,
1256    measured: &Measured,
1257    accepted: bool,
1258    recorder: Option<&dyn LoopRecorder>,
1259    log: &mut EventLog,
1260) -> Result<()> {
1261    // Infrastructure-only residuals are not code defects: steering the
1262    // model to "fix" them loops forever. Name the gap instead — the model
1263    // can add missing project configuration or report the blocker.
1264    let infra_only = !measured.residuals.is_empty()
1265        && measured
1266            .residuals
1267            .iter()
1268            .all(|residual| residual.class == perspt_sdk::ResidualClass::SensorUnavailable);
1269    if infra_only {
1270        let gaps: Vec<&str> = measured
1271            .residuals
1272            .iter()
1273            .take(4)
1274            .map(|residual| residual.evidence.summary.as_str())
1275            .collect();
1276        return context.push_user(
1277            format!(
1278                "Verification is blocked by unavailable sensors, not by the \
1279                 code: {}. If project configuration can enable them (for \
1280                 example a missing manifest), add it; otherwise state the \
1281                 blocker plainly and stop.",
1282                gaps.join("; ")
1283            ),
1284            recorder,
1285            log,
1286        );
1287    }
1288    let instruction = measured
1289        .correction
1290        .as_ref()
1291        .map(|c| c.instruction.clone())
1292        .unwrap_or_else(|| {
1293            if accepted {
1294                format!(
1295                    "The candidate descended to V = {:.3}. Continue addressing the remaining residuals.",
1296                    measured.energy
1297                )
1298            } else {
1299                format!(
1300                    "The candidate did not descend (V = {:.3}). Address the dominant residual.",
1301                    measured.energy
1302                )
1303            }
1304        });
1305    context.push_user(instruction, recorder, log)
1306}
1307
1308/// The seeded goal plus the baseline's typed diagnostics (up to six),
1309/// so the first model turn starts from measured evidence.
1310fn goal_with_baseline(goal: &str, baseline: &Measured) -> String {
1311    if baseline.residuals.is_empty() {
1312        return goal.to_string();
1313    }
1314    let mut text = goal.to_string();
1315    text.push_str("\n\nBaseline diagnostics (already measured):\n");
1316    for residual in baseline.residuals.iter().take(6) {
1317        text.push_str("- ");
1318        text.push_str(&residual.evidence.summary);
1319        text.push('\n');
1320    }
1321    text
1322}
1323
1324/// The finite decision bound the loop must respect. Computed once at node
1325/// entry from the measured baseline; the loop refuses the `(N_gate + 1)`-th
1326/// gate submission and terminates through the exhaustion path (Gate X).
1327pub fn loop_decision_bound(baseline_energy: f64, budgets: &LoopBudgets) -> Result<u64> {
1328    perspt_sdk::finite_decision_bound(baseline_energy, budgets.rho_gate, budgets.rejection_budget)
1329        .map_err(|e| anyhow::anyhow!("{e}"))
1330}
1331
1332fn emit(recorder: Option<&dyn LoopRecorder>, log: &mut EventLog, event: LoopEvent) -> Result<()> {
1333    if let Some(recorder) = recorder {
1334        recorder.record(&event)?;
1335    }
1336    log.push(&event)?;
1337    Ok(())
1338}