Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
184
crates/luxe-core/src/hooks/completion_challenger.rs
Normal file
184
crates/luxe-core/src/hooks/completion_challenger.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
//! Completion challenger — forces verification + confirmations before ending the loop.
|
||||
//!
|
||||
//! Prevents premature completion by requiring a forced verification turn and multiple
|
||||
//! confirmations before the loop can end.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::loop_controller::LoopController;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info};
|
||||
|
||||
struct HookState {
|
||||
confirmations_required: u8,
|
||||
confirmations_received: u8,
|
||||
}
|
||||
|
||||
/// A hook that challenges premature completion requests.
|
||||
///
|
||||
/// When `loop_control action="complete"` is received, forces a verification turn
|
||||
/// listing every phase + Definition-of-Done item with status. Only stops after
|
||||
/// configurable number of confirmations.
|
||||
pub struct CompletionChallengerHook {
|
||||
/// Loop controller for checking state.
|
||||
loop_controller: Arc<LoopController>,
|
||||
/// What a completion claim has to clear, shared with the phase gate the loop already runs.
|
||||
gate: Arc<crate::phase_gate::PhaseGate>,
|
||||
/// Mutable hook state (confirmations).
|
||||
state: Arc<Mutex<HookState>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CompletionChallengerHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("CompletionChallengerHook").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl CompletionChallengerHook {
|
||||
/// Create a new completion challenger hook.
|
||||
pub async fn new(loop_controller: Arc<LoopController>) -> Self {
|
||||
// Read the documented config knob from LoopState; fall back to 2 if unset (0).
|
||||
let state = loop_controller.get_state().await;
|
||||
let confirmations_required = if state.confirmations_required == 0 {
|
||||
2 // >=2 so the first `complete` surfaces the verification turn; a second call stops.
|
||||
} else {
|
||||
state.confirmations_required
|
||||
};
|
||||
|
||||
Self {
|
||||
loop_controller,
|
||||
gate: Arc::new(crate::phase_gate::PhaseGate::new()),
|
||||
state: Arc::new(Mutex::new(HookState {
|
||||
confirmations_required,
|
||||
confirmations_received: 0,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Judge completion claims with `gate`, the same one the phase gate runs.
|
||||
pub fn with_gate(mut self, gate: Arc<crate::phase_gate::PhaseGate>) -> Self {
|
||||
self.gate = gate;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the number of confirmations required.
|
||||
pub async fn set_confirmations_required(&self, n: u8) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.confirmations_required = n;
|
||||
}
|
||||
|
||||
/// Increment the confirmation counter.
|
||||
pub async fn increment_confirmation(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
if state.confirmations_received < state.confirmations_required {
|
||||
state.confirmations_received += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset the confirmation counter.
|
||||
pub async fn reset_confirmations(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.confirmations_received = 0;
|
||||
}
|
||||
|
||||
/// Check if we have enough confirmations to stop.
|
||||
async fn has_enough_confirmations(&self) -> bool {
|
||||
let state = self.state.lock().await;
|
||||
state.confirmations_received >= state.confirmations_required
|
||||
}
|
||||
|
||||
/// Get the verification message (asks the model to list all phases + Definition-of-Done items).
|
||||
fn verification_message(&self) -> String {
|
||||
"VERIFICATION REQUIRED: List every phase and Definition-of-Done item with status. Only call loop_control complete after re-confirmation.".to_string()
|
||||
}
|
||||
|
||||
/// Get the final stop message.
|
||||
fn final_stop_message(&self) -> String {
|
||||
"All phases verified. Ending loop.".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for CompletionChallengerHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"completion-challenger"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::LoopControl]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
let loop_control = match ev {
|
||||
HookEvent::LoopControl(lc) => lc,
|
||||
_ => return HookOutcome::Continue,
|
||||
};
|
||||
|
||||
if !self.loop_controller.is_running().await {
|
||||
debug!("loop not running, ignoring");
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
match loop_control {
|
||||
crate::hook::LoopControl::Complete => {
|
||||
// The gate first: `complete` is a claim like `progress`, and a door with no gate on
|
||||
// it lets an agent leave without the reviewer ever being consulted. A refused claim
|
||||
// does not count as a confirmation either: the agent has to fix the work and ask
|
||||
// again.
|
||||
let phase = self.loop_controller.get_state().await.current_phase;
|
||||
cx.notify("the work is claimed complete — running the gate");
|
||||
match self.gate.run(phase, "the work", &|line| cx.notify(line)).await {
|
||||
crate::phase_gate::GateOutcome::Passed => {}
|
||||
crate::phase_gate::GateOutcome::Refused(message) => {
|
||||
info!("the gate refused the completion claim");
|
||||
cx.notify(format!(
|
||||
"completion held: {}",
|
||||
crate::hooks::first_line(&message)
|
||||
));
|
||||
return HookOutcome::ContinueLoop {
|
||||
message: format!("{message}\n\nThe loop is still running."),
|
||||
};
|
||||
}
|
||||
crate::phase_gate::GateOutcome::Held(message) => {
|
||||
return crate::hooks::review_integrator::pause_for_a_person(
|
||||
&self.loop_controller,
|
||||
cx,
|
||||
message,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Require verification + confirmations.
|
||||
// Increment confirmation count on each complete request.
|
||||
self.increment_confirmation().await;
|
||||
if self.has_enough_confirmations().await {
|
||||
info!("enough confirmations, stopping loop");
|
||||
cx.notify("every phase verified — the run is complete");
|
||||
let _ = self.loop_controller.stop().await;
|
||||
return HookOutcome::ContinueLoop { message: self.final_stop_message() };
|
||||
}
|
||||
cx.notify("completion claimed — asking for a verification pass first");
|
||||
HookOutcome::ContinueLoop { message: self.verification_message() }
|
||||
}
|
||||
// Progress is the review integrator's business: a phase advances when the acceptance
|
||||
// gate agrees it may, and this hook does not run that gate. Advancing here as well is
|
||||
// how the counter moved twice for one claim, and moved at all for a claim the gate
|
||||
// would have refused.
|
||||
crate::hook::LoopControl::Progress { .. } => HookOutcome::Continue,
|
||||
crate::hook::LoopControl::Blocked { reason } => {
|
||||
info!(reason = %reason, "loop blocked");
|
||||
cx.notify(format!(
|
||||
"blocked, waiting for a person: {}",
|
||||
crate::hooks::first_line(reason)
|
||||
));
|
||||
let _ = self.loop_controller.pause().await;
|
||||
HookOutcome::StopLoop { reason: format!("Blocked: {reason}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
246
crates/luxe-core/src/hooks/completion_challenger/tests.rs
Normal file
246
crates/luxe-core/src/hooks/completion_challenger/tests.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_completion_challenger_hook_not_running() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
let hook = CompletionChallengerHook::new(controller).await;
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Loop not running -> Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
/// A completion claim the reviewer cannot approve pauses the run instead of ending it.
|
||||
///
|
||||
/// The break this catches: the gate's undecided outcome falling through to the confirmation
|
||||
/// count, so an outage could let a run declare itself complete with nobody having reviewed it.
|
||||
#[tokio::test]
|
||||
async fn an_undecided_completion_pauses_rather_than_ends() {
|
||||
use crate::phase_review::{PhaseReviewOutcome, PhaseReviewRequest, PhaseReviewer};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Down;
|
||||
#[async_trait]
|
||||
impl PhaseReviewer for Down {
|
||||
async fn review(&self, _request: PhaseReviewRequest) -> PhaseReviewOutcome {
|
||||
PhaseReviewOutcome::Unavailable("provider down".into())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Change;
|
||||
#[async_trait]
|
||||
impl crate::phase_gate::PhaseReviewContext for Change {
|
||||
async fn diff(&self) -> Result<String, String> {
|
||||
Ok("+ change".into())
|
||||
}
|
||||
async fn planning(&self, _phase: u32) -> String {
|
||||
String::new()
|
||||
}
|
||||
async fn files(
|
||||
&self,
|
||||
_diff: &str,
|
||||
_planning: &str,
|
||||
) -> Vec<crate::phase_review::ReviewedFile> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
let gate = crate::phase_gate::PhaseGate::new().with_reviewer(Arc::new(Down), Arc::new(Change));
|
||||
let hook = CompletionChallengerHook::new(controller.clone()).await.with_gate(Arc::new(gate));
|
||||
hook.set_confirmations_required(1).await;
|
||||
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::StopLoop { .. }), "got {outcome:?}");
|
||||
assert!(!controller.is_running().await, "paused");
|
||||
assert!(!dir.path().join("STOP").exists(), "paused, not stopped: the run resumes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_completion_challenger_hook_verification() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = CompletionChallengerHook::new(controller).await;
|
||||
hook.set_confirmations_required(2).await;
|
||||
|
||||
// First call should request verification (counter increments to 1).
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("VERIFICATION REQUIRED"), "message was: {}", message);
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome, got {:?}", outcome),
|
||||
}
|
||||
|
||||
// Second call should stop the loop (counter increments to 2, >= 2).
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("Ending loop"), "message was: {}", message);
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome, got {:?}", outcome),
|
||||
}
|
||||
|
||||
// Loop should be stopped.
|
||||
assert!(!hook.loop_controller.is_running().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_completion_challenger_hook_reset() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = CompletionChallengerHook::new(controller).await;
|
||||
hook.set_confirmations_required(2).await;
|
||||
|
||||
// Increment confirmation.
|
||||
hook.increment_confirmation().await;
|
||||
|
||||
// Reset confirmations.
|
||||
hook.reset_confirmations().await;
|
||||
|
||||
// Verify by checking state.
|
||||
let state = hook.state.lock().await;
|
||||
assert_eq!(state.confirmations_received, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_completion_challenger_reads_loop_state_config() {
|
||||
// Regression test: verifies the challenger reads confirmations_required from
|
||||
// LoopState at construction time (not just the hook's own setter). This pins
|
||||
// the threading introduced in 6b2c179 so it can't silently regress.
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
// Set LoopState.confirmations_required to 3 (distinctive value).
|
||||
controller
|
||||
.update_state(|s| {
|
||||
s.confirmations_required = 3;
|
||||
})
|
||||
.await;
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = CompletionChallengerHook::new(controller).await;
|
||||
|
||||
// First Complete -> verify (counter 0->1, 1<3).
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("VERIFICATION REQUIRED"), "message was: {}", message);
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome, got {:?}", outcome),
|
||||
}
|
||||
|
||||
// Second Complete -> verify (counter 1->2, 2<3).
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("VERIFICATION REQUIRED"), "message was: {}", message);
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome, got {:?}", outcome),
|
||||
}
|
||||
|
||||
// Third Complete -> stop (counter 2->3, 3>=3).
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(crate::hook::LoopControl::Complete),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("Ending loop"), "message was: {}", message);
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome, got {:?}", outcome),
|
||||
}
|
||||
|
||||
// Loop should be stopped.
|
||||
assert!(!hook.loop_controller.is_running().await);
|
||||
}
|
||||
237
crates/luxe-core/src/hooks/context_aware_termination.rs
Normal file
237
crates/luxe-core/src/hooks/context_aware_termination.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
//! Context-aware termination hook — ends a loop run when the context window is nearly full.
|
||||
//!
|
||||
//! Reads the turn's effective-context percent — occupancy of the usable window (see
|
||||
//! [`crate::compaction::usable_context_window`]) — from the `AgentEnd` event the engine attaches.
|
||||
//! At the `pause_percent` high-water mark it ends the run, so the next one starts lean.
|
||||
//!
|
||||
//! Compacting is the engine's job, at the threshold `luxe loop start` gives it. This hook does not
|
||||
//! answer `compact_percent`: a "wrap up and summarize" note compacts nothing, and a session grows
|
||||
//! without bound while carrying one on every turn.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::loop_controller::LoopController;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info};
|
||||
|
||||
struct HookState {
|
||||
grace_turns_remaining: u32,
|
||||
}
|
||||
|
||||
/// Pull the effective-context percent the engine attached to the `AgentEnd` event (0.0 when
|
||||
/// absent — e.g. no usage observed yet).
|
||||
fn effective_percent(ev: &HookEvent) -> f64 {
|
||||
match ev {
|
||||
HookEvent::Other(v) => {
|
||||
v.get("effective_context_percent").and_then(serde_json::Value::as_f64).unwrap_or(0.0)
|
||||
}
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A hook that ends a loop run once effective context passes `pause_percent`.
|
||||
///
|
||||
/// Fires on `HookPoint::AgentEnd`.
|
||||
pub struct ContextAwareTerminationHook {
|
||||
/// Loop controller for checking state and context thresholds.
|
||||
loop_controller: Arc<LoopController>,
|
||||
/// Mutable hook state (effective context, grace period).
|
||||
state: Arc<Mutex<HookState>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ContextAwareTerminationHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ContextAwareTerminationHook").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextAwareTerminationHook {
|
||||
/// Create a new context-aware termination hook.
|
||||
pub fn new(loop_controller: Arc<LoopController>) -> Self {
|
||||
Self {
|
||||
loop_controller,
|
||||
state: Arc::new(Mutex::new(HookState { grace_turns_remaining: 0 })),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set grace period turns (after compaction).
|
||||
pub async fn set_grace_period(&self, turns: u32) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.grace_turns_remaining = turns;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for ContextAwareTerminationHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"context-aware-termination"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::AgentEnd]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
let percent = effective_percent(ev);
|
||||
let mut state = self.state.lock().await;
|
||||
|
||||
// Decrement grace period.
|
||||
if state.grace_turns_remaining > 0 {
|
||||
state.grace_turns_remaining -= 1;
|
||||
}
|
||||
|
||||
if !self.loop_controller.is_running().await {
|
||||
debug!("loop not running, skipping");
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
let controller_state = self.loop_controller.get_state().await;
|
||||
|
||||
if state.grace_turns_remaining > 0 {
|
||||
debug!(
|
||||
grace_turns_remaining = state.grace_turns_remaining,
|
||||
"in grace period, skipping"
|
||||
);
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
if controller_state.should_pause_for_compaction(percent) {
|
||||
info!(
|
||||
effective_context = percent,
|
||||
"ending the run for compaction at the pause threshold"
|
||||
);
|
||||
cx.notify(format!(
|
||||
"the context window is {percent:.0}% full — ending the run so it can compact"
|
||||
));
|
||||
let _ = self.loop_controller.stop().await;
|
||||
return HookOutcome::ContinueLoop {
|
||||
message: "Context limit reached. Ending run for compaction.".to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
HookOutcome::Continue
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_context_aware_termination_not_running() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
let hook = ContextAwareTerminationHook::new(controller);
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Loop not running -> Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_context_aware_termination_grace_period() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = ContextAwareTerminationHook::new(controller);
|
||||
hook.set_grace_period(3).await;
|
||||
|
||||
// Even a pause-level percent is suppressed while in the grace window.
|
||||
let ev = HookEvent::Other(serde_json::json!({ "effective_context_percent": 95.0 }));
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&ev,
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
assert!(hook.loop_controller.is_running().await, "grace must not end the run");
|
||||
}
|
||||
|
||||
/// Past `compact_percent` and short of the pause, the run goes on with no note of its own.
|
||||
///
|
||||
/// The break this catches: the hook answered the threshold with a "wrap up" steer every turn,
|
||||
/// which compacted nothing and asked the agent to stop working.
|
||||
#[tokio::test]
|
||||
async fn past_the_compaction_mark_the_hook_sends_no_nudge() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = ContextAwareTerminationHook::new(controller);
|
||||
// 80%: past the default compact_percent (75), short of pause_percent (90)
|
||||
let ev = HookEvent::Other(serde_json::json!({ "effective_context_percent": 80.0 }));
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&ev,
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::Continue), "{outcome:?}");
|
||||
assert!(hook.loop_controller.is_running().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_context_aware_termination_pause() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = ContextAwareTerminationHook::new(controller);
|
||||
// 95%: above default pause_percent (90) -> end the run.
|
||||
let ev = HookEvent::Other(serde_json::json!({ "effective_context_percent": 95.0 }));
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&ev,
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert!(message.contains("Ending run"));
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome"),
|
||||
}
|
||||
|
||||
// Loop should be stopped.
|
||||
assert!(!hook.loop_controller.is_running().await);
|
||||
}
|
||||
}
|
||||
360
crates/luxe-core/src/hooks/file_changed.rs
Normal file
360
crates/luxe-core/src/hooks/file_changed.rs
Normal file
@@ -0,0 +1,360 @@
|
||||
//! Built-in hook that runs diagnostics and formatters when a file changes.
|
||||
//!
|
||||
//! Listens for `FileChanged` events and, when configured:
|
||||
//! - Runs the appropriate formatter for the changed file's language (format-on-save).
|
||||
//! - Runs LSP diagnostics on the changed file, surfacing what the edit introduced to the agent.
|
||||
//!
|
||||
//! # New problems, not every problem
|
||||
//!
|
||||
//! Every diagnostic in the file after each edit is the wrong report: in a codebase the language
|
||||
//! server only half understands — Django under pyright, without the virtualenv — it is a dozen
|
||||
//! errors the edit had nothing to do with, on every edit, re-read on every later turn, with an
|
||||
//! instruction to chase them. So before the first `edit` or `write` of a file the hook
|
||||
//! records what was already wrong, and after each change it reports only what is new and counts
|
||||
//! the rest. The comparison ignores line numbers, since an edit moves everything below it.
|
||||
|
||||
mod standards;
|
||||
|
||||
pub use standards::{FunctionSize, OutlineSource};
|
||||
|
||||
use crate::formatter::FormatterRegistry;
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use async_trait::async_trait;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// Reports changed symbols that no test covers, for the file just edited.
|
||||
///
|
||||
/// A test gap is *work*, not review information. Handing it to the human at review time makes them
|
||||
/// find the warning, read it, and retype it as a prompt; telling the agent while it is still editing
|
||||
/// lets it decide — write the test, or say why the change does not need one. Implemented outside
|
||||
/// `luxe-core` (the code graph lives in `luxe-lsp`) and injected here, exactly like review insight.
|
||||
#[async_trait]
|
||||
pub trait TestGapAdvisor: Send + Sync {
|
||||
/// Changed symbols in `path` with no covering test, as `path::Symbol`. Empty when there are none
|
||||
/// or the graph cannot say.
|
||||
async fn untested_symbols(&self, path: &std::path::Path) -> Vec<String>;
|
||||
}
|
||||
|
||||
/// A hook that runs formatters and diagnostics on file changes.
|
||||
pub struct FileChangedHook {
|
||||
/// Optional formatter registry for format-on-save.
|
||||
formatter_registry: Option<FormatterRegistry>,
|
||||
/// Optional LSP client for running diagnostics
|
||||
lsp_client: Option<Arc<dyn crate::lsp::DiagnosticsProvider>>,
|
||||
/// Optional shared cache the latest per-file diagnostics are published to for the dock.
|
||||
diagnostics_store: Option<crate::lsp::DiagnosticsStore>,
|
||||
/// Optional source of test-coverage gaps for the file just edited.
|
||||
test_gaps: Option<Arc<dyn TestGapAdvisor>>,
|
||||
/// What each file's diagnostics were before the change being reported, by absolute path
|
||||
baselines: std::sync::Mutex<std::collections::HashMap<PathBuf, Vec<crate::lsp::Diagnostic>>>,
|
||||
/// Where function boundaries come from, for the size standards
|
||||
outline: Option<Arc<dyn OutlineSource>>,
|
||||
/// Each file's size before the change being reported, by absolute path
|
||||
sizes: std::sync::Mutex<std::collections::HashMap<PathBuf, standards::SizeSnapshot>>,
|
||||
}
|
||||
|
||||
impl FileChangedHook {
|
||||
/// Create a new `FileChangedHook` with optional formatter registry and LSP client.
|
||||
pub fn new(
|
||||
formatter_registry: Option<FormatterRegistry>,
|
||||
lsp_client: Option<Arc<dyn crate::lsp::DiagnosticsProvider>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
formatter_registry,
|
||||
lsp_client,
|
||||
diagnostics_store: None,
|
||||
test_gaps: None,
|
||||
baselines: std::sync::Mutex::default(),
|
||||
outline: None,
|
||||
sizes: std::sync::Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the agent when a change takes a file past 500 lines or a function past 20.
|
||||
pub fn with_outline(mut self, outline: Arc<dyn OutlineSource>) -> Self {
|
||||
self.outline = Some(outline);
|
||||
self
|
||||
}
|
||||
|
||||
/// Report changed symbols with no covering test to the agent as it edits.
|
||||
pub fn with_test_gaps(mut self, advisor: Arc<dyn TestGapAdvisor>) -> Self {
|
||||
self.test_gaps = Some(advisor);
|
||||
self
|
||||
}
|
||||
|
||||
/// Publish each changed file's diagnostics to `store` so the Context Dock can show them.
|
||||
pub fn with_diagnostics_store(mut self, store: crate::lsp::DiagnosticsStore) -> Self {
|
||||
self.diagnostics_store = Some(store);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for FileChangedHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"file-changed"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::FileChanged, HookPoint::BeforeToolUse]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, _cx: &HookCtx) -> HookOutcome {
|
||||
if let HookEvent::ToolUse { tool_name, args } = ev {
|
||||
self.record_baseline(tool_name, args).await;
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
let HookEvent::FileChanged { path, operation } = ev else {
|
||||
return HookOutcome::Continue;
|
||||
};
|
||||
|
||||
let path_buf = PathBuf::from(path);
|
||||
// A formatter loads plugins named by the nearest config and a language server runs build
|
||||
// scripts, and in a fetched repository both of those came from a stranger
|
||||
if crate::fetched::contains(&path_buf) {
|
||||
debug!(path, "file_changed: inside a fetched repository; not formatting or checking");
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
debug!(path, operation, "file_changed: running formatter + diagnostics");
|
||||
|
||||
// Run the formatter if configured and a formatter exists for this language.
|
||||
if let Some(registry) = &self.formatter_registry {
|
||||
if registry.formatter_for(&path_buf).is_some() {
|
||||
debug!(path, "running formatter");
|
||||
match crate::formatter::run_formatter(&path_buf, registry).await {
|
||||
Ok(()) => debug!(path, "formatted successfully"),
|
||||
Err(e) => {
|
||||
// Formatter failure is non-fatal — skip silently with a note.
|
||||
warn!(error = %e, path, "formatter failed; skipping");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Diagnostics first: something being broken outranks something being too long, and both
|
||||
// outrank something being untested
|
||||
let mut notes = Vec::new();
|
||||
if let Some(lsp_client) = &self.lsp_client {
|
||||
match lsp_client.run_diagnostics(&path_buf).await {
|
||||
Ok(diagnostics) => {
|
||||
// Publish to the dock cache even when empty, so a fixed file drops out.
|
||||
if let Some(store) = &self.diagnostics_store {
|
||||
store.set(path_buf.clone(), diagnostics.clone());
|
||||
}
|
||||
let before =
|
||||
self.lock_baselines().insert(absolute(&path_buf), diagnostics.clone());
|
||||
let report = match &before {
|
||||
Some(before) => format_new_diagnostics(path, before, &diagnostics),
|
||||
None if diagnostics.is_empty() => None,
|
||||
None => Some(format_diagnostics(path, &diagnostics)),
|
||||
};
|
||||
notes.extend(report);
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(error = %e, path, "file_changed: failed to run diagnostics");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let broken = !notes.is_empty();
|
||||
notes.extend(self.size_note(path));
|
||||
|
||||
// Nothing is broken; is anything untested? Reported once per edit, bounded, and phrased as a
|
||||
// fact rather than an instruction — the agent decides what it is worth.
|
||||
if let (false, Some(advisor)) = (broken, &self.test_gaps) {
|
||||
let untested = advisor.untested_symbols(&path_buf).await;
|
||||
notes.extend(format_test_gaps(path, &untested));
|
||||
}
|
||||
|
||||
match notes.is_empty() {
|
||||
true => HookOutcome::Continue,
|
||||
false => HookOutcome::InjectContext(notes.join("\n")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FileChangedHook {
|
||||
/// Records what is already wrong with the file an `edit` or `write` is about to change, the
|
||||
/// first time this session touches it, so the report afterwards can tell its problems apart.
|
||||
async fn record_baseline(&self, tool: &str, args: &serde_json::Value) {
|
||||
if !matches!(tool, "edit" | "write") {
|
||||
return;
|
||||
}
|
||||
let Some(path) = args.get("path").and_then(|path| path.as_str()) else {
|
||||
return;
|
||||
};
|
||||
let path = crate::tool::ToolContext::working_dir().join(path);
|
||||
let key = absolute(&path);
|
||||
if crate::fetched::contains(&path) {
|
||||
return;
|
||||
}
|
||||
if let Some(outline) = &self.outline {
|
||||
let mut sizes = self.lock_sizes();
|
||||
if !sizes.contains_key(&key) {
|
||||
let source = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
sizes.insert(key.clone(), standards::snapshot(outline.as_ref(), &path, &source));
|
||||
}
|
||||
}
|
||||
let Some(lsp_client) = &self.lsp_client else {
|
||||
return;
|
||||
};
|
||||
if self.lock_baselines().contains_key(&key) {
|
||||
return;
|
||||
}
|
||||
// A file that does not exist yet has nothing wrong with it
|
||||
let before = if path.is_file() {
|
||||
match lsp_client.run_diagnostics(&path).await {
|
||||
Ok(diagnostics) => diagnostics,
|
||||
Err(error) => {
|
||||
debug!(%error, path = %path.display(), "no diagnostics baseline");
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
self.lock_baselines().insert(key, before);
|
||||
}
|
||||
|
||||
fn lock_sizes(
|
||||
&self,
|
||||
) -> std::sync::MutexGuard<'_, std::collections::HashMap<PathBuf, standards::SizeSnapshot>>
|
||||
{
|
||||
self.sizes.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The size limits `path` crossed in this change, measured against the last one.
|
||||
fn size_note(&self, path: &str) -> Option<String> {
|
||||
let outline = self.outline.as_ref()?;
|
||||
let path_buf = PathBuf::from(path);
|
||||
let source = std::fs::read_to_string(&path_buf).ok()?;
|
||||
let after = standards::snapshot(outline.as_ref(), &path_buf, &source);
|
||||
// No record of the file before means no change was seen coming, so nothing to compare
|
||||
let before = self.lock_sizes().insert(absolute(&path_buf), after.clone())?;
|
||||
standards::crossings(path, &before, &after)
|
||||
}
|
||||
|
||||
fn lock_baselines(
|
||||
&self,
|
||||
) -> std::sync::MutexGuard<'_, std::collections::HashMap<PathBuf, Vec<crate::lsp::Diagnostic>>>
|
||||
{
|
||||
self.baselines.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// One spelling per file, so a relative argument and an absolute event path meet.
|
||||
///
|
||||
/// A file `write` has not created yet cannot canonicalize, so its folder does instead: otherwise
|
||||
/// the record taken before it existed and the report after would land on different keys, which on
|
||||
/// Windows, where canonical paths gain a `\\?\` prefix, they always did.
|
||||
fn absolute(path: &std::path::Path) -> PathBuf {
|
||||
if let Ok(resolved) = path.canonicalize() {
|
||||
return resolved;
|
||||
}
|
||||
match (path.parent().map(std::path::Path::canonicalize), path.file_name()) {
|
||||
(Some(Ok(folder)), Some(name)) => folder.join(name),
|
||||
_ => path.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagnostics in `after` that were not in `before`, matched on severity and message rather
|
||||
/// than position, as a report — or `None` when the change introduced nothing.
|
||||
fn format_new_diagnostics(
|
||||
path: &str,
|
||||
before: &[crate::lsp::Diagnostic],
|
||||
after: &[crate::lsp::Diagnostic],
|
||||
) -> Option<String> {
|
||||
let mut remaining: Vec<&crate::lsp::Diagnostic> = before.iter().collect();
|
||||
let mut new = Vec::new();
|
||||
for diagnostic in after {
|
||||
let seen = remaining.iter().position(|old| {
|
||||
old.severity == diagnostic.severity && old.message == diagnostic.message
|
||||
});
|
||||
match seen {
|
||||
Some(at) => {
|
||||
remaining.swap_remove(at);
|
||||
}
|
||||
None => new.push(diagnostic.clone()),
|
||||
}
|
||||
}
|
||||
if new.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut report = render_diagnostics(path, &new, "new");
|
||||
let already = after.len() - new.len();
|
||||
if already > 0 {
|
||||
report.push_str(&format!(
|
||||
"({already} more were in the file before this change and are not listed.)\n"
|
||||
));
|
||||
}
|
||||
Some(report)
|
||||
}
|
||||
|
||||
/// Most untested symbols named inline; beyond this the list is counted.
|
||||
const MAX_INJECTED_TEST_GAPS: usize = 5;
|
||||
|
||||
/// `src/auth.rs: logout has no covering test.` — or `None` when everything changed is covered.
|
||||
fn format_test_gaps(path: &str, untested: &[String]) -> Option<String> {
|
||||
if untested.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let names: Vec<&str> = untested
|
||||
.iter()
|
||||
.take(MAX_INJECTED_TEST_GAPS)
|
||||
.map(|symbol| symbol.rsplit("::").next().unwrap_or(symbol))
|
||||
.collect();
|
||||
let overflow = untested.len().saturating_sub(names.len());
|
||||
let mut note = format!("{path}: no covering test for {}", names.join(", "));
|
||||
if overflow > 0 {
|
||||
note.push_str(&format!(" (+{overflow} more)"));
|
||||
}
|
||||
note.push_str(
|
||||
". Add one, or say why this change does not need it — a reviewer will be told the same thing.",
|
||||
);
|
||||
Some(note)
|
||||
}
|
||||
|
||||
/// Max diagnostics surfaced inline after an edit. The rest are summarized so a noisy file can't
|
||||
/// flood the model's context; the `lsp_diagnostics` tool always returns the full list.
|
||||
const MAX_INJECTED_DIAGNOSTICS: usize = 20;
|
||||
|
||||
/// Render diagnostics for injection: errors first, capped, with a summary tail when truncated.
|
||||
///
|
||||
/// Surfacing the just-edited file's diagnostics closes the edit→verify loop (the model sees what
|
||||
/// its change broke without being told to check). Ordering errors first + a cap keeps a file with
|
||||
/// many pre-existing warnings from drowning the real errors or flooding the context window.
|
||||
fn format_diagnostics(path: &str, diagnostics: &[crate::lsp::Diagnostic]) -> String {
|
||||
render_diagnostics(path, diagnostics, "total")
|
||||
}
|
||||
|
||||
/// [`format_diagnostics`], with what the count counts: `total`, or `new` for a delta.
|
||||
fn render_diagnostics(path: &str, diagnostics: &[crate::lsp::Diagnostic], counted: &str) -> String {
|
||||
let mut sorted: Vec<&crate::lsp::Diagnostic> = diagnostics.iter().collect();
|
||||
sorted.sort_by_key(|d| (d.severity.is_none(), d.severity, d.line, d.character));
|
||||
let errors = sorted.iter().filter(|d| d.severity == Some(crate::lsp::Severity::Error)).count();
|
||||
let mut message = format!(
|
||||
"Diagnostics after editing {path} ({} {counted}, {errors} error(s)) — fix errors before continuing:\n",
|
||||
diagnostics.len()
|
||||
);
|
||||
for diag in sorted.iter().take(MAX_INJECTED_DIAGNOSTICS) {
|
||||
message.push_str(&format!(
|
||||
"- {} {}:{}: {}\n",
|
||||
diag.severity.map_or("note", crate::lsp::Severity::label),
|
||||
diag.line + 1,
|
||||
diag.character + 1,
|
||||
diag.message
|
||||
));
|
||||
}
|
||||
if sorted.len() > MAX_INJECTED_DIAGNOSTICS {
|
||||
message.push_str(&format!(
|
||||
"… and {} more (run `lsp_diagnostics` on {path} for the full list)\n",
|
||||
sorted.len() - MAX_INJECTED_DIAGNOSTICS
|
||||
));
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
158
crates/luxe-core/src/hooks/file_changed/standards.rs
Normal file
158
crates/luxe-core/src/hooks/file_changed/standards.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
//! standards — the size limits the system prompt sets, held at the moment an edit crosses one.
|
||||
//!
|
||||
//! The prompt asks for functions of 4–20 lines and files of 500 or less, and a model agrees and
|
||||
//! then writes a 60-line function anyway, because nothing tells it while it can still act. This
|
||||
//! tells it, once, when a change takes a file or a function past a limit. Only crossings count:
|
||||
//! a codebase full of long functions the agent did not write is not news on every edit, the same
|
||||
//! rule the diagnostics after an edit follow. The outline comes from outside `core` (tree-sitter
|
||||
//! lives in `luxe-lsp`), injected like the test-gap advisor.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_FUNCTION_LINES: usize = 20;
|
||||
|
||||
const MAX_FILE_LINES: usize = 500;
|
||||
|
||||
/// Most functions named in one note; the rest are counted.
|
||||
const MAX_NAMED: usize = 5;
|
||||
|
||||
/// Where function boundaries come from: a parser outside `core`.
|
||||
pub trait OutlineSource: Send + Sync {
|
||||
/// The functions and methods in `source`, or `None` for a language it cannot parse.
|
||||
fn functions(&self, path: &Path, source: &str) -> Option<Vec<FunctionSize>>;
|
||||
}
|
||||
|
||||
/// One function's name, qualified by its container where it has one, and its length.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FunctionSize {
|
||||
/// `Class.method`, or a bare name at the top level
|
||||
pub name: String,
|
||||
/// Lines from its first to its last, inclusive
|
||||
pub lines: usize,
|
||||
}
|
||||
|
||||
/// A file's size and its functions past the limit, at one moment.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(super) struct SizeSnapshot {
|
||||
file_lines: usize,
|
||||
long: Vec<FunctionSize>,
|
||||
}
|
||||
|
||||
/// What `source` measures now.
|
||||
pub(super) fn snapshot(outline: &dyn OutlineSource, path: &Path, source: &str) -> SizeSnapshot {
|
||||
let long = outline
|
||||
.functions(path, source)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|function| function.lines > MAX_FUNCTION_LINES)
|
||||
.collect();
|
||||
SizeSnapshot { file_lines: source.lines().count(), long }
|
||||
}
|
||||
|
||||
/// A note naming each limit `after` crosses that `before` had not, or `None` when it crosses none.
|
||||
pub(super) fn crossings(path: &str, before: &SizeSnapshot, after: &SizeSnapshot) -> Option<String> {
|
||||
let mut parts = Vec::new();
|
||||
if after.file_lines > MAX_FILE_LINES && before.file_lines <= MAX_FILE_LINES {
|
||||
parts.push(format!(
|
||||
"{path} is now {} lines, past the {MAX_FILE_LINES}-line standard.",
|
||||
after.file_lines
|
||||
));
|
||||
}
|
||||
let grown: Vec<&FunctionSize> = after
|
||||
.long
|
||||
.iter()
|
||||
.filter(|function| !before.long.iter().any(|old| old.name == function.name))
|
||||
.collect();
|
||||
if !grown.is_empty() {
|
||||
let named: Vec<String> = grown
|
||||
.iter()
|
||||
.take(MAX_NAMED)
|
||||
.map(|function| format!("`{}` ({} lines)", function.name, function.lines))
|
||||
.collect();
|
||||
let more = grown.len().saturating_sub(named.len());
|
||||
let tail = if more > 0 { format!(" and {more} more") } else { String::new() };
|
||||
parts.push(format!(
|
||||
"Past the {MAX_FUNCTION_LINES}-line function standard now: {}{tail}.",
|
||||
named.join(", ")
|
||||
));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.push("Split them unless this project's own conventions say otherwise.".to_string());
|
||||
Some(parts.join(" "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reads `name lines` pairs, one per line, as the outline.
|
||||
struct Listed;
|
||||
|
||||
impl OutlineSource for Listed {
|
||||
fn functions(&self, _path: &Path, source: &str) -> Option<Vec<FunctionSize>> {
|
||||
Some(
|
||||
source
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("fn "))
|
||||
.filter_map(|rest| rest.split_once(' '))
|
||||
.map(|(name, lines)| FunctionSize {
|
||||
name: name.to_string(),
|
||||
lines: lines.parse().unwrap_or(0),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(source: &str) -> SizeSnapshot {
|
||||
snapshot(&Listed, Path::new("x.rs"), source)
|
||||
}
|
||||
|
||||
fn padded(functions: &str, total: usize) -> String {
|
||||
let mut text = functions.to_string();
|
||||
while text.lines().count() < total {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A function that grows past 20 lines is named; one that was already past it is not.
|
||||
#[test]
|
||||
fn a_function_crossing_the_limit_is_named_and_an_old_one_is_not() {
|
||||
let before = measure("fn legacy 80\nfn small 12\n");
|
||||
let after = measure("fn legacy 95\nfn small 21\nfn fresh 30\n");
|
||||
let note = crossings("x.rs", &before, &after).expect("two crossings");
|
||||
assert!(note.contains("`small` (21 lines), `fresh` (30 lines)"), "{note}");
|
||||
assert!(!note.contains("legacy"), "{note}");
|
||||
assert!(note.contains("unless this project's own conventions"), "{note}");
|
||||
}
|
||||
|
||||
/// Exactly at a limit is within it; one past is over.
|
||||
#[test]
|
||||
fn the_limits_are_inclusive() {
|
||||
let at = measure(&padded("fn edge 20", MAX_FILE_LINES));
|
||||
assert_eq!(crossings("x.rs", &SizeSnapshot::default(), &at), None);
|
||||
let over = measure(&padded("fn edge 21", MAX_FILE_LINES + 1));
|
||||
let note = crossings("x.rs", &SizeSnapshot::default(), &over).expect("both crossed");
|
||||
assert!(note.contains("x.rs is now 501 lines"), "{note}");
|
||||
assert!(note.contains("`edge` (21 lines)"), "{note}");
|
||||
}
|
||||
|
||||
/// A file already past 500 lines is not news when it grows again.
|
||||
#[test]
|
||||
fn a_file_already_over_says_nothing_more() {
|
||||
let before = measure(&padded("", 700));
|
||||
let after = measure(&padded("", 720));
|
||||
assert_eq!(crossings("x.rs", &before, &after), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_list_is_counted() {
|
||||
let many: String = (0..8).map(|n| format!("fn f{n} 30\n")).collect();
|
||||
let note = crossings("x.rs", &SizeSnapshot::default(), &measure(&many)).expect("crossed");
|
||||
assert!(note.contains("and 3 more"), "{note}");
|
||||
assert!(!note.contains("`f7`"), "{note}");
|
||||
}
|
||||
}
|
||||
56
crates/luxe-core/src/hooks/file_changed/tests.rs
Normal file
56
crates/luxe-core/src/hooks/file_changed/tests.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use super::*;
|
||||
use crate::lsp::{Diagnostic, Severity};
|
||||
|
||||
fn diag(severity: Severity, line: u32, message: &str) -> Diagnostic {
|
||||
Diagnostic { severity: Some(severity), line, character: 0, message: message.to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_orders_errors_first_and_labels_severity() {
|
||||
let diags = vec![
|
||||
diag(Severity::Warning, 10, "a warning"),
|
||||
diag(Severity::Error, 20, "an error"),
|
||||
diag(Severity::Hint, 5, "a hint"),
|
||||
diag(Severity::Information, 7, "an info"),
|
||||
];
|
||||
let out = format_diagnostics("src/x.rs", &diags);
|
||||
let error_pos = out.find("an error").unwrap();
|
||||
let warn_pos = out.find("a warning").unwrap();
|
||||
let info_pos = out.find("an info").unwrap();
|
||||
let hint_pos = out.find("a hint").unwrap();
|
||||
assert!(
|
||||
error_pos < warn_pos && warn_pos < info_pos && info_pos < hint_pos,
|
||||
"errors first, then warning, info, hint"
|
||||
);
|
||||
assert!(out.contains("info 8:1: an info"), "{out}");
|
||||
assert!(out.contains("error 21:1: an error"));
|
||||
assert!(out.contains("1 error(s)"));
|
||||
}
|
||||
|
||||
/// A server that does not say how serious something is gets a neutral label and the last place.
|
||||
#[test]
|
||||
fn a_diagnostic_with_no_severity_is_a_note_and_sorts_last() {
|
||||
let unranked =
|
||||
Diagnostic { severity: None, line: 0, character: 0, message: "unranked".to_string() };
|
||||
let diags = vec![unranked, diag(Severity::Hint, 5, "a hint")];
|
||||
|
||||
let out = format_diagnostics("src/x.rs", &diags);
|
||||
|
||||
assert!(out.find("a hint").unwrap() < out.find("unranked").unwrap(), "{out}");
|
||||
assert!(out.contains("note 1:1: unranked"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_caps_and_summarizes_overflow() {
|
||||
let diags: Vec<Diagnostic> =
|
||||
(0..30).map(|i| diag(Severity::Warning, i, &format!("w{i}"))).collect();
|
||||
let out = format_diagnostics("src/x.rs", &diags);
|
||||
let shown = out.lines().filter(|l| l.starts_with("- ")).count();
|
||||
assert_eq!(shown, MAX_INJECTED_DIAGNOSTICS, "caps the inline list");
|
||||
assert!(out.contains("and 10 more"), "summarizes the remainder: {out}");
|
||||
}
|
||||
|
||||
mod baseline;
|
||||
mod fetched;
|
||||
mod size;
|
||||
mod test_gap;
|
||||
110
crates/luxe-core/src/hooks/file_changed/tests/baseline.rs
Normal file
110
crates/luxe-core/src/hooks/file_changed/tests/baseline.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
//! Baseline — tests for the file-changed hook.
|
||||
|
||||
use super::*;
|
||||
use crate::lsp::Diagnostic;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Answers each diagnostics request with the next scripted list.
|
||||
struct Scripted(Mutex<VecDeque<Vec<Diagnostic>>>);
|
||||
|
||||
#[async_trait]
|
||||
impl crate::lsp::DiagnosticsProvider for Scripted {
|
||||
async fn run_diagnostics(
|
||||
&self,
|
||||
_path: &std::path::Path,
|
||||
) -> Result<Vec<Diagnostic>, crate::lsp::DiagnosticsError> {
|
||||
Ok(self.0.lock().expect("lock").pop_front().unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
fn diag(line: u32, message: &str) -> Diagnostic {
|
||||
Diagnostic {
|
||||
severity: Some(crate::lsp::Severity::Error),
|
||||
line,
|
||||
character: 0,
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hook(script: Vec<Vec<Diagnostic>>) -> FileChangedHook {
|
||||
let lsp: Arc<dyn crate::lsp::DiagnosticsProvider> =
|
||||
Arc::new(Scripted(Mutex::new(script.into())));
|
||||
FileChangedHook::new(None, Some(lsp))
|
||||
}
|
||||
|
||||
fn cx() -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn change(hook: &FileChangedHook, path: &std::path::Path) -> Option<String> {
|
||||
let event = HookEvent::FileChanged {
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
operation: "edit".to_string(),
|
||||
};
|
||||
match hook.on(HookPoint::FileChanged, &event, &cx()).await {
|
||||
HookOutcome::InjectContext(report) => Some(report),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn about_to(hook: &FileChangedHook, tool: &str, path: &std::path::Path) {
|
||||
let event = HookEvent::ToolUse {
|
||||
tool_name: tool.to_string(),
|
||||
args: serde_json::json!({ "path": path.to_string_lossy() }),
|
||||
};
|
||||
hook.on(HookPoint::BeforeToolUse, &event, &cx()).await;
|
||||
}
|
||||
|
||||
/// What was wrong before the edit stays out of the report, wherever the edit moved it; what
|
||||
/// the edit added is reported, and the rest is counted.
|
||||
#[tokio::test]
|
||||
async fn an_edit_reports_what_it_introduced_and_counts_the_rest() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let file = dir.path().join("views.py");
|
||||
std::fs::write(&file, "x\n").expect("write");
|
||||
let hook = hook(vec![
|
||||
vec![diag(4, "Import \"django\" could not be resolved"), diag(9, "old")],
|
||||
vec![diag(6, "Import \"django\" could not be resolved"), diag(11, "old"), diag(7, "new")],
|
||||
vec![diag(6, "Import \"django\" could not be resolved"), diag(11, "old"), diag(7, "new")],
|
||||
]);
|
||||
|
||||
about_to(&hook, "edit", &file).await;
|
||||
let report = change(&hook, &file).await.expect("the new error is reported");
|
||||
assert!(report.contains("(1 new, 1 error(s))"), "{report}");
|
||||
assert!(report.contains("error 8:1: new"), "{report}");
|
||||
assert!(!report.contains("could not be resolved") && !report.contains(": old"), "{report}");
|
||||
assert!(report.contains("2 more were in the file before this change"), "{report}");
|
||||
|
||||
// The next edit is measured against the last one, so the same error is not news again
|
||||
about_to(&hook, "edit", &file).await;
|
||||
assert_eq!(change(&hook, &file).await, None);
|
||||
}
|
||||
|
||||
/// A file `write` creates had nothing wrong with it, so everything in it is new.
|
||||
#[tokio::test]
|
||||
async fn a_new_file_reports_everything_as_new() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let file = dir.path().join("new.py");
|
||||
let hook = hook(vec![vec![diag(0, "undefined name")]]);
|
||||
|
||||
about_to(&hook, "write", &file).await;
|
||||
std::fs::write(&file, "x\n").expect("write");
|
||||
let report = change(&hook, &file).await.expect("reported");
|
||||
assert!(report.contains("(1 new, 1 error(s))") && !report.contains("more were"), "{report}");
|
||||
}
|
||||
|
||||
/// Without a baseline — no hook saw the call coming — the report is the whole list, as before.
|
||||
#[tokio::test]
|
||||
async fn without_a_baseline_everything_is_reported() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let file = dir.path().join("a.py");
|
||||
std::fs::write(&file, "x\n").expect("write");
|
||||
let hook = hook(vec![vec![diag(0, "old"), diag(1, "older")]]);
|
||||
let report = change(&hook, &file).await.expect("reported");
|
||||
assert!(report.contains("(2 total"), "{report}");
|
||||
}
|
||||
36
crates/luxe-core/src/hooks/file_changed/tests/fetched.rs
Normal file
36
crates/luxe-core/src/hooks/file_changed/tests/fetched.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Fetched — tests for the file-changed hook.
|
||||
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Records every file it was asked about.
|
||||
struct Recording(Arc<Mutex<Vec<PathBuf>>>);
|
||||
|
||||
#[async_trait]
|
||||
impl crate::lsp::DiagnosticsProvider for Recording {
|
||||
async fn run_diagnostics(
|
||||
&self,
|
||||
path: &std::path::Path,
|
||||
) -> Result<Vec<crate::lsp::Diagnostic>, crate::lsp::DiagnosticsError> {
|
||||
self.0.lock().expect("lock").push(path.to_path_buf());
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_edit_inside_a_fetched_repository_is_neither_formatted_nor_checked() {
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let lsp: Arc<dyn crate::lsp::DiagnosticsProvider> = Arc::new(Recording(seen.clone()));
|
||||
let hook = FileChangedHook::new(None, Some(lsp));
|
||||
let cx = HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
};
|
||||
for path in ["/p/.luxe/gh-cache/o/r/build.rs", "/p/src/lib.rs"] {
|
||||
let event =
|
||||
HookEvent::FileChanged { path: path.to_string(), operation: "edit".to_string() };
|
||||
hook.on(HookPoint::FileChanged, &event, &cx).await;
|
||||
}
|
||||
assert_eq!(*seen.lock().expect("lock"), vec![PathBuf::from("/p/src/lib.rs")]);
|
||||
}
|
||||
67
crates/luxe-core/src/hooks/file_changed/tests/size.rs
Normal file
67
crates/luxe-core/src/hooks/file_changed/tests/size.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! Size — tests for the file-changed hook.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Every line `def name` opens a function running to the next one or the end.
|
||||
struct Defs;
|
||||
|
||||
impl OutlineSource for Defs {
|
||||
fn functions(&self, _path: &std::path::Path, source: &str) -> Option<Vec<FunctionSize>> {
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
let starts: Vec<usize> =
|
||||
(0..lines.len()).filter(|i| lines[*i].starts_with("def ")).collect();
|
||||
Some(
|
||||
starts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(n, start)| FunctionSize {
|
||||
name: lines[*start][4..].to_string(),
|
||||
lines: starts.get(n + 1).unwrap_or(&lines.len()) - start,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn cx() -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn body(name: &str, lines: usize) -> String {
|
||||
format!("def {name}\n{}", " pass\n".repeat(lines - 1))
|
||||
}
|
||||
|
||||
/// The edit that pushes a function past 20 lines hears about it, alongside nothing else; the
|
||||
/// next edit to the same file, crossing nothing new, hears nothing.
|
||||
#[tokio::test]
|
||||
async fn an_edit_that_crosses_a_limit_is_told_once() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let file = dir.path().join("views.py");
|
||||
std::fs::write(&file, body("short", 10)).expect("write");
|
||||
let hook = FileChangedHook::new(None, None).with_outline(Arc::new(Defs));
|
||||
let path = file.to_string_lossy().into_owned();
|
||||
let about_to = HookEvent::ToolUse {
|
||||
tool_name: "edit".to_string(),
|
||||
args: serde_json::json!({ "path": path }),
|
||||
};
|
||||
let changed = HookEvent::FileChanged { path: path.clone(), operation: "edit".to_string() };
|
||||
|
||||
hook.on(HookPoint::BeforeToolUse, &about_to, &cx()).await;
|
||||
std::fs::write(&file, body("short", 30)).expect("write");
|
||||
let HookOutcome::InjectContext(note) = hook.on(HookPoint::FileChanged, &changed, &cx()).await
|
||||
else {
|
||||
panic!("the crossing is reported");
|
||||
};
|
||||
assert!(note.contains("`short` (30 lines)"), "{note}");
|
||||
|
||||
hook.on(HookPoint::BeforeToolUse, &about_to, &cx()).await;
|
||||
std::fs::write(&file, body("short", 35)).expect("write");
|
||||
assert!(matches!(
|
||||
hook.on(HookPoint::FileChanged, &changed, &cx()).await,
|
||||
HookOutcome::Continue
|
||||
));
|
||||
}
|
||||
30
crates/luxe-core/src/hooks/file_changed/tests/test_gap.rs
Normal file
30
crates/luxe-core/src/hooks/file_changed/tests/test_gap.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
//! Test gap — tests for the file-changed hook.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The advisory names the symbols, bounds the list, and leaves the decision to the agent.
|
||||
#[test]
|
||||
fn a_test_gap_reads_as_a_fact_with_a_choice() {
|
||||
let note = format_test_gaps("src/auth.rs", &["src/auth.rs::logout".to_string()])
|
||||
.expect("a gap is reported");
|
||||
|
||||
assert!(note.starts_with("src/auth.rs: no covering test for logout"));
|
||||
assert!(note.contains("Add one, or say why"), "the agent decides: {note}");
|
||||
// The reviewer will be told the same thing, which is why saying so here is honest.
|
||||
assert!(note.contains("a reviewer will be told the same thing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_gap_list_is_counted_rather_than_pasted() {
|
||||
let symbols: Vec<String> = (0..9).map(|index| format!("src/lib.rs::symbol_{index}")).collect();
|
||||
|
||||
let note = format_test_gaps("src/lib.rs", &symbols).expect("a gap is reported");
|
||||
|
||||
assert!(note.contains("(+4 more)"), "the tail is counted: {note}");
|
||||
assert!(!note.contains("symbol_8"), "beyond the cap nothing is named: {note}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fully_covered_edit_says_nothing() {
|
||||
assert!(format_test_gaps("src/auth.rs", &[]).is_none());
|
||||
}
|
||||
216
crates/luxe-core/src/hooks/fresh.rs
Normal file
216
crates/luxe-core/src/hooks/fresh.rs
Normal file
@@ -0,0 +1,216 @@
|
||||
//! Fresh hook — re-anchors a loop session from the repository's own memory.
|
||||
//!
|
||||
//! A continuous loop outlives its sessions: it restarts, compacts, and picks the work back up with
|
||||
//! a fresh context window. The task store carries what one *session* knew; the loop's journal is
|
||||
//! what carries across runs, and without it the loop opens every session with a generic steer and
|
||||
//! no idea what the last one did.
|
||||
//!
|
||||
//! Fires once per process on `BeforeAgentStart` and returns [`HookOutcome::InjectContext`], so the
|
||||
//! anchor is appended to the system prompt rather than submitted as a turn. That is the same
|
||||
//! treatment one-time context already gets everywhere else: appended, never prepended, so the
|
||||
//! cached prefix above it survives.
|
||||
//!
|
||||
//! # Bounded, and honest about it
|
||||
//!
|
||||
//! The journal is append-only and the spec grows without limit, to hundreds of kilobytes. Reading
|
||||
//! either whole is not a briefing, it is the context window. So the journal contributes its
|
||||
//! **tail** (recent entries are the ones that carry), the plan contributes a bounded head, and the
|
||||
//! spec contributes a *pointer*, because an agent with `read` does not need to be handed a document
|
||||
//! it can open.
|
||||
//!
|
||||
//! When there is nothing to anchor from, the hook says nothing. Announcing a re-anchor that loaded
|
||||
//! no memory is worse than silence: it tells the model it has been briefed.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use async_trait::async_trait;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Characters of the journal's tail to carry.
|
||||
const MAX_JOURNAL_CHARS: usize = 4_000;
|
||||
/// Characters of the current plan to carry.
|
||||
const MAX_PLAN_CHARS: usize = 4_000;
|
||||
|
||||
/// Re-anchors a fresh loop session from the repository's durable files.
|
||||
pub struct FreshHook {
|
||||
/// Repository root — where the journal, the plan and the spec live.
|
||||
repo_root: PathBuf,
|
||||
/// Whether the anchor has already been delivered this process.
|
||||
delivered: AtomicBool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FreshHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("FreshHook").field("repo_root", &self.repo_root).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl FreshHook {
|
||||
/// Create a new fresh hook rooted at `repo_root`.
|
||||
pub fn new(repo_root: PathBuf) -> Self {
|
||||
Self { repo_root, delivered: AtomicBool::new(false) }
|
||||
}
|
||||
|
||||
/// Read a file under the repository root, or `None` when it is absent or empty.
|
||||
async fn read(&self, relative: impl AsRef<std::path::Path>) -> Option<String> {
|
||||
let path = self.repo_root.join(relative);
|
||||
match tokio::fs::read_to_string(&path).await {
|
||||
Ok(content) if !content.trim().is_empty() => Some(content),
|
||||
Ok(_) => None,
|
||||
Err(error) => {
|
||||
debug!(path = %path.display(), %error, "nothing to read");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor for a fresh session, or `None` when the repository has nothing to say.
|
||||
pub async fn anchor(&self) -> Option<String> {
|
||||
let (journal_path, _) = crate::loop_hooks::journal_paths(&self.repo_root);
|
||||
let journal_relative =
|
||||
journal_path.strip_prefix(&self.repo_root).unwrap_or(&journal_path).to_path_buf();
|
||||
|
||||
let plan = self.read("PLAN.md").await.map(|plan| crate::hooks::head(&plan, MAX_PLAN_CHARS));
|
||||
let journal = self
|
||||
.read(&journal_relative)
|
||||
.await
|
||||
.map(|journal| crate::hooks::tail(&journal, MAX_JOURNAL_CHARS));
|
||||
let has_spec = self.repo_root.join("PROJECT.md").is_file();
|
||||
|
||||
if plan.is_none() && journal.is_none() {
|
||||
debug!("no plan and no journal, so nothing to anchor from");
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut out = String::from(
|
||||
"## Picking up where the loop left off\n\nThis session starts with a fresh context \
|
||||
window. What the repository remembers:",
|
||||
);
|
||||
if let Some(plan) = plan {
|
||||
out.push_str(&format!("\n\n### The current slice (`PLAN.md`)\n\n{plan}"));
|
||||
}
|
||||
if let Some(journal) = journal {
|
||||
out.push_str(&format!(
|
||||
"\n\n### Most recent journal entries (`{}`, tail)\n\n{journal}",
|
||||
crate::paths::display(&journal_relative)
|
||||
));
|
||||
}
|
||||
if has_spec {
|
||||
out.push_str(
|
||||
"\n\nThe full spec is in `PROJECT.md`. Read it when you need it rather than \
|
||||
assuming what it says.",
|
||||
);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for FreshHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"fresh"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::BeforeAgentStart]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, _ev: &HookEvent, _cx: &HookCtx) -> HookOutcome {
|
||||
// Once per process: `BeforeAgentStart` fires every turn, and re-anchoring on each one would
|
||||
// rewrite the system prompt's tail with the same text forever.
|
||||
if self.delivered.swap(true, Ordering::Relaxed) {
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
match self.anchor().await {
|
||||
Some(anchor) => {
|
||||
info!(chars = anchor.chars().count(), "anchoring from repo memory");
|
||||
HookOutcome::InjectContext(anchor)
|
||||
}
|
||||
None => HookOutcome::Continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn ctx() -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fire(hook: &FreshHook) -> HookOutcome {
|
||||
hook.on(HookPoint::BeforeAgentStart, &HookEvent::Other(serde_json::json!({})), &ctx()).await
|
||||
}
|
||||
|
||||
/// A repository with nothing to say gets to say nothing. Announcing a re-anchor that loaded no
|
||||
/// memory tells the model it has been briefed when it has not.
|
||||
#[tokio::test]
|
||||
async fn an_empty_repository_produces_no_anchor() {
|
||||
let dir = tempdir().unwrap();
|
||||
let hook = FreshHook::new(dir.path().to_path_buf());
|
||||
assert!(hook.anchor().await.is_none());
|
||||
assert!(matches!(fire(&hook).await, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_plan_and_the_journal_tail_are_carried_and_the_spec_is_pointed_at() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join(".luxe").join("loop")).unwrap();
|
||||
std::fs::write(root.join("PLAN.md"), "# Slice\n\nFix the thing.").unwrap();
|
||||
std::fs::write(
|
||||
root.join(".luxe").join("loop").join("PROGRESS.md"),
|
||||
"- old entry\n- newest entry\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("PROJECT.md"), "the whole spec").unwrap();
|
||||
|
||||
let anchor = FreshHook::new(root.to_path_buf()).anchor().await.expect("an anchor");
|
||||
|
||||
assert!(anchor.contains("Fix the thing"), "the plan rides along: {anchor}");
|
||||
assert!(anchor.contains("newest entry"), "so does the journal: {anchor}");
|
||||
assert!(anchor.contains("PROJECT.md"), "and the spec is named: {anchor}");
|
||||
assert!(
|
||||
!anchor.contains("the whole spec"),
|
||||
"...but not injected — the agent can open it: {anchor}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The failure this hook shipped with: a 372 KB journal read whole is not a briefing.
|
||||
#[tokio::test]
|
||||
async fn a_huge_journal_contributes_only_its_tail() {
|
||||
let dir = tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join(".luxe").join("loop")).unwrap();
|
||||
let journal = format!(
|
||||
"{}\nLAST LINE OF THE JOURNAL\n",
|
||||
"an old entry that scrolled away\n".repeat(20_000)
|
||||
);
|
||||
std::fs::write(root.join(".luxe").join("loop").join("PROGRESS.md"), &journal).unwrap();
|
||||
|
||||
let anchor = FreshHook::new(root.to_path_buf()).anchor().await.expect("an anchor");
|
||||
|
||||
assert!(anchor.chars().count() < MAX_JOURNAL_CHARS + 600, "bounded: {}", anchor.len());
|
||||
assert!(anchor.contains("LAST LINE OF THE JOURNAL"), "and it kept the recent end");
|
||||
assert!(anchor.contains("earlier entries omitted"), "and said so");
|
||||
}
|
||||
|
||||
/// `BeforeAgentStart` fires every turn; the anchor is a one-time briefing.
|
||||
#[tokio::test]
|
||||
async fn the_anchor_is_delivered_once() {
|
||||
let dir = tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("PLAN.md"), "# Slice").unwrap();
|
||||
let hook = FreshHook::new(dir.path().to_path_buf());
|
||||
|
||||
assert!(matches!(fire(&hook).await, HookOutcome::InjectContext(_)));
|
||||
assert!(matches!(fire(&hook).await, HookOutcome::Continue), "not again");
|
||||
assert!(matches!(fire(&hook).await, HookOutcome::Continue));
|
||||
}
|
||||
}
|
||||
336
crates/luxe-core/src/hooks/herdr.rs
Normal file
336
crates/luxe-core/src/hooks/herdr.rs
Normal file
@@ -0,0 +1,336 @@
|
||||
//! Herdr integration — report agent lifecycle state to the enclosing Herdr pane.
|
||||
//!
|
||||
//! [Herdr](https://herdr.dev) is a terminal multiplexer for coding agents: a sidebar rolls up
|
||||
//! each agent's state (`working`/`blocked`/`idle`/`done`) across every pane so a human can see,
|
||||
//! at a glance, which agent is running, which needs a decision, and which is ready to review.
|
||||
//!
|
||||
//! Herdr recognizes most agents by *process detection* + screen scraping, which requires a Herdr
|
||||
//! binary update per new agent. Instead Luxe acts as a **custom socket integration** (Herdr's
|
||||
//! supported extension path): when Luxe runs inside a Herdr pane (`HERDR_ENV=1`), this hook reports
|
||||
//! Luxe's own lifecycle to Herdr via the `herdr pane report-agent` CLI. That makes Luxe a
|
||||
//! first-class, correctly-tracked agent in the sidebar without Herdr needing to know the `luxe`
|
||||
//! process at all.
|
||||
//!
|
||||
//! It's deliberately **best-effort and side-effect-only** (no telemetry, offline-safe,
|
||||
//! never block loop work): reports are fire-and-forget, failures (Herdr absent, CLI error) are
|
||||
//! swallowed, the hook always returns [`HookOutcome::Continue`], and it self-disables outside a
|
||||
//! Herdr pane. Opt out entirely with `LUXE_HERDR=0`.
|
||||
//!
|
||||
//! Lifecycle mapping (`Action → … → Event`, observed at hook points):
|
||||
//! `SessionStart → idle`, `AgentStart → working`, `AgentEnd → idle`; the two ways a turn waits on a
|
||||
//! human both flip to `blocked` — an interactive permission prompt (`PermissionRequested` /
|
||||
//! `PermissionResolved`) and the `question` tool (`BeforeToolUse` / `AfterToolUse`); and
|
||||
//! `SessionEnd → release`.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use async_trait::async_trait;
|
||||
use std::process::Stdio;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The tool whose invocation means "the agent is waiting on a human answer".
|
||||
const BLOCKING_TOOL: &str = "question";
|
||||
|
||||
/// Semantic agent state Herdr understands. Maps 1:1 to `herdr pane report-agent --state`.
|
||||
///
|
||||
/// Note there is no `done`: Herdr *derives* `done` from an `idle` report that lands while the
|
||||
/// pane is unseen, so an integration only ever reports these three.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum HerdrState {
|
||||
/// A turn is in flight (calling the provider / running tools).
|
||||
Working,
|
||||
/// Waiting on a required human decision (e.g. the `question` tool).
|
||||
Blocked,
|
||||
/// At the prompt, turn complete — nothing in flight.
|
||||
Idle,
|
||||
}
|
||||
|
||||
impl HerdrState {
|
||||
/// The `--state` token Herdr expects.
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Working => "working",
|
||||
Self::Blocked => "blocked",
|
||||
Self::Idle => "idle",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sink for state reports. A trait so the hook is testable headless: the real impl shells out to
|
||||
/// `herdr`; tests record calls in memory.
|
||||
pub trait HerdrReporter: Send + Sync {
|
||||
/// Report the current semantic state to Herdr.
|
||||
fn report(&self, state: HerdrState);
|
||||
/// Relinquish this source's authority over the pane's agent state (on session end).
|
||||
fn release(&self);
|
||||
}
|
||||
|
||||
/// The production reporter: spawns `herdr pane report-agent` for the current pane.
|
||||
///
|
||||
/// Each report runs in a detached thread that reaps its child, so a report never blocks a turn and
|
||||
/// never leaks a zombie. Because those threads can finish out of order, every report carries a
|
||||
/// monotonically increasing `--seq` so Herdr orders them correctly regardless of completion order.
|
||||
pub struct CliHerdrReporter {
|
||||
/// Public pane id Herdr injected as `$HERDR_PANE_ID` (e.g. `w1:p1`).
|
||||
pane_id: String,
|
||||
/// Source identity that owns these reports (`--source`).
|
||||
source: String,
|
||||
/// Agent label shown in the sidebar (`--agent`).
|
||||
agent: String,
|
||||
/// Monotonic sequence so out-of-order subprocess completion can't reorder state.
|
||||
seq: AtomicU64,
|
||||
}
|
||||
|
||||
impl CliHerdrReporter {
|
||||
/// Build a reporter targeting `pane_id`, reporting as source/agent `luxe`.
|
||||
pub fn new(pane_id: String) -> Self {
|
||||
Self {
|
||||
pane_id,
|
||||
source: "luxe".to_string(),
|
||||
agent: "luxe".to_string(),
|
||||
seq: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn a detached `herdr pane <args…>` invocation, silencing its stdio so it can't corrupt
|
||||
/// the TUI. Errors (Herdr missing, non-zero exit) are intentionally ignored.
|
||||
fn spawn(&self, extra: &[&str]) {
|
||||
let seq = self.seq.fetch_add(1, Ordering::Relaxed).to_string();
|
||||
let mut args: Vec<String> = vec!["pane".to_string()];
|
||||
args.extend(extra.iter().map(|s| s.to_string()));
|
||||
args.extend(["--seq".to_string(), seq]);
|
||||
std::thread::spawn(move || {
|
||||
let _ = std::process::Command::new("herdr")
|
||||
.args(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl HerdrReporter for CliHerdrReporter {
|
||||
fn report(&self, state: HerdrState) {
|
||||
self.spawn(&[
|
||||
"report-agent",
|
||||
&self.pane_id,
|
||||
"--source",
|
||||
&self.source,
|
||||
"--agent",
|
||||
&self.agent,
|
||||
"--state",
|
||||
state.as_str(),
|
||||
]);
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.spawn(&[
|
||||
"release-agent",
|
||||
&self.pane_id,
|
||||
"--source",
|
||||
&self.source,
|
||||
"--agent",
|
||||
&self.agent,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports Luxe's lifecycle to Herdr. Registered only when running inside a Herdr pane.
|
||||
pub struct HerdrHook {
|
||||
reporter: Box<dyn HerdrReporter>,
|
||||
/// Last state sent, to suppress redundant reports (a turn fires `AgentStart` many times).
|
||||
last: Mutex<Option<HerdrState>>,
|
||||
}
|
||||
|
||||
impl HerdrHook {
|
||||
/// Auto-detect the Herdr environment and build the hook, or `None` when not applicable.
|
||||
///
|
||||
/// Requires `HERDR_ENV=1` and a non-empty `HERDR_PANE_ID` (both injected into every managed
|
||||
/// pane). Honors the `LUXE_HERDR=0`/`false`/`no`/`off` opt-out.
|
||||
pub fn detect() -> Option<Self> {
|
||||
if env_opted_out("LUXE_HERDR") {
|
||||
return None;
|
||||
}
|
||||
if std::env::var("HERDR_ENV").ok().as_deref() != Some("1") {
|
||||
return None;
|
||||
}
|
||||
let pane_id = std::env::var("HERDR_PANE_ID").ok().filter(|s| !s.trim().is_empty())?;
|
||||
Some(Self::with_reporter(Box::new(CliHerdrReporter::new(pane_id))))
|
||||
}
|
||||
|
||||
/// Build a hook over an explicit reporter (used by tests).
|
||||
pub fn with_reporter(reporter: Box<dyn HerdrReporter>) -> Self {
|
||||
Self { reporter, last: Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// Report `state`, skipping the CLI round-trip when it hasn't changed.
|
||||
fn set_state(&self, state: HerdrState) {
|
||||
let mut last = self.last.lock().expect("herdr last-state lock poisoned");
|
||||
if *last == Some(state) {
|
||||
return;
|
||||
}
|
||||
*last = Some(state);
|
||||
self.reporter.report(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for HerdrHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"herdr"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[
|
||||
HookPoint::SessionStart,
|
||||
HookPoint::SessionEnd,
|
||||
HookPoint::AgentStart,
|
||||
HookPoint::AgentEnd,
|
||||
HookPoint::BeforeToolUse,
|
||||
HookPoint::AfterToolUse,
|
||||
HookPoint::PermissionRequested,
|
||||
HookPoint::PermissionResolved,
|
||||
]
|
||||
}
|
||||
|
||||
async fn on(&self, point: HookPoint, ev: &HookEvent, _cx: &HookCtx) -> HookOutcome {
|
||||
// The `question` tool is the one built-in that suspends the turn waiting on a human, so it
|
||||
// (and only it) toggles blocked; every other tool keeps the turn in `working`.
|
||||
let is_question = matches!(ev, HookEvent::ToolUse { tool_name, .. } if tool_name == BLOCKING_TOOL)
|
||||
|| matches!(ev, HookEvent::ToolResult { tool_name, .. } if tool_name == BLOCKING_TOOL);
|
||||
|
||||
let state = match point {
|
||||
HookPoint::SessionStart | HookPoint::AgentEnd => HerdrState::Idle,
|
||||
HookPoint::AgentStart | HookPoint::PermissionResolved => HerdrState::Working,
|
||||
// An interactive permission prompt, or the `question` tool, blocks on a human.
|
||||
HookPoint::PermissionRequested => HerdrState::Blocked,
|
||||
HookPoint::BeforeToolUse if is_question => HerdrState::Blocked,
|
||||
HookPoint::AfterToolUse if is_question => HerdrState::Working,
|
||||
HookPoint::SessionEnd => {
|
||||
*self.last.lock().expect("herdr last-state lock poisoned") = None;
|
||||
self.reporter.release();
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
_ => return HookOutcome::Continue, // non-blocking tool use: no state change
|
||||
};
|
||||
self.set_state(state);
|
||||
HookOutcome::Continue
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an env var is explicitly set to a falsy value (`0`/`false`/`no`/`off`).
|
||||
fn env_opted_out(key: &str) -> bool {
|
||||
std::env::var(key)
|
||||
.map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Records every report/release so a test can assert the exact transition sequence.
|
||||
#[derive(Default)]
|
||||
struct MockReporter {
|
||||
events: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl HerdrReporter for MockReporter {
|
||||
fn report(&self, state: HerdrState) {
|
||||
self.events.lock().unwrap().push(state.as_str().to_string());
|
||||
}
|
||||
fn release(&self) {
|
||||
self.events.lock().unwrap().push("release".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// A reporter wrapper so the hook and the test can share one recording sink.
|
||||
struct SharedReporter(Arc<MockReporter>);
|
||||
impl HerdrReporter for SharedReporter {
|
||||
fn report(&self, state: HerdrState) {
|
||||
self.0.report(state);
|
||||
}
|
||||
fn release(&self) {
|
||||
self.0.release();
|
||||
}
|
||||
}
|
||||
|
||||
fn ctx() -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: "s".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn other() -> HookEvent {
|
||||
HookEvent::Other(serde_json::Value::Null)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn maps_lifecycle_points_to_states() {
|
||||
let sink = Arc::new(MockReporter::default());
|
||||
let hook = HerdrHook::with_reporter(Box::new(SharedReporter(sink.clone())));
|
||||
let cx = ctx();
|
||||
|
||||
hook.on(HookPoint::SessionStart, &other(), &cx).await;
|
||||
hook.on(HookPoint::AgentStart, &other(), &cx).await;
|
||||
// A non-question tool must NOT move state off `working`.
|
||||
let read = HookEvent::ToolUse { tool_name: "read".into(), args: serde_json::json!({}) };
|
||||
hook.on(HookPoint::BeforeToolUse, &read, &cx).await;
|
||||
// The question tool blocks, then resumes.
|
||||
let q = HookEvent::ToolUse { tool_name: "question".into(), args: serde_json::json!({}) };
|
||||
hook.on(HookPoint::BeforeToolUse, &q, &cx).await;
|
||||
let qr = HookEvent::ToolResult {
|
||||
tool_name: "question".into(),
|
||||
result: "ok".into(),
|
||||
is_error: false,
|
||||
};
|
||||
hook.on(HookPoint::AfterToolUse, &qr, &cx).await;
|
||||
hook.on(HookPoint::AgentEnd, &other(), &cx).await;
|
||||
hook.on(HookPoint::SessionEnd, &other(), &cx).await;
|
||||
|
||||
let events = sink.events.lock().unwrap().clone();
|
||||
assert_eq!(events, vec!["idle", "working", "blocked", "working", "idle", "release"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn permission_prompt_toggles_blocked_then_working() {
|
||||
let sink = Arc::new(MockReporter::default());
|
||||
let hook = HerdrHook::with_reporter(Box::new(SharedReporter(sink.clone())));
|
||||
let cx = ctx();
|
||||
|
||||
// Mid-turn a tool needs approval: blocked while the prompt is up, working once resolved.
|
||||
// The hook keys off the point, not the payload, so a bare event is fine here.
|
||||
hook.on(HookPoint::AgentStart, &other(), &cx).await;
|
||||
hook.on(HookPoint::PermissionRequested, &other(), &cx).await;
|
||||
hook.on(HookPoint::PermissionResolved, &other(), &cx).await;
|
||||
hook.on(HookPoint::AgentEnd, &other(), &cx).await;
|
||||
|
||||
assert_eq!(*sink.events.lock().unwrap(), vec!["working", "blocked", "working", "idle"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dedupes_repeated_states() {
|
||||
let sink = Arc::new(MockReporter::default());
|
||||
let hook = HerdrHook::with_reporter(Box::new(SharedReporter(sink.clone())));
|
||||
let cx = ctx();
|
||||
|
||||
// AgentStart fires once per provider call within a turn; only the first should report.
|
||||
hook.on(HookPoint::AgentStart, &other(), &cx).await;
|
||||
hook.on(HookPoint::AgentStart, &other(), &cx).await;
|
||||
hook.on(HookPoint::AgentStart, &other(), &cx).await;
|
||||
|
||||
assert_eq!(*sink.events.lock().unwrap(), vec!["working"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn always_continues() {
|
||||
let sink = Arc::new(MockReporter::default());
|
||||
let hook = HerdrHook::with_reporter(Box::new(SharedReporter(sink)));
|
||||
let outcome = hook.on(HookPoint::AgentStart, &other(), &ctx()).await;
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
}
|
||||
157
crates/luxe-core/src/hooks/journal_bounding.rs
Normal file
157
crates/luxe-core/src/hooks/journal_bounding.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
//! Journal bounding hook — moves the loop journal's entries to an archive past a size cap.
|
||||
//!
|
||||
//! Keeps the journal small enough to be read whole by bounding it, and keeps what it displaced by
|
||||
//! **appending** to the archive. The first version renamed the journal over the archive, so every
|
||||
//! archive destroyed the one before it and only the most recent survived — for a file whose whole
|
||||
//! job is to be the loop's durable memory.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use async_trait::async_trait;
|
||||
use std::path::PathBuf;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// Default maximum journal size in KB before archiving.
|
||||
const DEFAULT_JOURNAL_MAX_KB: u64 = 24;
|
||||
|
||||
/// A hook that auto-archives PROGRESS.md when it exceeds the size cap.
|
||||
///
|
||||
/// Fires on `HookPoint::AgentEnd`. If the journal exceeds `journal_max_kb`, moves it to
|
||||
/// `PROGRESS.archive.md`, keeping its newest section and a pointer to the archive.
|
||||
pub struct JournalBoundingHook {
|
||||
/// Path to the journal file (`.luxe/loop/PROGRESS.md`; see `loop_hooks::journal_paths`).
|
||||
journal_path: PathBuf,
|
||||
/// Path to the archive file (`.luxe/loop/PROGRESS.archive.md`).
|
||||
archive_path: PathBuf,
|
||||
/// Maximum journal size in KB before archiving.
|
||||
max_kb: u64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for JournalBoundingHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("JournalBoundingHook").field("max_kb", &self.max_kb).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl JournalBoundingHook {
|
||||
/// Create a new journal bounding hook.
|
||||
pub fn new(journal_path: PathBuf, archive_path: PathBuf, max_kb: u64) -> Self {
|
||||
Self { journal_path, archive_path, max_kb }
|
||||
}
|
||||
|
||||
/// Create with default max size (24 KB).
|
||||
pub fn with_defaults(journal_path: PathBuf, archive_path: PathBuf) -> Self {
|
||||
Self::new(journal_path, archive_path, DEFAULT_JOURNAL_MAX_KB)
|
||||
}
|
||||
|
||||
/// Check if the journal exceeds the size cap.
|
||||
async fn should_archive(&self) -> bool {
|
||||
match tokio::fs::metadata(&self.journal_path).await {
|
||||
Ok(metadata) => metadata.len() / 1024 >= self.max_kb,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the journal's older entries to the archive, keeping the newest section in place.
|
||||
///
|
||||
/// Append rather than replace: the archive is the older half of one continuous record, so a
|
||||
/// rename over it throws away everything before the last cap crossing.
|
||||
/// Both files are opened, read and written through `tokio::fs`, because this runs on the
|
||||
/// runtime's thread at the end of every turn. The files are small enough that the blocking
|
||||
/// version never showed up, which is exactly the kind of stall that is discovered later, on a
|
||||
/// slower disk, as a loop that pauses between iterations for no visible reason.
|
||||
async fn archive_journal(&self) -> std::io::Result<()> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
debug!(
|
||||
journal = ?self.journal_path,
|
||||
archive = ?self.archive_path,
|
||||
"archiving journal"
|
||||
);
|
||||
let journal = tokio::fs::read_to_string(&self.journal_path).await?;
|
||||
let archive_name = self.archive_path.file_name().unwrap_or_default().to_string_lossy();
|
||||
let (entries, kept) = split_for_archive(&journal, &archive_name);
|
||||
let mut archive = tokio::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.archive_path)
|
||||
.await?;
|
||||
// A separator, so two runs' entries do not fuse into one unreadable line.
|
||||
if archive.metadata().await.map(|meta| meta.len() > 0).unwrap_or(false) {
|
||||
archive.write_all(b"\n").await?;
|
||||
}
|
||||
archive.write_all(entries.as_bytes()).await?;
|
||||
archive.sync_all().await?;
|
||||
// Rewritten rather than removed: the loop appends to this path without re-creating it
|
||||
tokio::fs::write(&self.journal_path, kept).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits a journal into what moves to the archive and what stays: the preamble, a line pointing
|
||||
/// at the archive, and the newest `## ` section.
|
||||
///
|
||||
/// An empty journal after archiving told the next turn nothing — not where the history went, and
|
||||
/// not what the run had just done. A journal with no sections moves whole.
|
||||
fn split_for_archive(journal: &str, archive_name: &str) -> (String, String) {
|
||||
let starts: Vec<usize> = journal
|
||||
.match_indices("## ")
|
||||
.map(|(at, _)| at)
|
||||
.filter(|&at| at == 0 || journal[..at].ends_with('\n'))
|
||||
.collect();
|
||||
let Some(&first) = starts.first() else {
|
||||
return (journal.to_string(), pointer_header("", archive_name));
|
||||
};
|
||||
let newest = starts[starts.len() - 1];
|
||||
let header = pointer_header(&journal[..first], archive_name);
|
||||
match starts.len() {
|
||||
1 => (journal[first..].to_string(), header),
|
||||
_ => (journal[first..newest].to_string(), header + &journal[newest..]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `preamble`, or a title when there is none, with a line naming the archive unless it already
|
||||
/// does.
|
||||
fn pointer_header(preamble: &str, archive_name: &str) -> String {
|
||||
let preamble = match preamble.trim() {
|
||||
"" => "# Loop journal",
|
||||
text => text,
|
||||
};
|
||||
match preamble.contains(archive_name) {
|
||||
true => format!("{preamble}\n\n"),
|
||||
false => {
|
||||
format!("{preamble}\n\nEarlier entries are in `{archive_name}` beside this file.\n\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for JournalBoundingHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"journal-bounding"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::AgentEnd]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, _ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
if self.should_archive().await {
|
||||
info!(
|
||||
journal = ?self.journal_path,
|
||||
max_kb = self.max_kb,
|
||||
"archiving the journal at its size cap"
|
||||
);
|
||||
match self.archive_journal().await {
|
||||
Ok(()) => cx.notify(format!(
|
||||
"the journal passed {} KB — its entries moved to the archive beside it",
|
||||
self.max_kb
|
||||
)),
|
||||
Err(error) => warn!(%error, "failed to archive journal"),
|
||||
}
|
||||
}
|
||||
HookOutcome::Continue
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
179
crates/luxe-core/src/hooks/journal_bounding/tests.rs
Normal file
179
crates/luxe-core/src/hooks/journal_bounding/tests.rs
Normal file
@@ -0,0 +1,179 @@
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_journal_bounding_hook_not_exceeding() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
|
||||
// Create a small journal.
|
||||
std::fs::write(&journal_path, "Small journal content").unwrap();
|
||||
|
||||
let hook = JournalBoundingHook::with_defaults(journal_path.clone(), archive_path);
|
||||
|
||||
// Should not archive (small journal).
|
||||
assert!(!hook.should_archive().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_journal_bounding_hook_exceeding() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
|
||||
// Create a large journal (30 KB).
|
||||
let large_content = "x".repeat(30 * 1024);
|
||||
std::fs::write(&journal_path, &large_content).unwrap();
|
||||
|
||||
let hook = JournalBoundingHook::with_defaults(journal_path.clone(), archive_path.clone());
|
||||
|
||||
// Should archive (large journal).
|
||||
assert!(hook.should_archive().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_journal_bounding_hook_archive() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
|
||||
// Create a large journal.
|
||||
let large_content = "x".repeat(30 * 1024);
|
||||
std::fs::write(&journal_path, &large_content).unwrap();
|
||||
|
||||
let hook = JournalBoundingHook::with_defaults(journal_path.clone(), archive_path.clone());
|
||||
|
||||
// Archive the journal.
|
||||
hook.archive_journal().await.unwrap();
|
||||
|
||||
// The journal keeps only a pointer to where its entries went
|
||||
let journal_content = std::fs::read_to_string(&journal_path).unwrap();
|
||||
assert!(!journal_content.contains("xxx"), "{journal_content}");
|
||||
assert!(journal_content.contains("PROGRESS.archive.md"), "{journal_content}");
|
||||
|
||||
// Archive should exist with original content.
|
||||
let archive_content = std::fs::read_to_string(&archive_path).unwrap();
|
||||
assert_eq!(archive_content, large_content);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_journal_bounding_hook_on_agent_end() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
|
||||
// Create a large journal.
|
||||
let large_content = "x".repeat(30 * 1024);
|
||||
std::fs::write(&journal_path, &large_content).unwrap();
|
||||
|
||||
let hook = JournalBoundingHook::with_defaults(journal_path.clone(), archive_path.clone());
|
||||
|
||||
// Fire the hook.
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Should return Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
|
||||
// Journal should be archived.
|
||||
let journal_content = std::fs::read_to_string(&journal_path).unwrap();
|
||||
assert!(!journal_content.contains("xxx"), "{journal_content}");
|
||||
assert!(archive_path.exists());
|
||||
}
|
||||
|
||||
/// The bug this replaced: the archive step renamed the journal *over* the archive, so the
|
||||
/// second crossing destroyed everything the first one had saved.
|
||||
#[tokio::test]
|
||||
async fn a_second_archive_keeps_the_first_one() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
let hook = JournalBoundingHook::with_defaults(journal_path.clone(), archive_path.clone());
|
||||
|
||||
std::fs::write(&journal_path, "first run's entries").unwrap();
|
||||
hook.archive_journal().await.unwrap();
|
||||
std::fs::write(&journal_path, "second run's entries").unwrap();
|
||||
hook.archive_journal().await.unwrap();
|
||||
|
||||
let archived = std::fs::read_to_string(&archive_path).unwrap();
|
||||
assert!(archived.contains("first run's entries"), "history was overwritten: {archived:?}");
|
||||
assert!(archived.contains("second run's entries"), "{archived:?}");
|
||||
assert!(
|
||||
archived.find("first") < archived.find("second"),
|
||||
"and it stayed in order: {archived:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An archive that does not exist yet is created rather than being an error.
|
||||
#[tokio::test]
|
||||
async fn the_first_archive_creates_the_file() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
std::fs::write(&journal_path, "entries").unwrap();
|
||||
|
||||
JournalBoundingHook::with_defaults(journal_path, archive_path.clone())
|
||||
.archive_journal()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&archive_path).unwrap(), "entries");
|
||||
}
|
||||
|
||||
/// An archived journal keeps its preamble, a pointer to the archive and its newest section; the
|
||||
/// older sections move, in order.
|
||||
///
|
||||
/// The break this catches: archiving left `PROGRESS.md` empty, so the next turn read a journal
|
||||
/// that said nothing — not where its history went, and not what the run had just done.
|
||||
#[tokio::test]
|
||||
async fn an_archived_journal_keeps_its_pointer_and_newest_section() {
|
||||
let dir = tempdir().unwrap();
|
||||
let journal_path = dir.path().join("PROGRESS.md");
|
||||
let archive_path = dir.path().join("PROGRESS.archive.md");
|
||||
let journal = "# Loop journal\n\nWhat this loop has done.\n\n## Phase 1\n\none\n\n\
|
||||
## Phase 2\n\ntwo with a ## inside\n\n## Phase 3\n\nthree\n";
|
||||
std::fs::write(&journal_path, journal).unwrap();
|
||||
|
||||
JournalBoundingHook::with_defaults(journal_path.clone(), archive_path.clone())
|
||||
.archive_journal()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&journal_path).unwrap(),
|
||||
"# Loop journal\n\nWhat this loop has done.\n\nEarlier entries are in \
|
||||
`PROGRESS.archive.md` beside this file.\n\n## Phase 3\n\nthree\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&archive_path).unwrap(),
|
||||
"## Phase 1\n\none\n\n## Phase 2\n\ntwo with a ## inside\n\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// A preamble that already points at the archive is not given a second pointer.
|
||||
#[test]
|
||||
fn a_pointer_is_added_once() {
|
||||
let journal = "# Journal\n\nOlder ones are in `A.md`.\n\n## One\n\n## Two\n";
|
||||
let (_, kept) = split_for_archive(journal, "A.md");
|
||||
assert_eq!(kept, "# Journal\n\nOlder ones are in `A.md`.\n\n## Two\n");
|
||||
}
|
||||
|
||||
/// A journal of one section moves it whole, or a journal past its cap could never shrink; the
|
||||
/// preamble and the pointer stay.
|
||||
#[test]
|
||||
fn a_single_section_moves_and_the_pointer_stays() {
|
||||
let journal = "# Journal\n\n## Only\n\nall of it\n";
|
||||
let (archived, kept) = split_for_archive(journal, "A.md");
|
||||
assert_eq!(archived, "## Only\n\nall of it\n");
|
||||
assert_eq!(kept, "# Journal\n\nEarlier entries are in `A.md` beside this file.\n\n");
|
||||
}
|
||||
307
crates/luxe-core/src/hooks/plan_reminder.rs
Normal file
307
crates/luxe-core/src/hooks/plan_reminder.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
//! Plan reminder — tells the agent when its checklist has stopped keeping up with its work.
|
||||
//!
|
||||
//! The `todo` tool is the only view a user has of the plan, and it drifts in one direction: a model
|
||||
//! opens a checklist, works, finishes, and never marks anything. The PLAN panel then shows three
|
||||
//! items in progress over a task the agent has already reported as done, which is worse than no
|
||||
//! plan at all — the one surface that promised to say where things stand is the one lying about it.
|
||||
//!
|
||||
//! # Why this is a tool result and not a prompt
|
||||
//!
|
||||
//! A reminder has to reach the model *mid-turn*, and the transcript a request carries is an
|
||||
//! **append** to the last one's: every provider that caches matches an exact prefix, so anything
|
||||
//! that edits history — or the system prompt above it — re-bills the whole conversation at the
|
||||
//! write rate. A tool result is the one place a fact can be added mid-turn that costs nothing,
|
||||
//! because it was going to be appended anyway. So this hook returns
|
||||
//! [`HookOutcome::InjectContext`] at [`HookPoint::AfterToolUse`], which dispatch appends to the
|
||||
//! result of the call that just ran, and it is durable history from that moment on.
|
||||
//!
|
||||
//! # Why it backs off
|
||||
//!
|
||||
//! The note is a fact, not an instruction — the agent decides what it is worth. Which means it may
|
||||
//! decide it is worth nothing, and a reminder that repeats on the same cadence forever after that
|
||||
//! is noise the model has already learned to skip. So an ignored reminder doubles the interval and
|
||||
//! touching the checklist resets it: the first one arrives promptly, and a run that genuinely has
|
||||
//! nothing to update is left alone.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::todo::{TodoStatus, TodoStore};
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::debug;
|
||||
|
||||
/// Tool calls a plan may go unchanged for before the first reminder.
|
||||
///
|
||||
/// Ten is roughly a step's worth of work: a search, a few reads, an edit and its test. Below that
|
||||
/// the reminder fires inside the step it is asking about; well above it, a whole task closes out
|
||||
/// unmarked, which is the thing this exists to catch.
|
||||
const BASE_INTERVAL: u32 = 10;
|
||||
|
||||
/// The longest the interval may grow to after repeated reminders go unheeded.
|
||||
const MAX_INTERVAL: u32 = 80;
|
||||
|
||||
/// Open items named in the note before the rest become a count.
|
||||
const MAX_LISTED: usize = 4;
|
||||
|
||||
/// Whether the reminder is wired in at all. Set `LUXE_PLAN_NUDGE=0` to turn it off.
|
||||
fn enabled() -> bool {
|
||||
std::env::var("LUXE_PLAN_NUDGE").as_deref() != Ok("0")
|
||||
}
|
||||
|
||||
/// How far the checklist has drifted from the work, counted in tool calls.
|
||||
#[derive(Debug)]
|
||||
struct Drift {
|
||||
/// Calls since the checklist was last touched.
|
||||
since: u32,
|
||||
/// Calls the next reminder waits for.
|
||||
interval: u32,
|
||||
}
|
||||
|
||||
impl Default for Drift {
|
||||
fn default() -> Self {
|
||||
Self { since: 0, interval: BASE_INTERVAL }
|
||||
}
|
||||
}
|
||||
|
||||
/// Reminds the agent that its checklist has not moved while its work has.
|
||||
#[derive(Debug)]
|
||||
pub struct PlanReminderHook {
|
||||
store: TodoStore,
|
||||
drift: Mutex<Drift>,
|
||||
}
|
||||
|
||||
impl PlanReminderHook {
|
||||
/// Reminds against the checklists in `store`.
|
||||
pub fn new(store: TodoStore) -> Self {
|
||||
Self { store, drift: Mutex::new(Drift::default()) }
|
||||
}
|
||||
|
||||
/// The note for a session whose plan has fallen behind, or `None` when it has not.
|
||||
///
|
||||
/// Reads the durable checklist rather than any in-memory tally, so it describes the same list
|
||||
/// the panel draws — including one written by an earlier session and resumed into this one.
|
||||
fn note(&self, session_id: &str, since: u32) -> Option<String> {
|
||||
let todos = self.store.read(session_id).ok()?;
|
||||
let open: Vec<_> = todos.iter().filter(|todo| todo.status.is_open()).collect();
|
||||
if open.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut out = format!(
|
||||
"Plan check: {since} tool calls since the checklist last changed, and it still reads:"
|
||||
);
|
||||
for todo in open.iter().take(MAX_LISTED) {
|
||||
let status = match todo.status {
|
||||
TodoStatus::InProgress => "in progress",
|
||||
_ => "pending",
|
||||
};
|
||||
out.push_str(&format!("\n- #{} [{}] {}", todo.id, status, todo.subject));
|
||||
}
|
||||
if open.len() > MAX_LISTED {
|
||||
out.push_str(&format!("\n- … +{} more open", open.len() - MAX_LISTED));
|
||||
}
|
||||
// The consequence, not the instruction, and both readings of it: a model that has been
|
||||
// working one item the whole time is told so in as many words, rather than left to guess
|
||||
// whether the note is about it
|
||||
out.push_str(
|
||||
"\nThat list is the only view the user has of your plan. If you are still working \
|
||||
through these, nothing needs to change; a step you have finished but not marked reads \
|
||||
to the user as work still outstanding.",
|
||||
);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for PlanReminderHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"plan-reminder"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::AfterToolUse]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
let HookEvent::ToolResult { tool_name, .. } = ev else {
|
||||
return HookOutcome::Continue;
|
||||
};
|
||||
if !enabled() {
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
let mut drift = self.drift.lock().await;
|
||||
// Any `todo` call at all, including a plain `list`. Reading the plan is engagement with
|
||||
// it, and a reminder landing on the call after the agent just looked would be answering a
|
||||
// question nobody asked.
|
||||
if tool_name == "todo" {
|
||||
*drift = Drift::default();
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
// Our own request-budget bookkeeping is not a step in anyone's task, so it does not count
|
||||
// as work the plan has fallen behind.
|
||||
if crate::activity::is_bookkeeping(tool_name) {
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
drift.since += 1;
|
||||
if drift.since < drift.interval {
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
let Some(note) = self.note(&cx.session_id, drift.since) else {
|
||||
// Nothing open to fall behind. Start the count again rather than firing the moment a
|
||||
// checklist appears — a plan opened on call eleven has not drifted from anything.
|
||||
drift.since = 0;
|
||||
return HookOutcome::Continue;
|
||||
};
|
||||
debug!(calls = drift.since, "the checklist has not kept up with the work");
|
||||
drift.since = 0;
|
||||
drift.interval = (drift.interval * 2).min(MAX_INTERVAL);
|
||||
HookOutcome::InjectContext(note)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::todo::Todo;
|
||||
|
||||
fn context(session_id: &str) -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: session_id.to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn todo(id: u32, subject: &str, status: TodoStatus) -> Todo {
|
||||
Todo { id, subject: subject.to_string(), status, active_form: None, blocked_by: Vec::new() }
|
||||
}
|
||||
|
||||
fn result(tool_name: &str) -> HookEvent {
|
||||
HookEvent::ToolResult {
|
||||
tool_name: tool_name.to_string(),
|
||||
result: String::new(),
|
||||
is_error: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `tool` `count` times and returns every note the hook produced.
|
||||
async fn run(hook: &PlanReminderHook, tool: &str, count: u32) -> Vec<String> {
|
||||
let mut notes = Vec::new();
|
||||
for _ in 0..count {
|
||||
if let HookOutcome::InjectContext(note) =
|
||||
hook.on(HookPoint::AfterToolUse, &result(tool), &context("session-a")).await
|
||||
{
|
||||
notes.push(note);
|
||||
}
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
fn hook_over(todos: &[Todo]) -> (tempfile::TempDir, PlanReminderHook) {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let store = TodoStore::new(dir.path().to_path_buf());
|
||||
store.write("session-a", todos).expect("a checklist");
|
||||
let hook = PlanReminderHook::new(TodoStore::new(dir.path().to_path_buf()));
|
||||
(dir, hook)
|
||||
}
|
||||
|
||||
/// The plan drifts in one direction: a model opens a checklist, works, finishes, and never
|
||||
/// marks anything. The note has to name what the panel is still showing.
|
||||
#[tokio::test]
|
||||
async fn a_plan_that_stops_keeping_up_is_reported_once_the_work_piles_up() {
|
||||
let (_dir, hook) = hook_over(&[
|
||||
todo(1, "Wire the composing event", TodoStatus::InProgress),
|
||||
todo(2, "Sort the changes tree", TodoStatus::Pending),
|
||||
todo(3, "Run the gate", TodoStatus::Completed),
|
||||
]);
|
||||
|
||||
assert!(run(&hook, "read", BASE_INTERVAL - 1).await.is_empty(), "not before its time");
|
||||
let notes = run(&hook, "read", 1).await;
|
||||
let [note] = notes.as_slice() else { panic!("one reminder, on the tenth call: {notes:?}") };
|
||||
assert!(note.contains("10 tool calls since"), "{note}");
|
||||
assert!(note.contains("#1 [in progress] Wire the composing event"), "{note}");
|
||||
assert!(note.contains("#2 [pending] Sort the changes tree"), "{note}");
|
||||
assert!(!note.contains("Run the gate"), "a finished item is not outstanding work: {note}");
|
||||
assert!(note.contains("still working through these, nothing needs to change"), "{note}");
|
||||
assert!(note.contains("finished but not marked"), "{note}");
|
||||
}
|
||||
|
||||
/// Touching the checklist is the whole point, so it resets everything — the count *and* the
|
||||
/// backoff a previous reminder had earned. Any `todo` call at all counts, including a plain
|
||||
/// `list`: reading the plan is engagement with it.
|
||||
#[tokio::test]
|
||||
async fn touching_the_checklist_starts_the_count_again() {
|
||||
let (_dir, hook) = hook_over(&[todo(1, "Ship it", TodoStatus::InProgress)]);
|
||||
|
||||
assert_eq!(run(&hook, "read", BASE_INTERVAL * 2).await.len(), 1, "one, then it backs off");
|
||||
run(&hook, "todo", 1).await;
|
||||
|
||||
// A clean slate, so the count starts from this call rather than carrying ten with it — and
|
||||
// the next reminder is a full base interval away, not the doubled one it had earned.
|
||||
assert!(run(&hook, "read", BASE_INTERVAL - 1).await.is_empty(), "the count restarted");
|
||||
let notes = run(&hook, "read", 1).await;
|
||||
let [note] = notes.as_slice() else { panic!("the base interval is back: {notes:?}") };
|
||||
assert!(note.contains("10 tool calls since"), "{note}");
|
||||
}
|
||||
|
||||
/// A reminder is a fact the agent may decide is worth nothing. Repeating it on the same cadence
|
||||
/// after that is noise it has already learned to skip.
|
||||
#[tokio::test]
|
||||
async fn a_reminder_nobody_acts_on_gets_rarer_rather_than_louder() {
|
||||
let (_dir, hook) = hook_over(&[todo(1, "Ship it", TodoStatus::Pending)]);
|
||||
|
||||
// Four intervals' worth of work: at a fixed cadence that is four reminders.
|
||||
let notes = run(&hook, "read", BASE_INTERVAL * 4).await;
|
||||
assert_eq!(notes.len(), 2, "10 then 20, not 10-20-30-40: {notes:?}");
|
||||
assert!(notes[1].contains("20 tool calls since"), "and it says how long it has been");
|
||||
}
|
||||
|
||||
/// Nothing to fall behind, nothing to say. A checklist that opens on the eleventh call has not
|
||||
/// drifted from anything, so the count starts again rather than firing at it.
|
||||
#[tokio::test]
|
||||
async fn a_session_with_no_open_plan_is_left_alone() {
|
||||
let (dir, hook) = hook_over(&[todo(1, "Done", TodoStatus::Completed)]);
|
||||
assert!(run(&hook, "read", BASE_INTERVAL * 3).await.is_empty());
|
||||
|
||||
TodoStore::new(dir.path().to_path_buf())
|
||||
.write("session-a", &[todo(2, "New work", TodoStatus::InProgress)])
|
||||
.expect("a checklist");
|
||||
assert!(run(&hook, "read", BASE_INTERVAL - 1).await.is_empty(), "a full interval first");
|
||||
assert_eq!(run(&hook, "read", 1).await.len(), 1);
|
||||
}
|
||||
|
||||
/// Loading a deferred tool's schema is Luxe's own request-budget bookkeeping, not a step in the
|
||||
/// task — so it cannot be the work a plan has fallen behind.
|
||||
#[tokio::test]
|
||||
async fn bookkeeping_calls_are_not_work_the_plan_fell_behind() {
|
||||
let (_dir, hook) = hook_over(&[todo(1, "Ship it", TodoStatus::Pending)]);
|
||||
assert!(run(&hook, crate::tool::ACTIVATE_TOOLS_NAME, BASE_INTERVAL * 2).await.is_empty());
|
||||
assert_eq!(run(&hook, "read", BASE_INTERVAL).await.len(), 1, "real work still counts");
|
||||
}
|
||||
|
||||
/// A long plan is named up to the cap and counted past it; one exactly at the cap is whole.
|
||||
#[test]
|
||||
fn a_long_plan_is_named_then_counted() {
|
||||
let open = |count: u32| -> Vec<Todo> {
|
||||
(1..=count).map(|id| todo(id, &format!("Step {id}"), TodoStatus::Pending)).collect()
|
||||
};
|
||||
let (_dir, hook) = hook_over(&open(MAX_LISTED as u32 + 2));
|
||||
let note = hook.note("session-a", 10).expect("a note");
|
||||
assert!(note.contains("Step 4") && !note.contains("Step 5"), "{note}");
|
||||
assert!(note.contains("… +2 more open"), "{note}");
|
||||
|
||||
let (_dir, hook) = hook_over(&open(MAX_LISTED as u32));
|
||||
let note = hook.note("session-a", 10).expect("a note");
|
||||
assert!(!note.contains("more open"), "{note}");
|
||||
}
|
||||
|
||||
/// A session that never wrote a checklist has no plan to be reminded about, and reading one
|
||||
/// that is not there is not an error.
|
||||
#[tokio::test]
|
||||
async fn a_session_with_no_checklist_at_all_says_nothing() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let hook = PlanReminderHook::new(TodoStore::new(dir.path().to_path_buf()));
|
||||
assert!(run(&hook, "read", BASE_INTERVAL * 2).await.is_empty());
|
||||
}
|
||||
}
|
||||
228
crates/luxe-core/src/hooks/review_gate.rs
Normal file
228
crates/luxe-core/src/hooks/review_gate.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! Built-in hook that runs acceptance tests for review gates.
|
||||
//!
|
||||
//! This hook listens for `ReviewGate` events and runs acceptance commands (e.g.,
|
||||
//! `cargo test`, `cargo clippy`) to verify the recent work. It returns a verdict
|
||||
//! (PASS/FAIL/INVALID) based on the command output.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::review::{ReviewItem, ReviewItemStatus, ReviewVerdict};
|
||||
use async_trait::async_trait;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// Env var set on spawned acceptance-command children so a nested review gate can
|
||||
/// detect it is already running and refuse to recurse. Without this guard, a test
|
||||
/// that fires the review gate with default `cargo test`/`cargo clippy` commands would
|
||||
/// re-spawn the entire suite — an unbounded fork bomb that locks the machine.
|
||||
pub const RECURSION_GUARD_ENV: &str = "LUXE_REVIEW_GATE_ACTIVE";
|
||||
|
||||
/// A hook that runs acceptance tests for review gates.
|
||||
pub struct ReviewGateHook {
|
||||
/// Commands to run for the review gate (e.g., vec!["cargo", "test"]).
|
||||
commands: Vec<Vec<String>>,
|
||||
/// Timeout per acceptance command (default: 10 minutes).
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl ReviewGateHook {
|
||||
/// A gate with no acceptance commands, which passes without spawning anything.
|
||||
///
|
||||
/// Not `["true"]`: that is a real subprocess on every claim to arrive at "yes", and `true` is a
|
||||
/// unix *program* — on Windows the spawn fails, and a gate that cannot spawn its command
|
||||
/// reports FAIL.
|
||||
pub fn new() -> Self {
|
||||
Self { commands: Vec::new(), timeout: Duration::from_secs(600) }
|
||||
}
|
||||
|
||||
/// Create a new `ReviewGateHook` with custom commands.
|
||||
pub fn with_commands(commands: Vec<Vec<String>>) -> Self {
|
||||
Self { commands, timeout: Duration::from_secs(600) }
|
||||
}
|
||||
|
||||
/// Set the timeout per acceptance command.
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ReviewGateHook {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ReviewGateHook {
|
||||
/// Runs one acceptance command to its verdict: pass, fail with its stderr, or fail because it
|
||||
/// did not spawn, did not run, or ran out of time.
|
||||
async fn run_command(&self, cmd: &[String]) -> ReviewItem {
|
||||
let program = &cmd[0];
|
||||
let args = &cmd[1..];
|
||||
let label = cmd.join(" ");
|
||||
debug!(program = %program, ?args, "running acceptance command");
|
||||
|
||||
let mut command = TokioCommand::new(program);
|
||||
command
|
||||
.args(args)
|
||||
.env(RECURSION_GUARD_ENV, "1")
|
||||
.kill_on_drop(true)
|
||||
// Acceptance commands run under the TUI; none of their I/O may touch it.
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
// Own process group so a timeout can kill the whole tree, not just cargo.
|
||||
crate::program::detach_from_terminal(&mut command);
|
||||
|
||||
let child = match command.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(error) => {
|
||||
warn!(program = %program, error = %error, "could not spawn an acceptance command");
|
||||
let evidence = format!("Command failed to spawn: {error}");
|
||||
return failure(label, evidence, "Check command path and arguments".into());
|
||||
}
|
||||
};
|
||||
let child_pid = child.id();
|
||||
|
||||
match tokio::time::timeout(self.timeout, child.wait_with_output()).await {
|
||||
Ok(Ok(output)) if output.status.success() => {
|
||||
ReviewItem { label, status: ReviewItemStatus::Pass, evidence: None, fix: None }
|
||||
}
|
||||
Ok(Ok(output)) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
let fix = format!("Fix issues in: {label}");
|
||||
failure(label, stderr, fix)
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
warn!(program = %program, error = %error, "an acceptance command did not run");
|
||||
let evidence = format!("Command failed to execute: {error}");
|
||||
failure(label, evidence, "Check command path and arguments".into())
|
||||
}
|
||||
Err(_) => {
|
||||
let secs = self.timeout.as_secs();
|
||||
warn!(program = %program, timeout_secs = secs, "acceptance command timed out");
|
||||
// kill_on_drop reaps the direct child; this reaps its descendants.
|
||||
if let Some(pid) = child_pid {
|
||||
crate::program::kill_tree(pid);
|
||||
}
|
||||
let fix = format!("Increase timeout or optimize command: {label}");
|
||||
failure(label, format!("Command timed out after {secs}s"), fix)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed acceptance item with what happened and what to try.
|
||||
fn failure(label: String, evidence: String, fix: String) -> ReviewItem {
|
||||
ReviewItem { label, status: ReviewItemStatus::Fail, evidence: Some(evidence), fix: Some(fix) }
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for ReviewGateHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"review-gate"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::ReviewGate]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, _cx: &HookCtx) -> HookOutcome {
|
||||
let HookEvent::Other(_) = ev else {
|
||||
return HookOutcome::Continue;
|
||||
};
|
||||
|
||||
// Recursion guard: if we're already inside a review gate (env set by a parent
|
||||
// acceptance command), skip — otherwise a `cargo test` gate re-runs the suite.
|
||||
if std::env::var_os(RECURSION_GUARD_ENV).is_some() {
|
||||
warn!("already running inside a review gate; skipping acceptance commands to avoid recursion");
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
debug!("running acceptance commands");
|
||||
|
||||
let mut items = Vec::new();
|
||||
|
||||
for cmd in &self.commands {
|
||||
if !cmd.is_empty() {
|
||||
items.push(self.run_command(cmd).await);
|
||||
}
|
||||
}
|
||||
|
||||
let verdict = ReviewVerdict::new(items);
|
||||
|
||||
let verdict_str = format!(
|
||||
"{}\n\nItems:\n{}",
|
||||
verdict.overall,
|
||||
verdict
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| format!(
|
||||
" - [{}] {}: {}",
|
||||
item.status,
|
||||
item.label,
|
||||
item.evidence.as_deref().unwrap_or("no evidence")
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
|
||||
HookOutcome::InjectContext(verdict_str)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::hook::{HookCtx, HookEvent, HookOutcome, HookPoint, HookRegistry};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
fn test_ctx() -> HookCtx {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
HookCtx { session_id: "test".into(), event_tx: tx, hook_registry: HookRegistry::new() }
|
||||
}
|
||||
|
||||
/// The recursion guard must prevent acceptance commands from running when we're
|
||||
/// already inside a review gate — this is what stops the `cargo test` fork bomb.
|
||||
#[tokio::test]
|
||||
async fn test_recursion_guard_skips_commands() {
|
||||
let dir = std::env::temp_dir().join("luxe-review-gate-guard-test");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let sentinel = dir.join("ran");
|
||||
|
||||
// A command that would create a sentinel file if it ever executed.
|
||||
let hook = ReviewGateHook::with_commands(vec![vec![
|
||||
"touch".into(),
|
||||
sentinel.to_string_lossy().into_owned(),
|
||||
]]);
|
||||
|
||||
// Simulate being inside a parent review gate.
|
||||
std::env::set_var(RECURSION_GUARD_ENV, "1");
|
||||
let outcome = hook
|
||||
.on(HookPoint::ReviewGate, &HookEvent::Other(serde_json::Value::Null), &test_ctx())
|
||||
.await;
|
||||
std::env::remove_var(RECURSION_GUARD_ENV);
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::Continue), "guard should skip and Continue");
|
||||
assert!(!sentinel.exists(), "acceptance command must not run under the guard");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_with_no_commands_spawns_nothing() {
|
||||
// The break this catches: a default of `["true"]`, which spawned a real process on every
|
||||
// claim to answer "yes" — and, since `true` is a unix program, refused every claim on
|
||||
// Windows because a command that cannot be spawned is reported as a failure.
|
||||
assert!(ReviewGateHook::new().commands.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_review_gate_hook_custom_commands() {
|
||||
let commands = vec![vec!["echo".into(), "test".into()]];
|
||||
let hook = ReviewGateHook::with_commands(commands);
|
||||
assert_eq!(hook.commands.len(), 1);
|
||||
}
|
||||
}
|
||||
264
crates/luxe-core/src/hooks/review_integrator.rs
Normal file
264
crates/luxe-core/src/hooks/review_integrator.rs
Normal file
@@ -0,0 +1,264 @@
|
||||
//! Review integrator hook — the gate a claimed phase has to clear before the phase advances.
|
||||
//!
|
||||
//! Fires when the agent calls `loop_control action="progress"`, which is a *claim* that the phase is
|
||||
//! done rather than the fact of it. [`PhaseGate`] decides, and a refusal reaches the model as the
|
||||
//! tool's own result rather than a log entry.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint, LoopControl};
|
||||
use crate::loop_controller::LoopController;
|
||||
use crate::phase_gate::{GateOutcome, PhaseGate};
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
/// Runs the phase gate when a phase is claimed complete, and advances only if it passes.
|
||||
///
|
||||
/// The sole owner of phase advancement. Anything else moving that counter would be racing this,
|
||||
/// which is what happened while this hook fired on every `AgentEnd`.
|
||||
pub struct ReviewIntegratorHook {
|
||||
/// Loop controller for tracking phase and state.
|
||||
loop_controller: Arc<LoopController>,
|
||||
/// What a claim has to clear.
|
||||
gate: Arc<PhaseGate>,
|
||||
/// Project root, for re-anchoring the review baseline when a phase closes.
|
||||
repo_root: std::path::PathBuf,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ReviewIntegratorHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ReviewIntegratorHook").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ReviewIntegratorHook {
|
||||
/// A hook whose gate accepts everything.
|
||||
pub fn new(loop_controller: Arc<LoopController>) -> Self {
|
||||
Self {
|
||||
loop_controller,
|
||||
gate: Arc::new(PhaseGate::new()),
|
||||
repo_root: std::path::PathBuf::from("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// The project the loop is working in, whose `HEAD` anchors each phase's review.
|
||||
pub fn in_project(mut self, repo_root: impl Into<std::path::PathBuf>) -> Self {
|
||||
self.repo_root = repo_root.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Judge claims with `gate`, shared with whatever else has to consult it.
|
||||
pub fn with_gate(mut self, gate: Arc<PhaseGate>) -> Self {
|
||||
self.gate = gate;
|
||||
self
|
||||
}
|
||||
|
||||
/// Move the phase on, once the gate has agreed it may.
|
||||
///
|
||||
/// Always by one, whatever number the claim carried. A claim is the agent saying "this phase is
|
||||
/// finished", not choosing where the counter lands: honoring the number let a model with a
|
||||
/// one-phase plan in front of it walk the counter to three, because it kept naming a new phase
|
||||
/// each time it claimed. Setting an explicit phase is a human's call, and `luxe loop phase <n>`
|
||||
/// is how it is made.
|
||||
async fn advance_on_pass(&self, claimed: Option<u32>) -> Result<(), String> {
|
||||
let current = self.loop_controller.get_state().await.current_phase;
|
||||
if let Some(claimed) = claimed {
|
||||
if claimed != current {
|
||||
// `debug`, not `warn`: the number is for the record and the counter is ours, so a
|
||||
// claim that names the phase it thinks comes *next* is a disagreement about
|
||||
// spelling rather than an oddity the run coped with. It fired on every single
|
||||
// claim of a healthy four-phase run.
|
||||
debug!(claimed, current, "the claim named a phase other than the current one");
|
||||
}
|
||||
}
|
||||
info!(from = current, "gate passed, advancing to the next phase");
|
||||
self.loop_controller.advance_phase().await.map_err(|e| e.to_string())?;
|
||||
// The phase that just closed is the next one's starting point, so the review that follows
|
||||
// reads only what the next phase did.
|
||||
self.loop_controller.record_phase_baseline(&self.repo_root).await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for ReviewIntegratorHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"review-integrator"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::LoopControl]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
// Only a progress claim closes a phase. `complete` is the completion challenger's, which
|
||||
// runs the same gate before it accepts, and `blocked` belongs to whoever is being asked for
|
||||
// a decision.
|
||||
let HookEvent::LoopControl(LoopControl::Progress { phase }) = ev else {
|
||||
return HookOutcome::Continue;
|
||||
};
|
||||
debug!("phase claimed complete, running the gate");
|
||||
|
||||
let current = self.loop_controller.get_state().await.current_phase;
|
||||
cx.notify(format!("phase {current} claimed complete — running the gate"));
|
||||
match self.gate.run(current, "this phase", &|line| cx.notify(line)).await {
|
||||
GateOutcome::Passed => {
|
||||
if let Err(error) = self.advance_on_pass(*phase).await {
|
||||
error!(%error, "the gate passed but the phase could not be advanced");
|
||||
let message = format!(
|
||||
"The gate accepted phase {current}, but the loop could not save the new \
|
||||
phase ({error}), so it is paused with phase {current} still open. Check \
|
||||
that `.luxe/loop/` is writable, then run `luxe loop start` again."
|
||||
);
|
||||
return pause_for_a_person(&self.loop_controller, cx, message).await;
|
||||
}
|
||||
cx.notify(format!("phase {current} accepted — now on phase {}", current + 1));
|
||||
// The claim's own result says the gate agreed, as a refusal says why: echoing the
|
||||
// argument back would leave the agent unable to tell whether it was accepted.
|
||||
HookOutcome::ContinueLoop {
|
||||
message: format!(
|
||||
"The gate accepted phase {current}. The loop is now on phase {}: read what \
|
||||
`PLAN.md` says about it before starting.",
|
||||
current + 1
|
||||
),
|
||||
}
|
||||
}
|
||||
GateOutcome::Refused(message) => {
|
||||
info!("the gate refused the claim; the phase stays open");
|
||||
cx.notify(format!("phase {current} held: {}", crate::hooks::first_line(&message)));
|
||||
HookOutcome::ContinueLoop {
|
||||
message: format!("{message}\n\nThe phase number has not moved."),
|
||||
}
|
||||
}
|
||||
GateOutcome::Held(message) => {
|
||||
pause_for_a_person(&self.loop_controller, cx, message).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pause the loop on a claim the gate could not decide, telling the reader and the model why.
|
||||
pub(crate) async fn pause_for_a_person(
|
||||
controller: &LoopController,
|
||||
cx: &HookCtx,
|
||||
message: String,
|
||||
) -> HookOutcome {
|
||||
warn!(reason = %message, "the gate could not decide; pausing the loop");
|
||||
cx.notify(format!("paused for a person: {}", crate::hooks::first_line(&message)));
|
||||
if let Err(error) = controller.pause().await {
|
||||
error!(%error, "the loop could not be paused");
|
||||
}
|
||||
HookOutcome::StopLoop { reason: message }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn ctx() -> HookCtx {
|
||||
HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn running_controller(dir: &tempfile::TempDir) -> Arc<LoopController> {
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
controller
|
||||
}
|
||||
|
||||
/// With no gate configured, a progress claim is taken at its word.
|
||||
///
|
||||
/// A loop that has not been given acceptance commands must still be able to move through its
|
||||
/// plan; the gate is what makes a claim *checkable*, not what makes it possible.
|
||||
#[tokio::test]
|
||||
async fn a_claim_advances_when_no_gate_is_configured() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller = running_controller(&dir).await;
|
||||
let hook = ReviewIntegratorHook::new(controller.clone());
|
||||
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(LoopControl::Progress { phase: None }),
|
||||
&ctx(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// The claim's own result says what happened to it; echoing the argument back would leave an
|
||||
// agent that just claimed a phase unable to tell an acceptance from a refusal.
|
||||
let HookOutcome::ContinueLoop { message } = outcome else {
|
||||
panic!("an accepted claim answers the agent")
|
||||
};
|
||||
assert!(message.contains("accepted phase 0"), "{message}");
|
||||
assert!(message.contains("phase 1"), "and says where the loop is now: {message}");
|
||||
assert_eq!(controller.get_state().await.current_phase, 1);
|
||||
}
|
||||
|
||||
/// An acceptance the loop cannot save is not announced as one.
|
||||
///
|
||||
/// The break this catches: the phase moved in memory, the save failed, and the agent was told
|
||||
/// to start the next phase, which a restart would not remember.
|
||||
#[tokio::test]
|
||||
async fn an_acceptance_that_cannot_be_saved_pauses_with_the_phase_unmoved() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller = running_controller(&dir).await;
|
||||
// a directory where the state file belongs makes every later save fail
|
||||
std::fs::remove_file(dir.path().join("state.json")).unwrap();
|
||||
std::fs::create_dir(dir.path().join("state.json")).unwrap();
|
||||
let hook = ReviewIntegratorHook::new(controller.clone());
|
||||
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(LoopControl::Progress { phase: None }),
|
||||
&ctx(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let HookOutcome::StopLoop { reason } = outcome else {
|
||||
panic!("a failed save must not read as an acceptance, got {outcome:?}")
|
||||
};
|
||||
assert!(reason.contains("could not save"), "{reason}");
|
||||
assert_eq!(controller.get_state().await.current_phase, 0, "the live phase did not move");
|
||||
assert!(!controller.is_running().await, "and the loop waits for a person");
|
||||
}
|
||||
|
||||
/// A claim that names a phase still advances by exactly one.
|
||||
///
|
||||
/// The break this catches, measured on a real run: honoring the number let a local model with a
|
||||
/// one-phase plan walk the counter to three, because it named a new phase every time it claimed
|
||||
/// one. The counter is the gate's; `luxe loop phase <n>` is how a human sets it.
|
||||
#[tokio::test]
|
||||
async fn a_claim_cannot_choose_its_own_phase_number() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller = running_controller(&dir).await;
|
||||
let hook = ReviewIntegratorHook::new(controller.clone());
|
||||
|
||||
hook.on(
|
||||
HookPoint::LoopControl,
|
||||
&HookEvent::LoopControl(LoopControl::Progress { phase: Some(7) }),
|
||||
&ctx(),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(controller.get_state().await.current_phase, 1, "one step, not seven");
|
||||
}
|
||||
|
||||
/// Anything that is not a loop-control directive leaves the phase alone.
|
||||
#[tokio::test]
|
||||
async fn an_unrelated_event_is_not_a_phase_claim() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller = running_controller(&dir).await;
|
||||
let hook = ReviewIntegratorHook::new(controller.clone());
|
||||
|
||||
let outcome =
|
||||
hook.on(HookPoint::AgentEnd, &HookEvent::Other(serde_json::json!({})), &ctx()).await;
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
assert_eq!(controller.get_state().await.current_phase, 0);
|
||||
}
|
||||
}
|
||||
270
crates/luxe-core/src/hooks/runaway_guards.rs
Normal file
270
crates/luxe-core/src/hooks/runaway_guards.rs
Normal file
@@ -0,0 +1,270 @@
|
||||
//! Runaway guards hook — max turns/no-progress/stalls + rate-limit backoff.
|
||||
//!
|
||||
//! Prevents the loop from running away by enforcing:
|
||||
//! - Max turns per run (soft backstop)
|
||||
//! - Max no-progress turns (circling detection)
|
||||
//! - Max stalls before pausing for a human
|
||||
//! - Rate-limit backoff (429/TPM) distinct from hard errors
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::loop_controller::LoopController;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info};
|
||||
|
||||
struct HookState {
|
||||
turns_since_last_progress: u32,
|
||||
stalls_since_last_success: u32,
|
||||
consecutive_errors: u32,
|
||||
/// Whether the turn now ending failed.
|
||||
///
|
||||
/// `Error` fires before `AgentEnd`, so this is what lets "consecutive" mean consecutive: a turn
|
||||
/// that ends without having failed clears the count. Without it, five failures spread across a
|
||||
/// long run would stop the loop as though they had happened back to back.
|
||||
turn_failed: bool,
|
||||
last_progress_event: Option<String>,
|
||||
}
|
||||
|
||||
/// How long to wait before the loop's next iteration.
|
||||
///
|
||||
/// A trait so self-continuation can be paced without knowing what is counting the failures, and so
|
||||
/// a test can pace it without waiting.
|
||||
#[async_trait]
|
||||
pub trait IterationPacing: Send + Sync + std::fmt::Debug {
|
||||
/// The pause to take before enqueuing the next iteration.
|
||||
async fn pause_before_next_iteration(&self) -> std::time::Duration;
|
||||
}
|
||||
|
||||
/// A hook that prevents runaway loops with guards against max turns, no-progress,
|
||||
/// stalls, and rate-limit backoff.
|
||||
pub struct RunawayGuardsHook {
|
||||
/// Loop controller for checking state.
|
||||
loop_controller: Arc<LoopController>,
|
||||
/// Mutable hook state.
|
||||
state: Arc<Mutex<HookState>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RunawayGuardsHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RunawayGuardsHook").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl RunawayGuardsHook {
|
||||
/// Create a new runaway guards hook.
|
||||
pub fn new(loop_controller: Arc<LoopController>) -> Self {
|
||||
Self {
|
||||
loop_controller,
|
||||
state: Arc::new(Mutex::new(HookState {
|
||||
turns_since_last_progress: 0,
|
||||
stalls_since_last_success: 0,
|
||||
consecutive_errors: 0,
|
||||
turn_failed: false,
|
||||
last_progress_event: None,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Categorize a tool name as "building" (progress) vs "reading" (no progress).
|
||||
///
|
||||
/// Building tools modify the workspace (edit, write, bash, git). Reading tools
|
||||
/// only observe (read, grep, glob, web_search, web_fetch, etc.). Neutrals like
|
||||
/// question/skill/task/todo/astgrep/loop_control don't count as progress either —
|
||||
/// they're part of the thinking loop, not active building.
|
||||
fn is_building_tool(tool_name: &str) -> bool {
|
||||
matches!(tool_name, "edit" | "write" | "bash" | "git")
|
||||
}
|
||||
|
||||
/// Check if we should stop due to max turns.
|
||||
pub async fn check_max_turns(&self) -> Option<String> {
|
||||
let state = self.loop_controller.get_state().await;
|
||||
if state.iteration >= state.max_turns_per_run as u64 {
|
||||
Some("Max turns reached. Ending loop.".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if we should stop due to no-progress (circling).
|
||||
pub async fn check_no_progress(&self) -> Option<String> {
|
||||
let state = self.state.lock().await;
|
||||
let config = self.loop_controller.get_state().await;
|
||||
if state.turns_since_last_progress >= config.max_no_progress_turns {
|
||||
Some("No progress detected (circling). Ending loop.".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if we should stop due to max stalls.
|
||||
pub async fn check_max_stalls(&self) -> Option<String> {
|
||||
let state = self.state.lock().await;
|
||||
let config = self.loop_controller.get_state().await;
|
||||
if state.stalls_since_last_success >= config.max_stalls {
|
||||
Some("Max stalls reached. Pausing for human.".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if we should stop due to max consecutive errors.
|
||||
pub async fn check_max_errors(&self) -> Option<String> {
|
||||
let state = self.state.lock().await;
|
||||
let config = self.loop_controller.get_state().await;
|
||||
if state.consecutive_errors >= config.max_consecutive_errors {
|
||||
Some("Max consecutive errors reached. Ending loop.".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a progress event.
|
||||
pub async fn record_progress(&self, event: &str) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.turns_since_last_progress = 0;
|
||||
state.stalls_since_last_success = 0;
|
||||
state.last_progress_event = Some(event.to_string());
|
||||
}
|
||||
|
||||
/// Record a stall (no progress).
|
||||
pub async fn record_stall(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.turns_since_last_progress += 1;
|
||||
state.stalls_since_last_success += 1;
|
||||
}
|
||||
|
||||
/// Record an error, and remember that the turn now ending is a failed one.
|
||||
pub async fn record_error(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.consecutive_errors += 1;
|
||||
state.turn_failed = true;
|
||||
}
|
||||
|
||||
/// Reset error counter on success.
|
||||
pub async fn reset_errors(&self) {
|
||||
let mut state = self.state.lock().await;
|
||||
state.consecutive_errors = 0;
|
||||
}
|
||||
|
||||
/// Get the rate-limit backoff duration (exponential backoff based on consecutive errors).
|
||||
pub async fn get_backoff_ms(&self) -> u64 {
|
||||
let state = self.state.lock().await;
|
||||
// Exponential backoff: 1s, 2s, 4s, 8s, max 30s
|
||||
let base = 1000u64;
|
||||
let max = 30000u64;
|
||||
let backoff = base * 2u64.pow(state.consecutive_errors.min(5));
|
||||
backoff.min(max)
|
||||
}
|
||||
|
||||
/// Run all guards and return the first violation, if any.
|
||||
pub async fn check_all_guards(&self) -> Option<String> {
|
||||
if let Some(msg) = self.check_max_turns().await {
|
||||
return Some(msg);
|
||||
}
|
||||
if let Some(msg) = self.check_no_progress().await {
|
||||
return Some(msg);
|
||||
}
|
||||
if let Some(msg) = self.check_max_stalls().await {
|
||||
return Some(msg);
|
||||
}
|
||||
if let Some(msg) = self.check_max_errors().await {
|
||||
return Some(msg);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl IterationPacing for RunawayGuardsHook {
|
||||
/// Zero while things are working. After a failure it is [`Self::get_backoff_ms`]'s exponential
|
||||
/// pause, which is the difference between backing off a rate-limited provider and hammering it
|
||||
/// at full speed until an unrelated guard cuts the run off.
|
||||
async fn pause_before_next_iteration(&self) -> std::time::Duration {
|
||||
if self.state.lock().await.consecutive_errors == 0 {
|
||||
return std::time::Duration::ZERO;
|
||||
}
|
||||
std::time::Duration::from_millis(self.get_backoff_ms().await)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for RunawayGuardsHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"runaway-guards"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::AgentEnd, HookPoint::AfterToolUse, HookPoint::Error]
|
||||
}
|
||||
|
||||
async fn on(&self, point: HookPoint, ev: &HookEvent, _cx: &HookCtx) -> HookOutcome {
|
||||
match point {
|
||||
// A failed turn is an error the loop's budget has to see. Without this, a provider
|
||||
// outage never touched `consecutive_errors`, so `max_consecutive_errors` could not fire
|
||||
// and the exponential backoff had nothing to back off from.
|
||||
HookPoint::Error => {
|
||||
self.record_error().await;
|
||||
debug!("turn error recorded");
|
||||
HookOutcome::Continue
|
||||
}
|
||||
HookPoint::AfterToolUse => {
|
||||
// A failing tool call is the agent's ordinary feedback loop, not the loop breaking:
|
||||
// an `edit` whose `oldText` did not match, a `bash` that exited non-zero, a `read`
|
||||
// of a file that is not there. Counting them against the error budget ended a
|
||||
// productive run after five *scattered* tool failures, which is what
|
||||
// `max_consecutive_errors` is emphatically not for. Turn failures are what it
|
||||
// counts, and those arrive at `HookPoint::Error`. An unproductive turn is already
|
||||
// the no-progress guard's business.
|
||||
if let HookEvent::ToolResult { is_error, tool_name, .. } = ev {
|
||||
if *is_error {
|
||||
debug!(tool = %tool_name, "tool call failed (not counted against the error budget)");
|
||||
} else if Self::is_building_tool(tool_name) {
|
||||
self.record_progress(&format!("tool: {}", tool_name)).await;
|
||||
debug!(tool = %tool_name, "building tool progress recorded");
|
||||
} else {
|
||||
debug!(tool = %tool_name, "read-only/neutral tool (no progress)");
|
||||
}
|
||||
}
|
||||
HookOutcome::Continue
|
||||
}
|
||||
HookPoint::AgentEnd => {
|
||||
debug!("checking all guards");
|
||||
|
||||
// A turn that ended without failing clears the error run. `Error` fires first, so
|
||||
// the flag is already set when it is the failed one.
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
if state.turn_failed {
|
||||
state.turn_failed = false;
|
||||
} else {
|
||||
state.consecutive_errors = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(msg) = self.check_all_guards().await {
|
||||
// A guard firing is the loop doing what it was configured to do, and whatever
|
||||
// was actually wrong has already logged itself: a failed turn at `error`, a
|
||||
// stall at `warn`. Repeating it here as a warning would double-report the cause
|
||||
// and put a warning on the ordinary case of a run reaching its turn budget.
|
||||
info!(reason = %msg, "ending the run on a guard");
|
||||
let _ = self.loop_controller.stop().await;
|
||||
return HookOutcome::StopLoop { reason: msg };
|
||||
}
|
||||
|
||||
// Increment counters.
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
state.turns_since_last_progress += 1;
|
||||
state.stalls_since_last_success += 1;
|
||||
}
|
||||
|
||||
HookOutcome::Continue
|
||||
}
|
||||
_ => HookOutcome::Continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
301
crates/luxe-core/src/hooks/runaway_guards/tests.rs
Normal file
301
crates/luxe-core/src/hooks/runaway_guards/tests.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_not_running() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Loop not running -> Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_max_turns() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
// Set max turns to 2 (iteration starts at 1, so first turn passes, second triggers).
|
||||
controller
|
||||
.update_state(|state| {
|
||||
state.max_turns_per_run = 2;
|
||||
})
|
||||
.await;
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller.clone());
|
||||
|
||||
// First turn should pass.
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
|
||||
// Simulate a new run (increment iteration).
|
||||
controller.resume().await.unwrap();
|
||||
controller.start().await.unwrap();
|
||||
|
||||
// Second turn should trigger max turns.
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::StopLoop { reason } => {
|
||||
assert!(reason.contains("Max turns reached"));
|
||||
}
|
||||
_ => panic!("expected StopLoop outcome"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_no_progress() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
// Set max_no_progress_turns to 5 (lower than default 12).
|
||||
controller
|
||||
.update_state(|state| {
|
||||
state.max_no_progress_turns = 5;
|
||||
})
|
||||
.await;
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// Simulate 5 turns without progress.
|
||||
for _ in 0..5 {
|
||||
hook.record_stall().await;
|
||||
}
|
||||
|
||||
// Should trigger no-progress.
|
||||
let msg = hook.check_no_progress().await;
|
||||
assert!(msg.is_some());
|
||||
assert!(msg.unwrap().contains("No progress detected"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_record_progress() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// Simulate 5 turns without progress.
|
||||
for _ in 0..5 {
|
||||
hook.record_stall().await;
|
||||
}
|
||||
|
||||
// Record progress.
|
||||
hook.record_progress("edited file").await;
|
||||
|
||||
// Should not trigger no-progress.
|
||||
let msg = hook.check_no_progress().await;
|
||||
assert!(msg.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_rate_limit_backoff() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// 0 errors -> 1s backoff.
|
||||
assert_eq!(hook.get_backoff_ms().await, 1000);
|
||||
|
||||
// 1 error -> 2s backoff.
|
||||
hook.record_error().await;
|
||||
assert_eq!(hook.get_backoff_ms().await, 2000);
|
||||
|
||||
// 5 errors -> 30s backoff (max).
|
||||
for _ in 0..4 {
|
||||
hook.record_error().await;
|
||||
}
|
||||
assert_eq!(hook.get_backoff_ms().await, 30000);
|
||||
|
||||
// Reset errors.
|
||||
hook.reset_errors().await;
|
||||
assert_eq!(hook.get_backoff_ms().await, 1000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_after_tool_use_progress() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
// Set max_stalls to 3 (lower than default 5).
|
||||
controller
|
||||
.update_state(|state| {
|
||||
state.max_stalls = 3;
|
||||
})
|
||||
.await;
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// Simulate 3 stalls (would trigger max_stalls).
|
||||
for _ in 0..3 {
|
||||
hook.record_stall().await;
|
||||
}
|
||||
|
||||
// Should trigger max_stalls.
|
||||
let msg = hook.check_max_stalls().await;
|
||||
assert!(msg.is_some());
|
||||
|
||||
// Now simulate a successful tool use.
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AfterToolUse,
|
||||
&HookEvent::ToolResult {
|
||||
tool_name: "edit".to_string(),
|
||||
result: "success".to_string(),
|
||||
is_error: false,
|
||||
},
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
|
||||
// Should NOT trigger max_stalls anymore (progress recorded).
|
||||
let msg = hook.check_max_stalls().await;
|
||||
assert!(msg.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failing_tool_call_is_not_counted_against_the_error_budget() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// Five failing tool calls, which is what `max_consecutive_errors` defaults to.
|
||||
for _ in 0..5 {
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AfterToolUse,
|
||||
&HookEvent::ToolResult {
|
||||
tool_name: "edit".to_string(),
|
||||
result: "oldText not found".to_string(),
|
||||
is_error: true,
|
||||
},
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
// The break this catches, measured on a real run: an `edit` whose `oldText` did not match,
|
||||
// a `bash` that exited non-zero and a `read` of a missing file are the agent's ordinary
|
||||
// feedback loop. Counting them here ended a run that was working, with "Max consecutive
|
||||
// errors reached" and five scattered tool failures behind it. A turn failure is what the
|
||||
// budget is for, and that arrives at `HookPoint::Error`.
|
||||
assert!(hook.check_max_errors().await.is_none(), "ordinary tool failures must not end the run");
|
||||
assert_eq!(
|
||||
hook.get_backoff_ms().await,
|
||||
1000,
|
||||
"and must not earn a backoff, which is for a provider that is failing"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_runaway_guards_hook_read_only_tools_dont_reset_stalls() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
// Set max_stalls to 3.
|
||||
controller
|
||||
.update_state(|state| {
|
||||
state.max_stalls = 3;
|
||||
})
|
||||
.await;
|
||||
|
||||
let hook = RunawayGuardsHook::new(controller);
|
||||
|
||||
// Simulate 3 stalls.
|
||||
for _ in 0..3 {
|
||||
hook.record_stall().await;
|
||||
}
|
||||
|
||||
// Should trigger max_stalls.
|
||||
let msg = hook.check_max_stalls().await;
|
||||
assert!(msg.is_some());
|
||||
|
||||
// Simulate read-only tools (read, grep, glob).
|
||||
for tool in ["read", "grep", "glob"] {
|
||||
hook.on(
|
||||
HookPoint::AfterToolUse,
|
||||
&HookEvent::ToolResult {
|
||||
tool_name: tool.to_string(),
|
||||
result: "found stuff".to_string(),
|
||||
is_error: false,
|
||||
},
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Should STILL trigger max_stalls (read-only tools don't reset stalls).
|
||||
let msg = hook.check_max_stalls().await;
|
||||
assert!(msg.is_some());
|
||||
}
|
||||
283
crates/luxe-core/src/hooks/self_continuation.rs
Normal file
283
crates/luxe-core/src/hooks/self_continuation.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! Self-continuation hook — enqueues the next iteration's user message on AgentEnd.
|
||||
//!
|
||||
//! When the continuous loop is running, this hook fires on `HookPoint::AgentEnd` and
|
||||
//! returns `HookOutcome::ContinueLoop` with a "continue building" steer message. The
|
||||
//! engine handles this by sending `Action::SubmitUserMessage`.
|
||||
|
||||
use crate::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint};
|
||||
use crate::loop_controller::LoopController;
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Characters of the phase's plan section carried into the steer that opens it.
|
||||
///
|
||||
/// A steer is a user message and therefore permanent history, so the slice is bounded and sent
|
||||
/// **once per phase** — every later iteration of the same phase gets the heading alone.
|
||||
const MAX_PHASE_SECTION_CHARS: usize = 4_000;
|
||||
|
||||
/// Default steer message for self-continuation.
|
||||
///
|
||||
/// The journal path is built from the constants the loop actually writes to, so no iteration opens
|
||||
/// by telling the agent to read a file that is not there.
|
||||
///
|
||||
/// It also has to say how a phase *ends*. Without the last sentence nothing ever calls
|
||||
/// `loop_control`, so the phase gate never runs, the phase never advances, and the loop grinds
|
||||
/// through its turn budget on one phase forever. Measured: four turns of real work, no claim, no
|
||||
/// gate.
|
||||
fn default_continue_steer() -> String {
|
||||
format!(
|
||||
"Continue building. Read {dir}/{journal} to recall state, then take ONE small concrete \
|
||||
increment toward the current phase, validate it, record what you did, and END YOUR TURN. \
|
||||
When the current phase is genuinely finished and its acceptance checks pass, call \
|
||||
`loop_control` with action=\"progress\" to claim it — the phase only advances if the gate \
|
||||
agrees, and you will be told what is missing if it does not.",
|
||||
dir = crate::loop_hooks::journal_dir_display(),
|
||||
journal = crate::loop_hooks::JOURNAL_FILE,
|
||||
)
|
||||
}
|
||||
|
||||
/// What the loop is working on, as the steer says it.
|
||||
///
|
||||
/// `section` is `Some` only on the first iteration of a phase: the plan's own words are what stop a
|
||||
/// developer building the whole plan at once, and repeating them every turn would pay for them
|
||||
/// again in every request that follows.
|
||||
fn phase_steer(phase: u32, heading: Option<&str>, section: Option<&str>) -> String {
|
||||
let named = match heading {
|
||||
// A heading that already names its own number is left alone, or the steer reads
|
||||
// "phase 1 — Phase 1 — Ranking".
|
||||
Some(heading) if heading.to_ascii_lowercase().starts_with(&format!("phase {phase}")) => {
|
||||
heading.to_string()
|
||||
}
|
||||
Some(heading) => format!("phase {phase} — {heading}"),
|
||||
None => format!("phase {phase}"),
|
||||
};
|
||||
let mut steer = format!(
|
||||
"Continue building. You are on {named}. Read {dir}/{journal} to recall state, then take ONE \
|
||||
small concrete increment toward THIS phase — not the ones after it — validate it, record \
|
||||
what you did, and END YOUR TURN. When this phase is genuinely finished and its acceptance \
|
||||
checks pass, call `loop_control` with action=\"progress\" to claim it — the phase only \
|
||||
advances if the gate agrees, and you will be told what is missing if it does not.",
|
||||
dir = crate::loop_hooks::journal_dir_display(),
|
||||
journal = crate::loop_hooks::JOURNAL_FILE,
|
||||
);
|
||||
if let Some(section) = section {
|
||||
steer.push_str(&format!("\n\n## What phase {phase} is, from `PLAN.md`\n\n{section}"));
|
||||
}
|
||||
steer
|
||||
}
|
||||
|
||||
/// The steer for a phase number the plan does not have.
|
||||
///
|
||||
/// The counter can outrun the plan — the gate advances it on every accepted claim, and nothing in
|
||||
/// the plan says how many phases there are. Left alone the loop keeps steering "work on the current
|
||||
/// phase" at a phase that does not exist, and a finished project spends the rest of its turn
|
||||
/// budget. Saying so, and naming both ways out, is the difference between a loop that ends and
|
||||
/// one that idles.
|
||||
///
|
||||
/// What the work is verified against is `PLAN.md`, and `PROJECT.md`'s Definition of Done only where
|
||||
/// the project has one: naming a file that is not there sends the loop to `blocked`, asking a
|
||||
/// person for a document no plan-mode plan comes with.
|
||||
fn past_the_plan_steer(phase: u32, has_project_brief: bool) -> String {
|
||||
let against = match has_project_brief {
|
||||
true => "what `PLAN.md` asked for, and the Definition of Done in `PROJECT.md`,",
|
||||
false => "what each phase of `PLAN.md` asked for",
|
||||
};
|
||||
format!(
|
||||
"`PLAN.md` has no phase {phase}, so its phases are done. Do not invent another one. Verify \
|
||||
{against} against what is actually in the tree, record the result in {dir}/{journal}, and \
|
||||
then either call `loop_control` with action=\"complete\" if every item holds, or \
|
||||
action=\"blocked\" with the specific question if something needs a human decision.",
|
||||
dir = crate::loop_hooks::journal_dir_display(),
|
||||
journal = crate::loop_hooks::JOURNAL_FILE,
|
||||
)
|
||||
}
|
||||
|
||||
/// The steer for `phase`, as the loop would send it.
|
||||
///
|
||||
/// `brief` carries the phase's own section of `PLAN.md`; without it the steer names the phase and
|
||||
/// nothing more. Public because the loop's *kickoff* has to say the same thing its iterations do,
|
||||
/// or a developer sees nothing about which phase just started.
|
||||
pub async fn steer_for(repo_root: &std::path::Path, phase: u32, brief: bool) -> String {
|
||||
let Ok(plan) = tokio::fs::read_to_string(repo_root.join("PLAN.md")).await else {
|
||||
return default_continue_steer();
|
||||
};
|
||||
let Some(section) = crate::plan::phase_section(&plan, phase) else {
|
||||
// A plan with no phase headings at all is not a plan that ran out; it is a plan written
|
||||
// another way, and the generic steer is right for it.
|
||||
return match crate::plan::phase_section(&plan, 0).is_some() {
|
||||
true => past_the_plan_steer(phase, repo_root.join("PROJECT.md").is_file()),
|
||||
false => default_continue_steer(),
|
||||
};
|
||||
};
|
||||
let heading = crate::plan::phase_heading(&plan, phase);
|
||||
phase_steer(
|
||||
phase,
|
||||
heading.as_deref(),
|
||||
brief.then(|| crate::hooks::head(§ion, MAX_PHASE_SECTION_CHARS)).as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A hook that enables self-continuation for the native continuous loop.
|
||||
///
|
||||
/// On `HookPoint::AgentEnd`, if the loop is running, returns `HookOutcome::ContinueLoop`
|
||||
/// with a steer message to enqueue the next iteration.
|
||||
pub struct SelfContinuationHook {
|
||||
/// Loop controller for checking running state.
|
||||
loop_controller: Arc<LoopController>,
|
||||
/// Custom steer message (if None, use default).
|
||||
continue_steer: Option<String>,
|
||||
/// Cooldown in milliseconds between iterations (0 = no cooldown).
|
||||
cooldown_ms: u64,
|
||||
/// Where the pause after a failed turn comes from.
|
||||
pacing: Option<Arc<dyn crate::hooks::runaway_guards::IterationPacing>>,
|
||||
/// The project whose `PLAN.md` says what each phase is. `None` steers without one.
|
||||
repo_root: Option<std::path::PathBuf>,
|
||||
/// The phase whose plan section has already been sent, so it is sent once rather than per turn.
|
||||
briefed_phase: std::sync::Mutex<Option<u32>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SelfContinuationHook {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SelfContinuationHook").field("cooldown_ms", &self.cooldown_ms).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SelfContinuationHook {
|
||||
/// Create a new self-continuation hook.
|
||||
pub fn new(loop_controller: Arc<LoopController>) -> Self {
|
||||
Self {
|
||||
loop_controller,
|
||||
continue_steer: None,
|
||||
cooldown_ms: 0,
|
||||
pacing: None,
|
||||
repo_root: None,
|
||||
briefed_phase: std::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The project the loop is building, whose `PLAN.md` scopes each iteration to one phase.
|
||||
pub fn in_project(mut self, repo_root: impl Into<std::path::PathBuf>) -> Self {
|
||||
self.repo_root = Some(repo_root.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Treat `phase` as already briefed, because the loop's kickoff message carried its plan.
|
||||
pub fn briefed_on(self, phase: u32) -> Self {
|
||||
if let Ok(mut briefed) = self.briefed_phase.lock() {
|
||||
*briefed = Some(phase);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Pace iterations by how the last ones went, so a failing provider is backed off.
|
||||
pub fn with_pacing(
|
||||
mut self,
|
||||
pacing: Arc<dyn crate::hooks::runaway_guards::IterationPacing>,
|
||||
) -> Self {
|
||||
self.pacing = Some(pacing);
|
||||
self
|
||||
}
|
||||
|
||||
/// Wait before the next iteration: the fixed cooldown, then any backoff a failure earned.
|
||||
///
|
||||
/// Slept in short slices and abandoned the moment the loop stops, because `luxe loop stop` has
|
||||
/// to take effect while a backoff is in progress — a run that ignores it for half a minute reads
|
||||
/// as a hung process.
|
||||
async fn wait_before_continuing(&self) {
|
||||
let mut remaining = std::time::Duration::from_millis(self.cooldown_ms);
|
||||
if let Some(pacing) = self.pacing.as_ref() {
|
||||
let backoff = pacing.pause_before_next_iteration().await;
|
||||
if !backoff.is_zero() {
|
||||
debug!(?backoff, "backing off after a failed turn");
|
||||
remaining = remaining.saturating_add(backoff);
|
||||
}
|
||||
}
|
||||
const SLICE: std::time::Duration = std::time::Duration::from_millis(250);
|
||||
while !remaining.is_zero() {
|
||||
if !self.loop_controller.is_running().await {
|
||||
debug!("loop stopped during the pause");
|
||||
return;
|
||||
}
|
||||
let slice = remaining.min(SLICE);
|
||||
tokio::time::sleep(slice).await;
|
||||
remaining = remaining.saturating_sub(slice);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a custom steer message for self-continuation.
|
||||
pub fn with_steer(mut self, steer: String) -> Self {
|
||||
self.continue_steer = Some(steer);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the cooldown between iterations in milliseconds.
|
||||
pub fn with_cooldown(mut self, ms: u64) -> Self {
|
||||
self.cooldown_ms = ms;
|
||||
self
|
||||
}
|
||||
|
||||
/// The steer for this iteration: a custom one, else the current phase's, else the generic one.
|
||||
///
|
||||
/// The phase matters because nothing else tells the developer which one it is on. Without it a
|
||||
/// model handed a three-phase plan builds all three in the first turn, and then claims phases
|
||||
/// there is no work left in — which is exactly what a run with a 27B local developer did.
|
||||
async fn steer_message(&self) -> String {
|
||||
if let Some(custom) = self.continue_steer.clone() {
|
||||
return custom;
|
||||
}
|
||||
let Some(repo_root) = self.repo_root.as_ref() else { return default_continue_steer() };
|
||||
let phase = self.loop_controller.get_state().await.current_phase;
|
||||
|
||||
// Scoped, and never held across the read below: a phase is briefed once, and the lock only
|
||||
// decides whether this is that once.
|
||||
let first_iteration_of_this_phase = match self.briefed_phase.lock() {
|
||||
Ok(mut briefed) => {
|
||||
let first = *briefed != Some(phase);
|
||||
*briefed = Some(phase);
|
||||
first
|
||||
}
|
||||
Err(_) => true,
|
||||
};
|
||||
|
||||
steer_for(repo_root, phase, first_iteration_of_this_phase).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for SelfContinuationHook {
|
||||
fn name(&self) -> &'static str {
|
||||
"self-continuation"
|
||||
}
|
||||
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::AgentEnd]
|
||||
}
|
||||
|
||||
async fn on(&self, _point: HookPoint, _ev: &HookEvent, cx: &HookCtx) -> HookOutcome {
|
||||
if !self.loop_controller.is_running().await {
|
||||
debug!("loop not running, skipping");
|
||||
return HookOutcome::Continue;
|
||||
}
|
||||
|
||||
// Increment iteration for runaway guards.
|
||||
self.loop_controller.increment_iteration().await;
|
||||
|
||||
self.wait_before_continuing().await;
|
||||
|
||||
let steer = self.steer_message().await;
|
||||
// Routine, and the steer is long and identical every time: the iteration number is the part
|
||||
// worth reading, and the text itself is a `debug!` for when it is genuinely in question.
|
||||
let state = self.loop_controller.get_state().await;
|
||||
let iteration = state.iteration;
|
||||
info!(iteration, "continuing the loop");
|
||||
debug!(%steer, "self-continuation steer");
|
||||
// The one marker that makes a run readable from outside: where it is, each time it moves.
|
||||
cx.notify(format!("iteration {iteration} · phase {}", state.current_phase));
|
||||
|
||||
HookOutcome::ContinueLoop { message: steer }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
211
crates/luxe-core/src/hooks/self_continuation/tests.rs
Normal file
211
crates/luxe-core/src/hooks/self_continuation/tests.rs
Normal file
@@ -0,0 +1,211 @@
|
||||
use super::*;
|
||||
use crate::loop_state::LoopState;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_self_continuation_hook_not_running() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
let hook = SelfContinuationHook::new(controller);
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Loop not running -> Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_self_continuation_hook_running() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
// Start the loop.
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = SelfContinuationHook::new(controller);
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// Loop running -> ContinueLoop.
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert_eq!(message, default_continue_steer());
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A phased plan reaches the developer one phase at a time, and only once per phase.
|
||||
///
|
||||
/// The break this catches, measured on a real run: nothing told the developer which phase it was
|
||||
/// on, so a 27B local model handed a three-phase plan built all three in its first turn and then
|
||||
/// claimed three phases in three minutes with no work left in any of them. The section is sent
|
||||
/// on the phase's first iteration only — a steer is permanent history, and re-sending the plan
|
||||
/// every turn is paid for in every request after it.
|
||||
#[tokio::test]
|
||||
async fn the_steer_scopes_the_work_to_the_phase_the_loop_is_on() {
|
||||
let dir = tempdir().unwrap();
|
||||
tokio::fs::write(
|
||||
dir.path().join("PLAN.md"),
|
||||
"# Plan\n\n## Phase 0 — Counting\n\nCount the words.\n\n## Phase 1 — Ranking\n\nRank \
|
||||
them.\n",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
let hook = SelfContinuationHook::new(controller.clone()).in_project(dir.path());
|
||||
|
||||
let opening = hook.steer_message().await;
|
||||
assert!(opening.contains("You are on Phase 0 — Counting"), "{opening}");
|
||||
assert!(!opening.contains("phase 0 — Phase 0"), "the heading names itself once: {opening}");
|
||||
assert!(opening.contains("Count the words."), "the phase's own words: {opening}");
|
||||
assert!(!opening.contains("Rank them."), "and not the next phase's: {opening}");
|
||||
|
||||
let second = hook.steer_message().await;
|
||||
assert!(second.contains("You are on Phase 0"), "still says which phase: {second}");
|
||||
assert!(!second.contains("Count the words."), "sent once per phase, not per turn: {second}");
|
||||
|
||||
controller.advance_phase().await.unwrap();
|
||||
let next = hook.steer_message().await;
|
||||
assert!(next.contains("Rank them."), "a new phase is briefed again: {next}");
|
||||
}
|
||||
|
||||
/// A counter past the end of the plan is told so, rather than steered at a phase that is not.
|
||||
///
|
||||
/// The break this catches: the gate advances the counter on every accepted claim and nothing
|
||||
/// bounds it by the plan, so a finished three-phase project kept being told to "work on the
|
||||
/// current phase" at phase 4 — spending the rest of its turn budget inventing work.
|
||||
#[tokio::test]
|
||||
async fn a_phase_the_plan_does_not_have_ends_the_plan_rather_than_inventing_one() {
|
||||
let dir = tempdir().unwrap();
|
||||
tokio::fs::write(dir.path().join("PLAN.md"), "## Phase 0 — Only\n\nDo it.\n").await.unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
controller.set_phase(4).await.unwrap();
|
||||
|
||||
let steer = SelfContinuationHook::new(controller).in_project(dir.path()).steer_message().await;
|
||||
|
||||
assert!(steer.contains("no phase 4"), "{steer}");
|
||||
assert!(steer.contains("complete"), "a way out: {steer}");
|
||||
assert!(steer.contains("blocked"), "and the other one: {steer}");
|
||||
assert!(!steer.contains("PROJECT.md"), "a brief the project does not have: {steer}");
|
||||
|
||||
tokio::fs::write(dir.path().join("PROJECT.md"), "# Brief\n").await.unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
controller.set_phase(4).await.unwrap();
|
||||
let steer = SelfContinuationHook::new(controller).in_project(dir.path()).steer_message().await;
|
||||
assert!(steer.contains("Definition of Done in `PROJECT.md`"), "{steer}");
|
||||
}
|
||||
|
||||
/// A plan written without phase headings keeps the generic steer.
|
||||
#[tokio::test]
|
||||
async fn a_plan_without_phases_is_steered_the_old_way() {
|
||||
let dir = tempdir().unwrap();
|
||||
tokio::fs::write(dir.path().join("PLAN.md"), "# Plan\n\nJust do the thing.\n").await.unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let steer = SelfContinuationHook::new(controller).in_project(dir.path()).steer_message().await;
|
||||
|
||||
assert_eq!(steer, default_continue_steer());
|
||||
}
|
||||
|
||||
/// The steer names the journal the loop actually writes, and says how to claim a phase.
|
||||
///
|
||||
/// Two breaks this catches, both of which shipped. The path used to be
|
||||
/// `.pi/agent-loop/PROGRESS.md` — another harness's directory, and nothing here writes it — so
|
||||
/// every iteration told the agent to read a file that did not exist. And nothing told it to call
|
||||
/// `loop_control` at all, so the phase gate never ran: measured at four turns of real work with
|
||||
/// no claim and no gate.
|
||||
#[test]
|
||||
fn the_steer_points_at_the_journal_and_says_how_to_claim_a_phase() {
|
||||
let steer = default_continue_steer();
|
||||
assert!(steer.contains(".luxe/loop/PROGRESS.md"), "{steer}");
|
||||
assert!(!steer.contains(".pi/"), "the loop must not send anyone to another harness: {steer}");
|
||||
assert!(steer.contains("loop_control"), "a phase has to be claimable: {steer}");
|
||||
assert!(steer.contains("progress"), "{steer}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_self_continuation_hook_custom_steer() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
controller.start().await.unwrap();
|
||||
|
||||
let hook = SelfContinuationHook::new(controller).with_steer("Custom steer message".to_string());
|
||||
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
match outcome {
|
||||
HookOutcome::ContinueLoop { message } => {
|
||||
assert_eq!(message, "Custom steer message");
|
||||
}
|
||||
_ => panic!("expected ContinueLoop outcome"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_self_continuation_hook_stopped_sentinel() {
|
||||
let dir = tempdir().unwrap();
|
||||
let controller =
|
||||
Arc::new(LoopController::new(dir.path().join("state.json"), dir.path().join("STOP")));
|
||||
|
||||
// Start the loop, then create STOP sentinel.
|
||||
controller.start().await.unwrap();
|
||||
LoopState::create_stop_sentinel(dir.path().join("STOP").as_path()).unwrap();
|
||||
|
||||
let hook = SelfContinuationHook::new(controller);
|
||||
let outcome = hook
|
||||
.on(
|
||||
HookPoint::AgentEnd,
|
||||
&HookEvent::Other(serde_json::json!({})),
|
||||
&HookCtx {
|
||||
session_id: "test".to_string(),
|
||||
event_tx: tokio::sync::mpsc::channel(1).0,
|
||||
hook_registry: crate::hook::HookRegistry::new(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// STOP sentinel exists -> Continue.
|
||||
assert!(matches!(outcome, HookOutcome::Continue));
|
||||
}
|
||||
Reference in New Issue
Block a user