Skip to main content

eclipse_core/
hooks.rs

1//! In-process hooks into the agent loop: the extension point the loop did not have.
2//!
3//! The loop has exactly one turn shape and six places where policy could differ: the start of
4//! a run, the request for a turn, the model's answer, a tool about to run, a tool's result,
5//! and the end of a run. A [`LoopHook`] sees all six and may change what happens next.
6//!
7//! ```text
8//! run_start ─▶ [ completion_call ─▶ model ─▶ model_turn_finished ─▶ dispatch ─▶ tool ─▶ outcome ]* ─▶ run_settled
9//! ```
10//!
11//! # Three rules, because a hook is control flow and control flow is easy to regret
12//!
13//! **Actions, not booleans.** Every method returns an action enum whose default is "carry on",
14//! so a hook that wants to observe can say nothing, and adding an event later cannot break a
15//! hook written today.
16//!
17//! **Hooks are awaited inline, so they must be cheap.** A hook runs inside the loop, in the
18//! way of the next model call: anything that blocks here is latency on every turn. A hook that
19//! needs to shell out, call a network service, or take its time is a *plugin*
20//! ([`crate::plugins`]), which runs in its own process with its own timeouts. That boundary is
21//! deliberate and it is the only reason the loop stays predictable.
22//!
23//! **A patch is not sticky.** [`hooks::RequestPatch`] affects the one turn its event belonged
24//! to; the event fires again next turn and produces a fresh answer. A hook that sets
25//! `tool_choice: required` every turn has built an infinite loop, and it will look like a bug
26//! in the model.
27//!
28//! # What a hook is not for
29//!
30//! Not for anything that must survive a restart (that is M13), not for anything that must run
31//! out of process (plugins), and not for replacing the loop's own guarantees — cancellation,
32//! the iteration cap and the dangling-call repair stay where they are, because a hook cannot
33//! be trusted to preserve them.
34use std::collections::BTreeMap;
35use std::sync::Arc;
36
37use async_trait::async_trait;
38
39use crate::config::{Config, HooksConfig};
40use crate::error::Error;
41use crate::message::Message;
42use crate::tools::ToolSpec;
43
44/// How a turn's request differs from the agent's defaults.
45///
46/// Every field is optional and every field is a *this turn only* decision. Providers that
47/// cannot express a field must say so rather than drop it silently: a patch nobody applied is
48/// worse than an error, because the model then looks irrational for reasons nothing records.
49#[derive(Debug, Clone, Default, PartialEq)]
50pub struct RequestPatch {
51    /// An extra system message, sent ahead of the conversation. Use it for a per-turn
52    /// reminder; the agent's own system prompt stays where it is.
53    pub preamble: Option<String>,
54    pub temperature: Option<f32>,
55    pub max_tokens: Option<u32>,
56    /// What the model may do with tools on this turn.
57    pub tool_choice: Option<ToolChoice>,
58    /// An allow-list of tool names to advertise. Unknown names are dropped, so a hook that
59    /// names a tool this build does not have narrows the list to what exists rather than
60    /// failing the turn.
61    pub active_tools: Option<Vec<String>>,
62    /// Merged into the request body, shallow: a key here replaces the same key from the config
63    /// profile. This is the escape hatch for provider-specific knobs (`top_p`, `min_p`,
64    /// `repeat_penalty`) without teaching Eclipse every vendor's spelling.
65    pub extra_params: BTreeMap<String, serde_json::Value>,
66    /// Extra messages inserted after the system prompt and ahead of the conversation. They are
67    /// *this turn only* — they are never stored, so the session reads as if they were not there.
68    /// Use for a per-turn reference document or a fetched excerpt.
69    pub documents: Vec<Message>,
70    /// Replaces the assembled conversation (everything after the system prompt) for this turn.
71    /// The agent's own system prompt is preserved; the history the loop would have sent is not.
72    /// Last writer wins, like `preamble`.
73    pub history: Option<Vec<Message>>,
74}
75
76impl RequestPatch {
77    pub fn is_empty(&self) -> bool {
78        self.preamble.is_none()
79            && self.temperature.is_none()
80            && self.max_tokens.is_none()
81            && self.tool_choice.is_none()
82            && self.active_tools.is_none()
83            && self.extra_params.is_empty()
84            && self.documents.is_empty()
85            && self.history.is_none()
86    }
87
88    /// Names of the fields this patch sets, for an error or a log line.
89    pub fn describe(&self) -> String {
90        let mut set = Vec::new();
91        if self.preamble.is_some() {
92            set.push("preamble");
93        }
94        if self.temperature.is_some() {
95            set.push("temperature");
96        }
97        if self.max_tokens.is_some() {
98            set.push("max_tokens");
99        }
100        if self.tool_choice.is_some() {
101            set.push("tool_choice");
102        }
103        if self.active_tools.is_some() {
104            set.push("active_tools");
105        }
106        if !self.extra_params.is_empty() {
107            set.push("extra_params");
108        }
109        if !self.documents.is_empty() {
110            set.push("documents");
111        }
112        if self.history.is_some() {
113            set.push("history");
114        }
115        set.join(", ")
116    }
117
118    /// Fold a later hook's patch into this one: scalars are last-writer-wins, `extra_params`
119    /// merge key by key, and two allow-lists intersect.
120    ///
121    /// Intersecting is the only composition that cannot widen what a hook meant to narrow: if
122    /// hook A permits three tools and hook B permits two, the turn gets the two. Union would
123    /// let a later hook quietly re-enable what an earlier one forbade.
124    pub fn merge(&mut self, later: RequestPatch) {
125        if later.preamble.is_some() {
126            self.preamble = later.preamble;
127        }
128        if later.temperature.is_some() {
129            self.temperature = later.temperature;
130        }
131        if later.max_tokens.is_some() {
132            self.max_tokens = later.max_tokens;
133        }
134        if later.tool_choice.is_some() {
135            self.tool_choice = later.tool_choice;
136        }
137        if let Some(names) = later.active_tools {
138            self.active_tools = Some(match self.active_tools.take() {
139                Some(mine) => mine.into_iter().filter(|n| names.contains(n)).collect(),
140                None => names,
141            });
142        }
143        self.extra_params.extend(later.extra_params);
144        self.documents.extend(later.documents);
145        if later.history.is_some() {
146            self.history = later.history;
147        }
148    }
149}
150
151/// The `tool_choice` values an OpenAI-compatible endpoint understands.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum ToolChoice {
154    Auto,
155    None,
156    Required,
157    /// Force one named tool.
158    Function(String),
159}
160
161impl ToolChoice {
162    /// The wire form: a bare string, or the function object.
163    pub fn to_json(&self) -> serde_json::Value {
164        match self {
165            ToolChoice::Auto => serde_json::json!("auto"),
166            ToolChoice::None => serde_json::json!("none"),
167            ToolChoice::Required => serde_json::json!("required"),
168            ToolChoice::Function(name) => serde_json::json!({
169                "type": "function",
170                "function": { "name": name }
171            }),
172        }
173    }
174
175    /// The config form: one string. The three keywords mean what OpenAI means by them;
176    /// anything else is a tool name, which is why `tool_choice = "read_file"` reads the way
177    /// a person writes it.
178    pub fn as_config_str(&self) -> &str {
179        match self {
180            ToolChoice::Auto => "auto",
181            ToolChoice::None => "none",
182            ToolChoice::Required => "required",
183            ToolChoice::Function(name) => name,
184        }
185    }
186
187    pub fn from_config_str(value: &str) -> ToolChoice {
188        match value.trim() {
189            "auto" => ToolChoice::Auto,
190            "none" => ToolChoice::None,
191            "required" => ToolChoice::Required,
192            other => ToolChoice::Function(other.to_string()),
193        }
194    }
195}
196
197impl serde::Serialize for ToolChoice {
198    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
199        s.serialize_str(self.as_config_str())
200    }
201}
202
203impl<'de> serde::Deserialize<'de> for ToolChoice {
204    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
205        let text = String::deserialize(d)?;
206        if text.trim().is_empty() {
207            return Err(serde::de::Error::custom(
208                "tool_choice must be `auto`, `none`, `required`, or a tool name",
209            ));
210        }
211        Ok(ToolChoice::from_config_str(&text))
212    }
213}
214
215/// A run beginning. `prompt` is what the user asked for, after the CLI resolved it.
216pub struct RunStart<'a> {
217    pub session: &'a str,
218    pub prompt: &'a str,
219}
220
221/// A turn about to request the model.
222pub struct CallEvent<'a> {
223    pub session: &'a str,
224    /// 1 for the first model call of the run.
225    pub turn: usize,
226    /// What the request will carry. The assembled system prompt and trimmed history are the
227    /// first two entries; a hook reads them, it does not edit them in place — it returns a
228    /// [`RequestPatch`].
229    pub messages: &'a [Message],
230    pub tools: &'a [ToolSpec],
231}
232
233/// The model's answer to a turn, before it is stored.
234pub struct Turn<'a> {
235    pub session: &'a str,
236    pub turn: usize,
237    pub reply: &'a Message,
238}
239
240/// What a hook asked to do with a malformed call: the name and the argument string the call
241/// should run with instead.
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct DispatchRepair {
244    pub name: String,
245    pub arguments: String,
246}
247
248/// A tool call about to run.
249pub struct Dispatch<'a> {
250    pub session: &'a str,
251    pub tool: &'a str,
252    pub arguments: &'a str,
253}
254
255/// A tool result, before the model sees it.
256pub struct Outcome<'a> {
257    pub session: &'a str,
258    pub tool: &'a str,
259    pub output: &'a str,
260    pub is_error: bool,
261    /// The call could not even be attempted: unknown tool, or arguments that are not JSON.
262    pub malformed: bool,
263}
264
265/// How a run ended, for hooks that audit or clean up.
266pub struct Settled<'a> {
267    pub session: &'a str,
268    pub turns: usize,
269    pub ending: Ending<'a>,
270}
271
272#[derive(Debug, PartialEq, Eq)]
273pub enum Ending<'a> {
274    /// The model answered.
275    Answered,
276    /// A hook said stop, or the loop gave up. The run's history is on disk either way.
277    Stopped(&'a str),
278    Cancelled,
279    Failed(&'a str),
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub enum RunStartAction {
284    Proceed,
285    Stop(String),
286}
287
288#[derive(Debug, Clone, PartialEq)]
289pub enum CallAction {
290    Proceed,
291    Patch(RequestPatch),
292    Stop(String),
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub enum TurnAction {
297    Proceed,
298    /// Ask again with the same context. Counts as a turn, so the iteration cap still bounds a
299    /// hook that repeats forever.
300    Repeat,
301    /// Discard this answer and ask again with a note added as a user message. The reply is not
302    /// stored, so the session reads as if the retry were the first attempt.
303    RetryWithFeedback(String),
304    Stop(String),
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub enum DispatchAction {
309    Proceed,
310    /// Rewrite the call before it runs: a malformed name or JSON arguments become something
311    /// the tool can actually use. Only the first hook that answers non-Proceed wins, so two
312    /// hooks repairing different calls in the same turn cannot fight over one call.
313    Repair {
314        name: String,
315        arguments: String,
316    },
317    Stop(String),
318}
319
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub enum OutcomeAction {
322    Proceed,
323    /// Replace what the model will read. The original is gone: this is for redaction as much
324    /// as for repair, and a hook that wants both must include what it wants to keep.
325    ReplaceOutput(String),
326    Stop(String),
327}
328
329/// One place to intervene in the loop. Every method has a "carry on" default, so implement
330/// only what you need.
331#[async_trait]
332pub trait LoopHook: Send + Sync {
333    async fn on_run_start(&self, _ev: RunStart<'_>) -> RunStartAction {
334        RunStartAction::Proceed
335    }
336
337    async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
338        CallAction::Proceed
339    }
340
341    async fn on_model_turn_finished(&self, _ev: Turn<'_>) -> TurnAction {
342        TurnAction::Proceed
343    }
344
345    async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
346        DispatchAction::Proceed
347    }
348
349    async fn on_outcome(&self, _ev: Outcome<'_>) -> OutcomeAction {
350        OutcomeAction::Proceed
351    }
352
353    async fn on_run_settled(&self, _ev: Settled<'_>) {}
354}
355
356/// The hooks a runtime runs, in registration order.
357///
358/// Empty by default: an agent with no hooks behaves exactly as it did before this module
359/// existed, which is what makes the surface safe to add.
360#[derive(Default, Clone)]
361pub struct LoopHooks {
362    hooks: Vec<Arc<dyn LoopHook>>,
363}
364
365impl std::fmt::Debug for LoopHooks {
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367        f.debug_struct("LoopHooks")
368            .field("count", &self.hooks.len())
369            .finish()
370    }
371}
372
373impl LoopHooks {
374    pub fn new(hooks: Vec<Arc<dyn LoopHook>>) -> Self {
375        Self { hooks }
376    }
377
378    pub fn len(&self) -> usize {
379        self.hooks.len()
380    }
381
382    pub fn is_empty(&self) -> bool {
383        self.hooks.is_empty()
384    }
385
386    /// `Some(reason)` when a hook stopped the run before it started.
387    pub async fn run_start(&self, ev: RunStart<'_>) -> Option<String> {
388        for hook in &self.hooks {
389            if let RunStartAction::Stop(reason) = hook.on_run_start(ev_clone(&ev)).await {
390                return Some(reason);
391            }
392        }
393        None
394    }
395
396    /// The merged patch for this turn, or the reason the run stopped.
397    ///
398    /// Stops end the chain: a later hook is not consulted about a turn that will not happen.
399    pub async fn completion_call(
400        &self,
401        session: &str,
402        turn: usize,
403        messages: &[Message],
404        tools: &[ToolSpec],
405    ) -> Result<RequestPatch, String> {
406        let mut merged = RequestPatch::default();
407        for hook in &self.hooks {
408            match hook
409                .on_completion_call(CallEvent {
410                    session,
411                    turn,
412                    messages,
413                    tools,
414                })
415                .await
416            {
417                CallAction::Proceed => {}
418                CallAction::Patch(p) => merged.merge(p),
419                CallAction::Stop(reason) => return Err(reason),
420            }
421        }
422        Ok(merged)
423    }
424
425    pub async fn model_turn_finished(
426        &self,
427        session: &str,
428        turn: usize,
429        reply: &Message,
430    ) -> TurnAction {
431        for hook in &self.hooks {
432            let action = hook
433                .on_model_turn_finished(Turn {
434                    session,
435                    turn,
436                    reply,
437                })
438                .await;
439            match action {
440                TurnAction::Proceed => {}
441                // First real instruction wins: two hooks telling the loop to do different
442                // things is a bug in the hooks, and the earliest is the most specific.
443                other => return other,
444            }
445        }
446        TurnAction::Proceed
447    }
448
449    /// `Ok(Some(repair))` when a hook rewrote the call, `Ok(None)` to let it go as-is,
450    /// `Err(reason)` to stop the run. The first real instruction wins, like the other events.
451    pub async fn dispatch(
452        &self,
453        session: &str,
454        tool: &str,
455        arguments: &str,
456    ) -> Result<Option<DispatchRepair>, String> {
457        for hook in &self.hooks {
458            match hook
459                .on_dispatch(Dispatch {
460                    session,
461                    tool,
462                    arguments,
463                })
464                .await
465            {
466                DispatchAction::Proceed => {}
467                DispatchAction::Repair { name, arguments } => {
468                    return Ok(Some(DispatchRepair { name, arguments }))
469                }
470                DispatchAction::Stop(reason) => return Err(reason),
471            }
472        }
473        Ok(None)
474    }
475
476    pub async fn outcome(
477        &self,
478        session: &str,
479        tool: &str,
480        output: &str,
481        is_error: bool,
482        malformed: bool,
483    ) -> OutcomeAction {
484        let mut current: Option<String> = None;
485        for hook in &self.hooks {
486            let shown = current.as_deref().unwrap_or(output);
487            match hook
488                .on_outcome(Outcome {
489                    session,
490                    tool,
491                    output: shown,
492                    is_error,
493                    malformed,
494                })
495                .await
496            {
497                OutcomeAction::Proceed => {}
498                OutcomeAction::ReplaceOutput(text) => current = Some(text),
499                OutcomeAction::Stop(reason) => return OutcomeAction::Stop(reason),
500            }
501        }
502        match current {
503            Some(text) => OutcomeAction::ReplaceOutput(text),
504            None => OutcomeAction::Proceed,
505        }
506    }
507
508    pub async fn run_settled(&self, ev: Settled<'_>) {
509        for hook in &self.hooks {
510            hook.on_run_settled(ev_clone_settled(&ev)).await;
511        }
512    }
513}
514
515/// Re-borrow an event for the next hook. The structs hold references, so they are rebuilt
516/// rather than cloned; this keeps the event types allocation-free.
517fn ev_clone<'a>(ev: &RunStart<'a>) -> RunStart<'a> {
518    RunStart {
519        session: ev.session,
520        prompt: ev.prompt,
521    }
522}
523
524fn ev_clone_settled<'a>(ev: &Settled<'a>) -> Settled<'a> {
525    Settled {
526        session: ev.session,
527        turns: ev.turns,
528        ending: match ev.ending {
529            Ending::Answered => Ending::Answered,
530            Ending::Stopped(r) => Ending::Stopped(r),
531            Ending::Cancelled => Ending::Cancelled,
532            Ending::Failed(r) => Ending::Failed(r),
533        },
534    }
535}
536
537// ---------------------------------------------------------------------------------------------
538// What a build ships, and the one place that turns `[hooks]` into hooks.
539// ---------------------------------------------------------------------------------------------
540
541/// A hook this build knows by name.
542pub struct HookInfo {
543    pub name: &'static str,
544    /// The loop point it is wired at, as `config show` prints it.
545    pub point: &'static str,
546    /// The keys its `[hooks.<name>]` table accepts. Empty: it takes no settings.
547    pub settings: &'static [&'static str],
548    /// Checks the *values* of a settings table whose keys are already known to be valid.
549    pub check: fn(&toml::value::Table) -> Result<(), String>,
550}
551
552/// The hooks this build ships. A name in `[hooks] order` must be one of these.
553pub const SHIPPED: &[HookInfo] = &[
554    HookInfo {
555        name: "recall-sessions",
556        point: "on_completion_call",
557        settings: &[
558            "results",
559            "budget_chars",
560            "min_query_chars",
561            "include_this_session",
562        ],
563        check: check_recall_settings,
564    },
565    HookInfo {
566        name: "redact-secrets",
567        point: "on_outcome",
568        settings: &["allow"],
569        check: check_redact_settings,
570    },
571];
572
573/// What `[hooks] order` is when the section is absent.
574///
575/// Redaction only. Recall used to be here too, on the argument that "a memory is knowing before
576/// you answer" — and that argument was wrong in a way that is easy to see from the outside: a new
577/// session is not new if the first request already carries the last three, chosen by a keyword
578/// match on the prompt. A person who wanted last week's decision to count would say so; a person
579/// starting a fresh topic gets their previous topic pushed at the model, and an agent that reads
580/// `## Recalled from earlier sessions` will anchor on it. `session_search` is the honest form of
581/// the same feature: the model decides it needs the archive, and chooses the query. Recall stays
582/// implemented and stays available — naming it in `order` turns it back on.
583pub const DEFAULT_ORDER: &[&str] = &["redact-secrets"];
584
585/// The `allow` list of `[hooks.redact-secrets]`, validated.
586fn redact_allow(table: &toml::value::Table) -> Result<Vec<String>, String> {
587    let Some(value) = table.get("allow") else {
588        return Ok(Vec::new());
589    };
590    let Some(items) = value.as_array() else {
591        return Err("[hooks.redact-secrets] `allow` must be a list of strings, \
592             e.g. allow = [\"my-fixture-key\"]"
593            .into());
594    };
595    let mut out = Vec::with_capacity(items.len());
596    for item in items {
597        match item.as_str() {
598            Some("") => {
599                return Err(
600                    "[hooks.redact-secrets] `allow` holds an empty string, which would \
601                     exempt nothing and read like it exempts everything; remove it"
602                        .into(),
603                )
604            }
605            Some(text) => out.push(text.to_string()),
606            None => {
607                return Err("[hooks.redact-secrets] `allow` must hold only strings, \
608                     e.g. allow = [\"my-fixture-key\"]"
609                    .into())
610            }
611        }
612    }
613    Ok(out)
614}
615
616fn check_redact_settings(table: &toml::value::Table) -> Result<(), String> {
617    redact_allow(table).map(|_| ())
618}
619
620// ---------------------------------------------------------------------------------------------
621// recall-sessions: the archive as memory
622// ---------------------------------------------------------------------------------------------
623
624/// What `[hooks.recall-sessions]` accepts, with what a bare `[hooks]` gets.
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626pub struct RecallSettings {
627    /// Earlier sessions a single prompt may draw on.
628    pub results: usize,
629    /// Hard cap on the injected text, heading and pointer included.
630    pub budget_chars: usize,
631    /// Prompts shorter than this are not searched: "yes" is not a query.
632    pub min_query_chars: usize,
633    /// Whether a hit in the session being written is allowed. Off by default: this is a
634    /// memory of *earlier* sessions, and the current transcript is already in the request.
635    pub include_this_session: bool,
636}
637
638impl Default for RecallSettings {
639    fn default() -> Self {
640        Self {
641            results: 3,
642            budget_chars: 1_200,
643            min_query_chars: 24,
644            include_this_session: false,
645        }
646    }
647}
648
649fn recall_int(
650    table: &toml::value::Table,
651    key: &str,
652    low: i64,
653    high: i64,
654    what: &str,
655) -> Result<Option<i64>, String> {
656    let Some(value) = table.get(key) else {
657        return Ok(None);
658    };
659    match value.as_integer() {
660        Some(n) if (low..=high).contains(&n) => Ok(Some(n)),
661        _ => Err(format!(
662            "[hooks.recall-sessions] `{key}` {what}, {low} to {high}"
663        )),
664    }
665}
666
667fn recall_settings(table: &toml::value::Table) -> Result<RecallSettings, String> {
668    let mut s = RecallSettings::default();
669    if let Some(n) = recall_int(
670        table,
671        "results",
672        1,
673        8,
674        "is how many earlier sessions a prompt may recall",
675    )? {
676        s.results = n as usize;
677    }
678    if let Some(n) = recall_int(
679        table,
680        "budget_chars",
681        200,
682        8_000,
683        "is the most text a recall may add to a prompt",
684    )? {
685        s.budget_chars = n as usize;
686    }
687    if let Some(n) = recall_int(
688        table,
689        "min_query_chars",
690        0,
691        2_000,
692        "is the shortest prompt worth searching for",
693    )? {
694        s.min_query_chars = n as usize;
695    }
696    if let Some(value) = table.get("include_this_session") {
697        s.include_this_session = value.as_bool().ok_or_else(|| {
698            "[hooks.recall-sessions] `include_this_session` must be true or false".to_string()
699        })?;
700    }
701    Ok(s)
702}
703
704fn check_recall_settings(table: &toml::value::Table) -> Result<(), String> {
705    recall_settings(table).map(|_| ())
706}
707
708/// Words a prompt is searched by: the content words, in the order they were typed.
709///
710/// Deliberately crude. This runs on every prompt, so it is a split, a length filter and a
711/// stopword list — no stemming, no model, nothing that could disagree with itself between two
712/// turns on the same sentence.
713pub fn recall_terms(text: &str) -> Vec<String> {
714    /// Words that carry no topic. Kept short on purpose: a term that slips through costs one
715    /// extra full-text query, a stopword that is missing costs a recall that reads like noise.
716    const STOP: &[&str] = &[
717        "the", "and", "for", "that", "this", "with", "from", "have", "has", "had", "what", "when",
718        "where", "which", "who", "why", "how", "would", "should", "could", "there", "their",
719        "them", "they", "then", "than", "these", "those", "about", "into", "just", "like", "make",
720        "made", "your", "you", "are", "was", "were", "its", "can", "cannot", "not", "but", "all",
721        "any", "one", "two", "out", "use", "using", "used", "get", "got", "need", "want", "please",
722        "thanks", "okay", "also", "still", "now", "did", "does", "done", "back", "over", "only",
723        "some", "more", "most", "such", "been", "being", "because", "before", "after", "again",
724        "here", "very", "much", "should", "shall",
725    ];
726    let mut seen = std::collections::HashSet::new();
727    let mut terms = Vec::new();
728    for word in text.split(|c: char| !c.is_alphanumeric()) {
729        if word.chars().count() < 3 {
730            continue;
731        }
732        let word = word.to_lowercase();
733        if STOP.contains(&word.as_str()) || !seen.insert(word.clone()) {
734            continue;
735        }
736        terms.push(word);
737        if terms.len() == 10 {
738            break;
739        }
740    }
741    terms
742}
743
744/// The archive, read as memory: the closest earlier sessions for this prompt, injected before
745/// the model's first request rather than left for it to ask for.
746///
747/// This is the half of `session_search` that Hermes has and Eclipse did not. A tool the model
748/// may call only helps a model that suspects it should; the point of a memory is that the
749/// agent knows the fact *before* it answers. It is computed — full-text queries over the same
750/// store the agent is already writing, no model call — bounded by `budget_chars` and
751/// `results`, and it fires at `on_completion_call` only when the newest message is the user's,
752/// which is once per prompt and never again for that prompt's tool round-trips.
753pub struct RecallSessions {
754    store: crate::session::SessionStore,
755    settings: RecallSettings,
756    reporting: Reporting,
757    /// Runs already reported, so the note belongs to the run rather than to each turn.
758    announced: std::sync::Mutex<std::collections::HashSet<String>>,
759    /// `once_per_process` reporting: the dashboard says it once, not once per conversation.
760    said_once: std::sync::atomic::AtomicBool,
761}
762
763impl RecallSessions {
764    pub fn new(
765        store: crate::session::SessionStore,
766        settings: RecallSettings,
767        reporting: Reporting,
768    ) -> Self {
769        Self {
770            store,
771            settings,
772            reporting,
773            announced: Default::default(),
774            said_once: Default::default(),
775        }
776    }
777
778    /// The document for this prompt, or `None` when the archive has nothing to say.
779    fn recall(&self, prompt: &str, current: &str) -> Option<(String, usize, usize)> {
780        let terms = recall_terms(prompt);
781        if terms.is_empty() {
782            return None;
783        }
784        // Archived rows included: a match in one is still a match, and the line below names the
785        // session it was found in — an id with no title beside it reads as a deleted session.
786        let listed = self.store.list_with_archived().ok()?;
787        let by_id: std::collections::HashMap<&str, &crate::session::SessionInfo> =
788            listed.iter().map(|s| (s.id.as_str(), s)).collect();
789
790        // Score a row by how many of the prompt's terms it holds. One query per term, merged:
791        // `store.search` takes one query and requires every word in it, which for a whole
792        // prompt would match nothing at all.
793        let mut found: std::collections::HashMap<
794            (String, usize),
795            (usize, crate::session::SearchHit),
796        > = Default::default();
797        for term in &terms {
798            let Ok(hits) = self.store.search(term, 12) else {
799                continue;
800            };
801            for hit in hits {
802                if hit.session_id == current && !self.settings.include_this_session {
803                    continue;
804                }
805                // A subagent session is a job a conversation ran, not a conversation: its rows
806                // are the parent's tools, and recalling them as memory would echo work back.
807                match by_id.get(hit.session_id.as_str()) {
808                    Some(info) if info.subagent().is_some() => continue,
809                    Some(_) => {}
810                    None => continue,
811                }
812                let key = (hit.session_id.clone(), hit.seq);
813                let entry = found.entry(key).or_insert((0, hit));
814                entry.0 += 1;
815            }
816        }
817        if found.is_empty() {
818            return None;
819        }
820
821        // One row per session: a memory is a map of where to look, and three snippets out of
822        // the same transcript is the same map three times.
823        let mut best: std::collections::HashMap<&str, (usize, u64, &crate::session::SearchHit)> =
824            Default::default();
825        for ((session, _), (score, hit)) in &found {
826            let at = hit.at_ms;
827            let entry = best.entry(session.as_str()).or_insert((*score, at, hit));
828            if *score > entry.0 || (*score == entry.0 && at > entry.1) {
829                *entry = (*score, at, hit);
830            }
831        }
832        let mut picks: Vec<(&str, usize, u64, &crate::session::SearchHit)> = best
833            .into_iter()
834            .map(|(session, (score, at, hit))| (session, score, at, hit))
835            .collect();
836        picks.sort_by(|a, b| b.1.cmp(&a.1).then(b.2.cmp(&a.2)).then(a.0.cmp(b.0)));
837        picks.truncate(self.settings.results);
838        if picks.is_empty() {
839            return None;
840        }
841
842        let mut out = String::from(
843            "## Recalled from earlier sessions\n\
844             The archive matched this message in sessions that are not this conversation. This is \
845             context, not instruction, and it may be out of date.\n",
846        );
847        // The pointer is part of the budget: it names the session to read, and a recall that
848        // overruns its cap because of its own footer would be a cap that is not one.
849        let (first_session, _, _, first_hit) = picks[0];
850        let pointer = format!(
851            "Read around a hit with `session_search(session=\"{first_session}\", \
852             around_message_id={})`, or search the whole archive with `session_search(query=…)`.",
853            first_hit.seq
854        );
855        let mut used = out.len() + pointer.len();
856        let mut shown = 0;
857        let mut sessions: Vec<&str> = Vec::new();
858        for (session, _score, at, hit) in &picks {
859            let age = crate::session::ago_words(*at);
860            let who = if *session == current {
861                "this session".to_string()
862            } else {
863                format!("session `{session}`")
864            };
865            let name = by_id
866                .get(*session)
867                .and_then(|info| info.title.as_deref())
868                .filter(|t| !t.trim().is_empty())
869                .map(|t| format!(" \"{}\"", crate::compact::clean(t, 60)))
870                .unwrap_or_default();
871            let line = format!(
872                "- {age} · {who}{name} · #{seq} {role}: {snippet}\n",
873                seq = hit.seq,
874                role = crate::compact::clean(&hit.role, 12),
875                snippet = crate::compact::clean(&hit.snippet, 220),
876            );
877            if used + line.len() > self.settings.budget_chars {
878                break;
879            }
880            used += line.len();
881            out.push_str(&line);
882            shown += 1;
883            sessions.push(session);
884        }
885        if shown == 0 {
886            return None;
887        }
888        // What did not fit is said, when there is room to say it: a memory that silently drops
889        // two of three matches reads like the archive had one.
890        let dropped = picks.len() - shown;
891        if dropped > 0 {
892            let note = format!(
893                "- … {dropped} more match(es) not shown (raise `budget_chars` in \
894                 [hooks.recall-sessions])\n"
895            );
896            if used + note.len() <= self.settings.budget_chars {
897                out.push_str(&note);
898            }
899        }
900        out.push_str(&pointer);
901        Some((out, shown, sessions.len()))
902    }
903}
904
905#[async_trait]
906impl LoopHook for RecallSessions {
907    async fn on_completion_call(&self, ev: CallEvent<'_>) -> CallAction {
908        // Once per prompt. After a tool result the newest message is not the user's, so a
909        // memory injected here cannot be injected again for the same prompt's later turns.
910        let Some(prompt) = ev.messages.last() else {
911            return CallAction::Proceed;
912        };
913        if !matches!(prompt.role, crate::message::Role::User) {
914            return CallAction::Proceed;
915        }
916        let Some(text) = prompt.content.as_deref() else {
917            return CallAction::Proceed;
918        };
919        if text.chars().count() < self.settings.min_query_chars {
920            return CallAction::Proceed;
921        }
922        let Some((document, shown, from)) = self.recall(text, ev.session) else {
923            return CallAction::Proceed;
924        };
925
926        // One announcement per process, or one per run — and the per-run set is only kept in the
927        // mode that needs it. In `once_per_process` a run after the first is never announced, so a
928        // session set there would only grow: one `String` per session ever recalled for, inside a
929        // hook the dashboard holds for days.
930        let announce = if self.reporting.once_per_process {
931            !self
932                .said_once
933                .swap(true, std::sync::atomic::Ordering::SeqCst)
934        } else {
935            self.announced
936                .lock()
937                .unwrap_or_else(std::sync::PoisonError::into_inner)
938                .insert(ev.session.to_string())
939        };
940        if announce {
941            let noun = if shown == 1 { "excerpt" } else { "excerpts" };
942            (self.reporting.sink)(&format!(
943                "note: recall-sessions added {shown} {noun} from {from} earlier session(s) to this \
944                 prompt; [hooks] order turns it off"
945            ));
946        }
947
948        CallAction::Patch(RequestPatch {
949            documents: vec![Message::system(document)],
950            ..Default::default()
951        })
952    }
953}
954
955fn names(known: &[HookInfo]) -> String {
956    known.iter().map(|h| h.name).collect::<Vec<_>>().join(", ")
957}
958
959/// Check `[hooks]` against the hooks `known`, saying what is wrong and what to do about it.
960///
961/// This is the whole of the "no silent ignoring" rule for hooks: the section is read with
962/// `flatten` so that nothing in it is dropped by the parser, and every key is accounted for
963/// here instead.
964pub fn validate_with(section: &HooksConfig, known: &[HookInfo]) -> Result<(), String> {
965    let mut seen: Vec<&str> = Vec::new();
966    for name in &section.order {
967        if !known.iter().any(|h| h.name == name) {
968            return Err(format!(
969                "[hooks] order names `{name}`, which this build does not have. \
970                 Hooks that exist: {}. Fix the name, or remove it from order.",
971                names(known)
972            ));
973        }
974        if seen.contains(&name.as_str()) {
975            return Err(format!(
976                "[hooks] order lists `{name}` twice; a hook runs once per event, so the \
977                 second entry would do nothing. Remove one."
978            ));
979        }
980        seen.push(name);
981    }
982    for (key, value) in &section.settings {
983        let Some(table) = value.as_table() else {
984            return Err(format!(
985                "[hooks] has a key `{key}` that is not a hook table. The only key directly \
986                 under [hooks] is `order`; a hook's settings go in [hooks.<name>]."
987            ));
988        };
989        let Some(info) = known.iter().find(|h| h.name == key) else {
990            return Err(format!(
991                "[hooks.{key}] configures a hook this build does not have. \
992                 Hooks that exist: {}. Fix the name, or delete the table.",
993                names(known)
994            ));
995        };
996        if !seen.contains(&key.as_str()) {
997            return Err(format!(
998                "[hooks.{key}] is configured but `{key}` is not in [hooks] order, so it would \
999                 never run. Add \"{key}\" to order, or delete the table."
1000            ));
1001        }
1002        if info.settings.is_empty() {
1003            return Err(format!(
1004                "[hooks.{key}] is a settings table, but the `{key}` hook takes no settings. \
1005                 Delete the table."
1006            ));
1007        }
1008        if let Some(unknown) = table.keys().find(|k| !info.settings.contains(&k.as_str())) {
1009            return Err(format!(
1010                "[hooks.{key}] has an unknown key `{unknown}`; this hook accepts: {}. \
1011                 Fix the spelling, or delete the key.",
1012                info.settings.join(", ")
1013            ));
1014        }
1015        (info.check)(table)?;
1016    }
1017    Ok(())
1018}
1019
1020/// [`validate_with`] against what this build ships.
1021pub fn validate(section: &HooksConfig) -> Result<(), String> {
1022    validate_with(section, SHIPPED)
1023}
1024
1025/// The `# hooks:` lines `eclipse config show` prints above the section: the order that is in
1026/// effect, and for each hook the loop point it is wired at.
1027pub fn describe(section: &HooksConfig) -> Vec<String> {
1028    if section.order.is_empty() {
1029        return vec![format!(
1030            "# hooks: none (order = []; the default is {:?})",
1031            DEFAULT_ORDER
1032        )];
1033    }
1034    let mut lines = vec![
1035        "# hooks, in run order (redact-secrets is on by default; recall-sessions is available and \
1036         off, because a new session is a new session — the agent reaches the archive through \
1037         `session_search`. `order = []` turns every hook off):"
1038            .to_string(),
1039    ];
1040    for (n, name) in section.order.iter().enumerate() {
1041        let point = SHIPPED
1042            .iter()
1043            .find(|h| h.name == name)
1044            .map_or("(unknown)", |h| h.point);
1045        lines.push(format!("#   {}. {name} @ {point}", n + 1));
1046    }
1047    // A hook that is shipped but not in the order is the one people ask about: it has settings in
1048    // their config and no effect. Naming it here is cheaper than reading hooks.rs.
1049    for hook in SHIPPED {
1050        if !section.order.iter().any(|n| n == hook.name) {
1051            lines.push(format!("#   - {} @ {} (off)", hook.name, hook.point));
1052        }
1053    }
1054    lines
1055}
1056
1057/// Where a hook's one-line report goes, and how often.
1058///
1059/// A filter that rewrites what the model reads without saying so is worse than no filter, so
1060/// `redact-secrets` reports. Where that report is *shown* is the front end's business: the CLI
1061/// has a stderr, the full-screen UI would lose it to the alternate screen, and the dashboard
1062/// is one process serving many runs.
1063#[derive(Clone)]
1064pub struct Reporting {
1065    sink: Arc<dyn Fn(&str) + Send + Sync>,
1066    once_per_process: bool,
1067}
1068
1069impl std::fmt::Debug for Reporting {
1070    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1071        f.debug_struct("Reporting")
1072            .field("once_per_process", &self.once_per_process)
1073            .finish()
1074    }
1075}
1076
1077impl Default for Reporting {
1078    fn default() -> Self {
1079        Self::stderr()
1080    }
1081}
1082
1083impl Reporting {
1084    /// One line on stderr for every run that had something to report.
1085    pub fn stderr() -> Self {
1086        Self::to(Arc::new(|line| eprintln!("{line}")))
1087    }
1088
1089    /// One line on stderr for the whole process: a dashboard serves runs for days, and the
1090    /// same sentence for every one of them would teach its reader to stop reading it.
1091    pub fn stderr_once_per_process() -> Self {
1092        Self {
1093            once_per_process: true,
1094            ..Self::stderr()
1095        }
1096    }
1097
1098    /// Hand each line to `sink`, once per run.
1099    pub fn to(sink: Arc<dyn Fn(&str) + Send + Sync>) -> Self {
1100        Self {
1101            sink,
1102            once_per_process: false,
1103        }
1104    }
1105}
1106
1107/// Build the hooks `[hooks]` names, in the order it names them.
1108///
1109/// The one place a config section becomes hooks, so `run`, the REPL, the full-screen UI, every
1110/// dashboard path and a `delegate` child all get the same ones. It takes the run's store
1111/// because `recall-sessions` reads the archive: a hook that guessed at a directory would be a
1112/// second opinion about where sessions live.
1113pub fn from_config(cfg: &Config, store: &crate::session::SessionStore) -> Result<LoopHooks, Error> {
1114    from_config_reporting(cfg, store, Reporting::default())
1115}
1116
1117/// [`from_config`], with the report going where the caller says.
1118pub fn from_config_reporting(
1119    cfg: &Config,
1120    store: &crate::session::SessionStore,
1121    reporting: Reporting,
1122) -> Result<LoopHooks, Error> {
1123    validate(&cfg.hooks).map_err(Error::Config)?;
1124    let mut built: Vec<Arc<dyn LoopHook>> = Vec::new();
1125    for name in &cfg.hooks.order {
1126        match name.as_str() {
1127            "redact-secrets" => {
1128                let allow = match cfg.hooks.settings.get("redact-secrets") {
1129                    Some(toml::Value::Table(t)) => redact_allow(t).map_err(Error::Config)?,
1130                    _ => Vec::new(),
1131                };
1132                built.push(Arc::new(RedactSecrets::new(allow, reporting.clone())));
1133            }
1134            "recall-sessions" => {
1135                let settings = match cfg.hooks.settings.get("recall-sessions") {
1136                    Some(toml::Value::Table(t)) => recall_settings(t).map_err(Error::Config)?,
1137                    _ => RecallSettings::default(),
1138                };
1139                built.push(Arc::new(RecallSessions::new(
1140                    store.clone(),
1141                    settings,
1142                    reporting.clone(),
1143                )));
1144            }
1145            // `validate` proved every name is one this build ships; a name added to SHIPPED
1146            // without an arm here is caught by the test that builds every shipped hook.
1147            other => {
1148                return Err(Error::Config(format!(
1149                    "[hooks] order names `{other}`, which this build lists but cannot build. \
1150                     This is a bug in Eclipse; remove it from order and report it."
1151                )))
1152            }
1153        }
1154    }
1155    Ok(LoopHooks::new(built))
1156}
1157
1158/// Replaces secrets in tool results before the model reads them, and before they are stored.
1159///
1160/// It sits at `on_outcome` because that is the one place a secret enters the conversation that
1161/// a hook can still stop: the request patch cannot edit messages, and a dispatch hook cannot
1162/// rewrite arguments, so what the user types and what the model writes in a call are not
1163/// scanned.
1164pub struct RedactSecrets {
1165    allow: Vec<String>,
1166    reporting: Reporting,
1167    /// Secrets replaced so far in each run that has not settled yet.
1168    counts: std::sync::Mutex<std::collections::HashMap<String, usize>>,
1169    announced: std::sync::atomic::AtomicBool,
1170}
1171
1172impl RedactSecrets {
1173    pub fn new(allow: Vec<String>, reporting: Reporting) -> Self {
1174        Self {
1175            allow,
1176            reporting,
1177            counts: Default::default(),
1178            announced: Default::default(),
1179        }
1180    }
1181
1182    fn counts(&self) -> std::sync::MutexGuard<'_, std::collections::HashMap<String, usize>> {
1183        self.counts
1184            .lock()
1185            .unwrap_or_else(std::sync::PoisonError::into_inner)
1186    }
1187}
1188
1189#[async_trait]
1190impl LoopHook for RedactSecrets {
1191    async fn on_outcome(&self, ev: Outcome<'_>) -> OutcomeAction {
1192        let found = crate::redact::redact(ev.output, &self.allow);
1193        if found.count == 0 {
1194            return OutcomeAction::Proceed;
1195        }
1196        *self.counts().entry(ev.session.to_string()).or_insert(0) += found.count;
1197        OutcomeAction::ReplaceOutput(found.text)
1198    }
1199
1200    async fn on_run_settled(&self, ev: Settled<'_>) {
1201        let Some(count) = self.counts().remove(ev.session) else {
1202            return;
1203        };
1204        if count == 0 {
1205            return;
1206        }
1207        if self.reporting.once_per_process
1208            && self
1209                .announced
1210                .swap(true, std::sync::atomic::Ordering::SeqCst)
1211        {
1212            return;
1213        }
1214        let noun = if count == 1 { "secret" } else { "secrets" };
1215        let tail = if self.reporting.once_per_process {
1216            "; said once per process, later runs are not reported"
1217        } else {
1218            ""
1219        };
1220        (self.reporting.sink)(&format!(
1221            "note: redact-secrets replaced {count} {noun} in tool output; \
1222             [hooks] order turns it off{tail}"
1223        ));
1224    }
1225}
1226
1227#[cfg(test)]
1228mod tests {
1229    use super::*;
1230
1231    /// A store with nothing in it: the tests that only care about redaction still have to hand the
1232    /// builder one, because `recall-sessions` reads the archive. The directory is owned by the
1233    /// returned store (see `Scratch`), so it is removed when the test statement ends instead of
1234    /// being left in `$TMPDIR`.
1235    fn scratch_store() -> crate::scratch::Scratch<crate::session::SessionStore> {
1236        crate::scratch::Scratch::new("eclipse-hooks-", |path| {
1237            crate::session::SessionStore::new(path.join("sessions"))
1238        })
1239    }
1240
1241    #[test]
1242    fn an_empty_patch_says_so_and_claims_nothing() {
1243        let p = RequestPatch::default();
1244        assert!(p.is_empty());
1245        assert_eq!(p.describe(), "");
1246        let mut q = RequestPatch::default();
1247        q.extra_params
1248            .insert("top_p".into(), serde_json::json!(0.9));
1249        assert!(!q.is_empty());
1250        assert_eq!(q.describe(), "extra_params");
1251    }
1252
1253    #[test]
1254    fn a_later_patch_wins_on_scalars_and_merges_extra_params() {
1255        let mut a = RequestPatch {
1256            temperature: Some(0.2),
1257            max_tokens: Some(100),
1258            extra_params: [("top_p".to_string(), serde_json::json!(0.5))]
1259                .into_iter()
1260                .collect(),
1261            ..Default::default()
1262        };
1263        let b = RequestPatch {
1264            temperature: Some(0.9),
1265            extra_params: [
1266                ("top_p".to_string(), serde_json::json!(0.95)),
1267                ("min_p".to_string(), serde_json::json!(0.05)),
1268            ]
1269            .into_iter()
1270            .collect(),
1271            ..Default::default()
1272        };
1273        a.merge(b);
1274        assert_eq!(a.temperature, Some(0.9), "later wins");
1275        assert_eq!(a.max_tokens, Some(100), "untouched fields survive");
1276        assert_eq!(a.extra_params["top_p"], serde_json::json!(0.95));
1277        assert_eq!(a.extra_params["min_p"], serde_json::json!(0.05));
1278    }
1279
1280    /// Union would let a later hook quietly re-enable what an earlier one forbade, so two
1281    /// allow-lists can only ever narrow each other.
1282    #[test]
1283    fn two_allow_lists_compose_as_an_intersection() {
1284        let mut a = RequestPatch {
1285            active_tools: Some(vec!["read_file".into(), "shell".into(), "fetch".into()]),
1286            ..Default::default()
1287        };
1288        a.merge(RequestPatch {
1289            active_tools: Some(vec!["shell".into(), "write_file".into()]),
1290            ..Default::default()
1291        });
1292        assert_eq!(a.active_tools, Some(vec!["shell".to_string()]));
1293    }
1294
1295    #[test]
1296    fn a_tool_choice_reads_from_config_as_one_string() {
1297        use ToolChoice::*;
1298        assert_eq!(ToolChoice::from_config_str("auto"), Auto);
1299        assert_eq!(ToolChoice::from_config_str(" none "), None);
1300        assert_eq!(ToolChoice::from_config_str("required"), Required);
1301        assert_eq!(
1302            ToolChoice::from_config_str("read_file"),
1303            Function("read_file".into()),
1304            "anything that is not a keyword is a tool name"
1305        );
1306        for choice in [Auto, None, Required, Function("read_file".into())] {
1307            assert_eq!(ToolChoice::from_config_str(choice.as_config_str()), choice);
1308        }
1309    }
1310
1311    #[test]
1312    fn a_tool_choice_reaches_the_wire_in_the_shape_servers_expect() {
1313        assert_eq!(ToolChoice::Auto.to_json(), serde_json::json!("auto"));
1314        assert_eq!(ToolChoice::None.to_json(), serde_json::json!("none"));
1315        assert_eq!(
1316            ToolChoice::Required.to_json(),
1317            serde_json::json!("required")
1318        );
1319        assert_eq!(
1320            ToolChoice::Function("read_file".into()).to_json(),
1321            serde_json::json!({"type": "function", "function": {"name": "read_file"}})
1322        );
1323    }
1324
1325    #[test]
1326    fn documents_concatenate_and_history_is_last_writer_wins() {
1327        let mut a = RequestPatch {
1328            documents: vec![Message::user("first")],
1329            history: Some(vec![Message::user("h1")]),
1330            ..Default::default()
1331        };
1332        a.merge(RequestPatch {
1333            documents: vec![Message::user("second")],
1334            history: Some(vec![Message::user("h2")]),
1335            ..Default::default()
1336        });
1337        assert_eq!(a.documents.len(), 2);
1338        assert_eq!(a.documents[0].content.as_deref(), Some("first"));
1339        assert_eq!(
1340            a.history.as_ref().unwrap()[0].content.as_deref(),
1341            Some("h2")
1342        );
1343
1344        let mut b = RequestPatch::default();
1345        b.merge(RequestPatch {
1346            documents: vec![Message::user("only")],
1347            ..Default::default()
1348        });
1349        assert_eq!(b.documents.len(), 1);
1350        assert!(
1351            b.history.is_none(),
1352            "an absent history leaves the earlier one"
1353        );
1354    }
1355
1356    #[test]
1357    fn documents_and_history_are_described() {
1358        let p = RequestPatch {
1359            documents: vec![Message::user("d")],
1360            history: Some(vec![Message::user("h")]),
1361            ..Default::default()
1362        };
1363        assert!(!p.is_empty());
1364        assert_eq!(p.describe(), "documents, history");
1365    }
1366
1367    #[tokio::test]
1368    async fn a_dispatch_repair_is_returned_and_stop_still_ends_the_chain() {
1369        struct Repair;
1370        #[async_trait]
1371        impl LoopHook for Repair {
1372            async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
1373                DispatchAction::Repair {
1374                    name: "echo".into(),
1375                    arguments: r#"{"text":"fixed"}"#.into(),
1376                }
1377            }
1378        }
1379        let hooks = LoopHooks::new(vec![Arc::new(Repair) as Arc<dyn LoopHook>]);
1380        let got = hooks.dispatch("s", "broken", "not json").await.unwrap();
1381        assert_eq!(got.as_ref().unwrap().name, "echo");
1382        assert_eq!(got.as_ref().unwrap().arguments, r#"{"text":"fixed"}"#);
1383
1384        struct Stop;
1385        #[async_trait]
1386        impl LoopHook for Stop {
1387            async fn on_dispatch(&self, _ev: Dispatch<'_>) -> DispatchAction {
1388                DispatchAction::Stop("no".into())
1389            }
1390        }
1391        let hooks = LoopHooks::new(vec![Arc::new(Stop) as Arc<dyn LoopHook>]);
1392        let err = hooks.dispatch("s", "t", "{}").await.unwrap_err();
1393        assert_eq!(err, "no");
1394    }
1395
1396    #[tokio::test]
1397    async fn an_agent_with_no_hooks_asks_nothing_of_the_loop() {
1398        let hooks = LoopHooks::default();
1399        assert!(hooks.is_empty());
1400        let merged = hooks.completion_call("s", 1, &[], &[]).await.unwrap();
1401        assert!(merged.is_empty());
1402        assert_eq!(
1403            hooks
1404                .run_start(RunStart {
1405                    session: "s",
1406                    prompt: "p"
1407                })
1408                .await,
1409            None
1410        );
1411    }
1412
1413    #[tokio::test]
1414    async fn a_stop_ends_the_chain_so_later_hooks_are_not_consulted() {
1415        struct Stopper;
1416        #[async_trait]
1417        impl LoopHook for Stopper {
1418            async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
1419                CallAction::Stop("no more turns".into())
1420            }
1421        }
1422        struct NeverReached(Arc<std::sync::atomic::AtomicUsize>);
1423        #[async_trait]
1424        impl LoopHook for NeverReached {
1425            async fn on_completion_call(&self, _ev: CallEvent<'_>) -> CallAction {
1426                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1427                CallAction::Proceed
1428            }
1429        }
1430        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1431        let hooks = LoopHooks::new(vec![
1432            Arc::new(Stopper) as Arc<dyn LoopHook>,
1433            Arc::new(NeverReached(counter.clone())),
1434        ]);
1435        let err = hooks.completion_call("s", 1, &[], &[]).await.unwrap_err();
1436        assert_eq!(err, "no more turns");
1437        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 0);
1438    }
1439
1440    fn config(text: &str) -> Config {
1441        Config::from_toml_str(text).unwrap()
1442    }
1443
1444    fn collecting() -> (Reporting, Arc<std::sync::Mutex<Vec<String>>>) {
1445        let lines = Arc::new(std::sync::Mutex::new(Vec::new()));
1446        let sink = lines.clone();
1447        (
1448            Reporting::to(Arc::new(move |l: &str| {
1449                sink.lock().unwrap().push(l.to_string())
1450            })),
1451            lines,
1452        )
1453    }
1454
1455    async fn run_with_secret(hooks: &LoopHooks, session: &str, output: &str) -> String {
1456        let shown = match hooks.outcome(session, "read", output, false, false).await {
1457            OutcomeAction::ReplaceOutput(t) => t,
1458            OutcomeAction::Proceed => output.to_string(),
1459            OutcomeAction::Stop(r) => panic!("unexpected stop: {r}"),
1460        };
1461        hooks
1462            .run_settled(Settled {
1463                session,
1464                turns: 1,
1465                ending: Ending::Answered,
1466            })
1467            .await;
1468        shown
1469    }
1470
1471    const KEY: &str = "sk-abcdefghijklmnopqrstuvwxyz0123";
1472
1473    #[test]
1474    fn an_order_of_nothing_builds_no_hooks_and_the_default_builds_the_default_order() {
1475        assert!(
1476            from_config(&config("[hooks]\norder = []\n"), &scratch_store())
1477                .unwrap()
1478                .is_empty()
1479        );
1480        // An absent `[hooks]` gets exactly `DEFAULT_ORDER`, which is redaction only: recall is
1481        // implemented and available, but off unless `order` names it.
1482        assert_eq!(
1483            from_config(&config(""), &scratch_store()).unwrap().len(),
1484            DEFAULT_ORDER.len()
1485        );
1486        assert_eq!(
1487            from_config(&Config::default(), &scratch_store())
1488                .unwrap()
1489                .len(),
1490            DEFAULT_ORDER.len()
1491        );
1492    }
1493
1494    #[test]
1495    fn building_hooks_from_a_config_that_was_never_validated_still_refuses_it() {
1496        let err =
1497            from_config(&config("[hooks]\norder = [\"nope\"]\n"), &scratch_store()).unwrap_err();
1498        assert!(err.to_string().contains("`nope`"), "{err}");
1499        let err = from_config(
1500            &config("[hooks]\norder = []\n[hooks.redact-secrets]\n"),
1501            &scratch_store(),
1502        )
1503        .unwrap_err();
1504        assert!(err.to_string().contains("never run"), "{err}");
1505    }
1506
1507    // ---- recall-sessions: the archive as memory ------------------------------------------
1508
1509    /// Two sessions: one that talked about the docker bridge, and the one being written now.
1510    fn memory_store() -> crate::session::SessionStore {
1511        let dir = tempfile::tempdir().unwrap();
1512        let store = crate::session::SessionStore::new(dir.keep().join("sessions"));
1513        store
1514            .append(
1515                "earlier",
1516                &Message::user("the docker bridge address for the host is 172.17.0.1"),
1517            )
1518            .unwrap();
1519        store.rename("earlier", "bridge notes").unwrap();
1520        store
1521            .append(
1522                "current",
1523                &Message::user("which address does the container use for the host?"),
1524            )
1525            .unwrap();
1526        store
1527    }
1528
1529    const PROMPT: &str = "which address does the container use for the host?";
1530
1531    fn call_event<'a>(session: &'a str, messages: &'a [Message]) -> CallEvent<'a> {
1532        CallEvent {
1533            session,
1534            turn: 1,
1535            messages,
1536            tools: &[],
1537        }
1538    }
1539
1540    fn quiet() -> Reporting {
1541        Reporting::to(Arc::new(|_| {}))
1542    }
1543
1544    #[tokio::test]
1545    async fn the_recall_hook_puts_an_earlier_session_in_front_of_the_model() {
1546        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), quiet());
1547        let messages = vec![Message::system("you are eclipse"), Message::user(PROMPT)];
1548        let action = hook
1549            .on_completion_call(call_event("current", &messages))
1550            .await;
1551        let CallAction::Patch(patch) = action else {
1552            panic!("a prompt that matches the archive has to be answered with a patch");
1553        };
1554        assert_eq!(patch.documents.len(), 1, "one document, not one per hit");
1555        let text = patch.documents[0].content.clone().unwrap_or_default();
1556        assert!(
1557            text.starts_with("## Recalled from earlier sessions"),
1558            "{text}"
1559        );
1560        assert!(
1561            text.contains("session `earlier`"),
1562            "the session is named: {text}"
1563        );
1564        assert!(text.contains("bridge notes"), "and so is its title: {text}");
1565        assert!(
1566            text.contains("docker bridge address"),
1567            "with the text: {text}"
1568        );
1569        assert!(
1570            text.contains("session_search(session=\"earlier\""),
1571            "and the way to read around it: {text}"
1572        );
1573        assert!(
1574            !text.contains("session `current`"),
1575            "the conversation being written is not its own memory: {text}"
1576        );
1577    }
1578
1579    #[tokio::test]
1580    async fn a_recall_can_be_told_to_include_the_session_it_is_writing() {
1581        let settings = RecallSettings {
1582            include_this_session: true,
1583            ..Default::default()
1584        };
1585        let hook = RecallSessions::new(memory_store(), settings, quiet());
1586        let messages = vec![Message::system("sys"), Message::user(PROMPT)];
1587        let CallAction::Patch(patch) = hook
1588            .on_completion_call(call_event("current", &messages))
1589            .await
1590        else {
1591            panic!("expected a patch");
1592        };
1593        let text = patch.documents[0].content.clone().unwrap_or_default();
1594        assert!(text.contains("this session"), "{text}");
1595        assert!(
1596            text.contains("session `earlier`"),
1597            "and the earlier one is still there: {text}"
1598        );
1599    }
1600
1601    #[tokio::test]
1602    async fn a_short_prompt_is_not_a_query_and_a_tool_result_is_not_a_prompt() {
1603        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), quiet());
1604        let short = vec![Message::system("sys"), Message::user("go on")];
1605        assert_eq!(
1606            hook.on_completion_call(call_event("current", &short)).await,
1607            CallAction::Proceed,
1608            "\"go on\" is not a search"
1609        );
1610
1611        // After a tool result the newest message is not the user's: the memory was injected on
1612        // the turn's first call and must not be injected again for this prompt.
1613        let mid_turn = vec![
1614            Message::system("sys"),
1615            Message::user(PROMPT),
1616            Message::tool_result("c1", "ok"),
1617        ];
1618        assert_eq!(
1619            hook.on_completion_call(call_event("current", &mid_turn))
1620                .await,
1621            CallAction::Proceed,
1622            "a tool round-trip is not a new prompt"
1623        );
1624    }
1625
1626    #[tokio::test]
1627    async fn a_recall_that_matches_nothing_says_nothing() {
1628        let hook = RecallSessions::new(
1629            memory_store(),
1630            RecallSettings {
1631                min_query_chars: 0,
1632                ..Default::default()
1633            },
1634            quiet(),
1635        );
1636        let messages = vec![
1637            Message::system("sys"),
1638            Message::user("zebra xylophone quokka"),
1639        ];
1640        assert_eq!(
1641            hook.on_completion_call(call_event("current", &messages))
1642                .await,
1643            CallAction::Proceed
1644        );
1645    }
1646
1647    #[tokio::test]
1648    async fn a_recall_stays_inside_its_budget_including_its_pointer() {
1649        let messages = vec![Message::system("sys"), Message::user(PROMPT)];
1650
1651        // Smaller than the heading plus the pointer: nothing fits, so nothing is injected
1652        // rather than a document that breaks its own cap.
1653        let tight = RecallSessions::new(
1654            memory_store(),
1655            RecallSettings {
1656                budget_chars: 320,
1657                ..Default::default()
1658            },
1659            quiet(),
1660        );
1661        assert_eq!(
1662            tight
1663                .on_completion_call(call_event("current", &messages))
1664                .await,
1665            CallAction::Proceed
1666        );
1667
1668        let roomy = RecallSessions::new(
1669            memory_store(),
1670            RecallSettings {
1671                budget_chars: 900,
1672                results: 8,
1673                ..Default::default()
1674            },
1675            quiet(),
1676        );
1677        let CallAction::Patch(patch) = roomy
1678            .on_completion_call(call_event("current", &messages))
1679            .await
1680        else {
1681            panic!("expected a patch");
1682        };
1683        let text = patch.documents[0].content.clone().unwrap_or_default();
1684        assert!(
1685            text.chars().count() <= 900,
1686            "{} chars over a 900 cap: {text}",
1687            text.chars().count()
1688        );
1689        assert!(
1690            text.contains("session_search(session="),
1691            "the pointer is inside the cap, not appended after it: {text}"
1692        );
1693        assert!(text.contains("bridge notes"), "{text}");
1694    }
1695
1696    #[tokio::test]
1697    async fn a_recall_setting_outside_its_range_is_refused_with_the_bounds() {
1698        let mut table = toml::value::Table::new();
1699        table.insert("results".to_string(), toml::Value::Integer(99));
1700        let err = check_recall_settings(&table).unwrap_err();
1701        assert!(err.contains("`results`") && err.contains("1 to 8"), "{err}");
1702
1703        let mut table = toml::value::Table::new();
1704        table.insert(
1705            "include_this_session".to_string(),
1706            toml::Value::String("yes".to_string()),
1707        );
1708        let err = check_recall_settings(&table).unwrap_err();
1709        assert!(err.contains("true or false"), "{err}");
1710    }
1711
1712    #[test]
1713    fn a_prompt_is_searched_by_its_content_words() {
1714        let terms = recall_terms("Which address does the container use for the HOST, again?");
1715        assert!(
1716            terms.contains(&"address".to_string())
1717                && terms.contains(&"container".to_string())
1718                && terms.contains(&"host".to_string()),
1719            "{terms:?}"
1720        );
1721        assert!(
1722            !terms.contains(&"the".to_string()) && !terms.contains(&"does".to_string()),
1723            "stopwords are not terms: {terms:?}"
1724        );
1725        assert!(
1726            recall_terms("ok").is_empty(),
1727            "a two-letter word is not a query"
1728        );
1729        assert_eq!(
1730            recall_terms(&"alpha ".repeat(20)).len(),
1731            1,
1732            "duplicates collapse"
1733        );
1734    }
1735
1736    #[test]
1737    fn every_hook_this_build_ships_can_be_built_and_names_a_point() {
1738        for info in SHIPPED {
1739            let cfg = config(&format!("[hooks]\norder = [\"{}\"]\n", info.name));
1740            assert_eq!(
1741                from_config(&cfg, &scratch_store()).unwrap().len(),
1742                1,
1743                "{}",
1744                info.name
1745            );
1746            assert!(info.point.starts_with("on_"), "{}", info.name);
1747        }
1748    }
1749
1750    #[test]
1751    fn a_hook_that_takes_no_settings_refuses_a_settings_table() {
1752        fn accept_anything(_: &toml::value::Table) -> Result<(), String> {
1753            Ok(())
1754        }
1755        let known = [HookInfo {
1756            name: "plain",
1757            point: "on_outcome",
1758            settings: &[],
1759            check: accept_anything,
1760        }];
1761        let ok = config("[hooks]\norder = [\"plain\"]\n");
1762        assert!(validate_with(&ok.hooks, &known).is_ok());
1763        let bad = config("[hooks]\norder = [\"plain\"]\n[hooks.plain]\nallow = []\n");
1764        let err = validate_with(&bad.hooks, &known).unwrap_err();
1765        assert!(err.contains("takes no settings"), "{err}");
1766        assert!(err.contains("Delete the table"), "{err}");
1767    }
1768
1769    #[test]
1770    fn config_show_names_the_order_and_the_point_each_hook_is_wired_at() {
1771        // Recall is available but not default: the header says which hooks are on and which
1772        // are merely known, so `config show` answers "why did a new session have old text in
1773        // it" without reading this file.
1774        let on = describe(&Config::default().hooks);
1775        assert!(
1776            on[0].contains("redact-secrets is on by default") && on[0].contains("recall-sessions"),
1777            "{on:?}"
1778        );
1779        assert_eq!(on[1], "#   1. redact-secrets @ on_outcome");
1780        assert_eq!(on[2], "#   - recall-sessions @ on_completion_call (off)");
1781        // Naming it in `order` turns it on, and the describe line stops saying `(off)`.
1782        let back_on = describe(&config("[hooks]\norder = [\"recall-sessions\"]\n").hooks);
1783        assert_eq!(back_on[1], "#   1. recall-sessions @ on_completion_call");
1784        let off = describe(&config("[hooks]\norder = []\n").hooks);
1785        assert_eq!(off.len(), 1);
1786        assert!(off[0].starts_with("# hooks: none"), "{off:?}");
1787        assert!(
1788            off[0].contains("the default is [\"redact-secrets\"]"),
1789            "{off:?}"
1790        );
1791    }
1792
1793    #[tokio::test]
1794    async fn redact_secrets_replaces_a_secret_in_a_tool_result_and_leaves_the_rest() {
1795        let hooks = from_config_reporting(&config(""), &scratch_store(), collecting().0).unwrap();
1796        let shown = run_with_secret(&hooks, "s", &format!("key is {KEY} ok")).await;
1797        assert_eq!(shown, "key is [redacted:api-key] ok");
1798    }
1799
1800    #[tokio::test]
1801    async fn a_result_with_nothing_to_redact_is_not_replaced_at_all() {
1802        let hooks = from_config_reporting(&config(""), &scratch_store(), collecting().0).unwrap();
1803        let action = hooks
1804            .outcome(
1805                "s",
1806                "read",
1807                "2024-01-01 INFO listening on :8080",
1808                false,
1809                false,
1810            )
1811            .await;
1812        assert_eq!(action, OutcomeAction::Proceed);
1813    }
1814
1815    #[tokio::test]
1816    async fn an_allowed_literal_is_not_redacted_and_not_reported() {
1817        let cfg = config(&format!("[hooks.redact-secrets]\nallow = [\"{KEY}\"]\n"));
1818        let (reporting, lines) = collecting();
1819        let hooks = from_config_reporting(&cfg, &scratch_store(), reporting).unwrap();
1820        let text = format!("fixture {KEY}");
1821        assert_eq!(run_with_secret(&hooks, "s", &text).await, text);
1822        assert!(lines.lock().unwrap().is_empty());
1823    }
1824
1825    #[tokio::test]
1826    async fn the_report_comes_once_per_run_and_counts_every_secret_in_it() {
1827        let (reporting, lines) = collecting();
1828        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
1829        // Two results in one run, then settle: one line.
1830        let first = hooks
1831            .outcome("s", "read", &format!("a {KEY}"), false, false)
1832            .await;
1833        assert!(matches!(first, OutcomeAction::ReplaceOutput(_)));
1834        run_with_secret(&hooks, "s", &format!("b {KEY} and password=hunter2hunter2")).await;
1835        assert_eq!(
1836            lines.lock().unwrap().as_slice(),
1837            ["note: redact-secrets replaced 3 secrets in tool output; [hooks] order turns it off"]
1838        );
1839        // A clean run says nothing; the next run with a secret says it again.
1840        run_with_secret(&hooks, "t", "nothing here").await;
1841        assert_eq!(lines.lock().unwrap().len(), 1);
1842        run_with_secret(&hooks, "u", KEY).await;
1843        let lines = lines.lock().unwrap();
1844        assert_eq!(lines.len(), 2);
1845        assert!(lines[1].contains("replaced 1 secret in"), "{}", lines[1]);
1846    }
1847
1848    #[tokio::test]
1849    async fn the_report_of_a_long_lived_process_comes_once_not_once_per_run() {
1850        let lines = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
1851        let sink = lines.clone();
1852        let mut reporting = Reporting::to(Arc::new(move |l: &str| {
1853            sink.lock().unwrap().push(l.to_string())
1854        }));
1855        reporting.once_per_process = true;
1856        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
1857        for session in ["a", "b", "c"] {
1858            run_with_secret(&hooks, session, KEY).await;
1859        }
1860        let lines = lines.lock().unwrap();
1861        assert_eq!(lines.len(), 1);
1862        assert!(lines[0].contains("said once per process"), "{}", lines[0]);
1863    }
1864
1865    /// `once_per_process` needs no per-session set: after the first run nothing is announced, so the
1866    /// set could only grow — one `String` per session recalled for, in a hook held for days.
1867    #[tokio::test]
1868    async fn once_per_process_announces_once_and_remembers_no_sessions() {
1869        let (mut reporting, lines) = collecting();
1870        reporting.once_per_process = true;
1871        let hook = RecallSessions::new(memory_store(), RecallSettings::default(), reporting);
1872
1873        for session in ["current", "other", "third"] {
1874            let messages = vec![Message::system("you are eclipse"), Message::user(PROMPT)];
1875            let action = hook
1876                .on_completion_call(call_event(session, &messages))
1877                .await;
1878            assert!(
1879                matches!(action, CallAction::Patch(_)),
1880                "every prompt still gets its patch — suppressing the note must not suppress the memory"
1881            );
1882        }
1883
1884        assert_eq!(lines.lock().unwrap().len(), 1, "one line for the process");
1885        assert!(
1886            hook.announced.lock().unwrap().is_empty(),
1887            "and no session set: {:?}",
1888            hook.announced.lock().unwrap()
1889        );
1890    }
1891
1892    #[tokio::test]
1893    async fn two_runs_at_once_are_counted_apart() {
1894        let (reporting, lines) = collecting();
1895        let hooks = from_config_reporting(&config(""), &scratch_store(), reporting).unwrap();
1896        let _ = hooks.outcome("a", "read", KEY, false, false).await;
1897        run_with_secret(&hooks, "b", "clean").await;
1898        assert!(
1899            lines.lock().unwrap().is_empty(),
1900            "b must not report a's secret"
1901        );
1902        run_with_secret(&hooks, "a", "clean").await;
1903        assert_eq!(lines.lock().unwrap().len(), 1);
1904    }
1905}