eclipse_core/approvals.rs
1//! Durable approvals: the pending tool calls of a run, and the answer when it arrives.
2//!
3//! The approval gate is normally a question asked of whoever is driving the loop, and its answer
4//! exists only in that process. That is fine until the process is not there — a CLI run in a
5//! script, a dashboard tab that was closed, a shell that lost its terminal — and then a call the
6//! model made is neither approved nor denied: it is simply unrecorded, and the transcript repairs
7//! it on the next run as "interrupted". The intent is lost.
8//!
9//! This module is the small amount of state that fixes it, and deliberately nothing more: one row
10//! per call the model made and the gate has not answered, keyed by the message that carried it
11//! (`seq`, `ord`), with the answer written into the same row when it arrives. There is no second
12//! state machine, no run registry and no job queue — a *run* is still just a transcript, and the
13//! rows are only the answers that were not in it yet.
14//!
15//! Three answers, not two:
16//!
17//! - [`Decision::Allow`] runs the call;
18//! - [`Decision::Deny`] answers it as declined, with the reason the model reads;
19//! - [`Decision::Defer`] means *nobody has answered and the loop must not guess*. The call is
20//! recorded and the turn stops. Fail-closed: an unanswered gate is never an approval, and it is
21//! no longer a silent denial either.
22//!
23//! `Defer` is what makes the state durable without a daemon: the process that asked can exit, and
24//! any later process can look at the same rows and answer them.
25
26use crate::session::SessionStore;
27use crate::Result;
28
29/// Who answered a waiting call, for the `by` column (`#340`).
30///
31/// `user` is every answer that came through a person — `eclipse approve`, a card, a dashboard
32/// button. `judge` is the aux route in `smart` mode. `policy` is reserved for a call a rule
33/// settled without either, so the column's vocabulary is fixed before anything writes a third word.
34pub const DECIDED_BY_USER: &str = "user";
35/// The aux route in `smart` mode (`#340`).
36pub const DECIDED_BY_JUDGE: &str = "judge";
37
38/// One call the model made, as the gate sees it: enough to ask, enough to re-run it later.
39#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
40pub struct Pending {
41 /// The model's id for this call, which is also how its result is matched back.
42 pub call_id: String,
43 pub tool: String,
44 /// The one-liner the gate shows a human (`Tool::describe_call`).
45 pub summary: String,
46 /// The arguments as the call will run: what the model wrote, unless an `on_dispatch` hook
47 /// repaired it before the gate saw it. This row — not the transcript — is what a resumed run
48 /// replays, so it is what the human is shown and what actually happens.
49 pub args: String,
50}
51
52impl Pending {
53 pub fn new(
54 call_id: impl Into<String>,
55 tool: impl Into<String>,
56 summary: String,
57 args: String,
58 ) -> Self {
59 Self {
60 call_id: call_id.into(),
61 tool: tool.into(),
62 summary,
63 args,
64 }
65 }
66}
67
68/// The gate's answer to one call.
69#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
70#[serde(rename_all = "snake_case")]
71pub enum Decision {
72 Allow,
73 /// Declined, with the reason the model reads as the tool result. A denial is information:
74 /// "the user declined" without a why teaches the model nothing.
75 Deny(String),
76 /// Not answered yet. The loop stops rather than deciding on the user's behalf.
77 Defer,
78}
79
80impl Decision {
81 /// How this answer is stored. `Defer` has no row value: a call with no decision *is* deferred,
82 /// and storing "deferred" would make "waiting" look like an answer that had arrived.
83 pub fn store(&self) -> Option<String> {
84 match self {
85 Decision::Allow => Some("allow".to_string()),
86 Decision::Deny(reason) => Some(format!("deny:{reason}")),
87 Decision::Defer => None,
88 }
89 }
90
91 /// The inverse of [`store`](Self::store), for a row that has a decision column set.
92 ///
93 /// Fails closed (`#427`). This used to read anything without a `deny:` prefix as Allow, so a
94 /// row this build did not write — an older scheme, a higher version's word, a hand-edited
95 /// `state.db` — became an approval for a call nobody approved. An unknown answer is a denial
96 /// that says what it did not understand; the only way to allow is to say `allow`.
97 pub fn parse(stored: &str) -> Self {
98 match stored.strip_prefix("deny:") {
99 Some(reason) => Decision::Deny(reason.to_string()),
100 None if stored == "allow" => Decision::Allow,
101 None => Decision::Deny(format!(
102 "the stored answer {stored:?} is not one this build understands, so the call was \
103 not run"
104 )),
105 }
106 }
107}
108
109/// One line of the append-only log: a call, its answer, and who gave it (`#340`).
110///
111/// The waiting rows in `approvals` are deleted as soon as the answer reaches the transcript, so
112/// this is what a later reader has: "what did the model wave through last week" is a query over
113/// these, and it is answerable because nothing removes them.
114#[derive(Debug, Clone, PartialEq, serde::Serialize)]
115pub struct Ruling {
116 pub at_ms: i64,
117 pub call_id: String,
118 pub tool: String,
119 pub summary: String,
120 pub decision: Decision,
121 pub by: String,
122}
123
124/// One stored row: a call, and the answer if one arrived.
125#[derive(Debug, Clone, PartialEq, serde::Serialize)]
126pub struct PendingCall {
127 /// The `seq` of the assistant message that carried the call.
128 pub seq: i64,
129 /// Its position within that message, so two calls can never collide on one row.
130 pub ord: usize,
131 pub call: Pending,
132 pub decision: Option<Decision>,
133 pub decided_ms: Option<i64>,
134 /// Who answered: `user`, `judge` or `policy` (`#340`). `None` for a row that has no answer
135 /// yet, and for one written before the column existed — nobody recorded it, and saying so is
136 /// better than guessing a name.
137 pub by: Option<String>,
138}
139
140impl PendingCall {
141 pub fn is_waiting(&self) -> bool {
142 self.decision.is_none()
143 }
144}
145
146/// What a run left behind when it stopped on the gate.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Waiting {
149 pub session: String,
150 /// How many calls are waiting for an answer.
151 pub calls: usize,
152}
153
154impl Waiting {
155 /// The line a human needs: what is waiting and the command that resolves it.
156 pub fn hint(&self) -> String {
157 format!(
158 "{} tool call(s) in {} waiting for an answer; run `eclipse approve {} --all` \
159 (or `--index N`, `--deny <reason>`) to resolve them",
160 self.calls, self.session, self.session
161 )
162 }
163}
164
165/// Record the calls of one assistant message as pending. An existing row is left alone: the same
166/// call re-recorded has the same answer or none, and overwriting it would lose a decision that
167/// arrived while the run was stopping.
168pub fn record(store: &SessionStore, session: &str, seq: i64, calls: &[Pending]) -> Result<()> {
169 store.record_pending(session, seq, calls)
170}
171
172/// Record `calls` as pending, starting at `ord` — the position `calls[0]` holds in the assistant
173/// message that carried it.
174///
175/// A caller that records a turn's deferred calls one at a time must pass each call's own position.
176/// `ord` is half the row's key, so writing them all at 0 makes the second one collide with the
177/// first and `ON CONFLICT DO NOTHING` drops it (#547).
178pub fn record_at(
179 store: &SessionStore,
180 session: &str,
181 seq: i64,
182 ord: usize,
183 calls: &[Pending],
184) -> Result<()> {
185 store.record_pending_at(session, seq, ord, calls)
186}
187
188/// The calls waiting for an answer, oldest first.
189pub fn waiting(store: &SessionStore, session: &str) -> Result<Vec<PendingCall>> {
190 Ok(store
191 .pending_calls(session)?
192 .into_iter()
193 .filter(PendingCall::is_waiting)
194 .collect())
195}
196
197/// Answer one waiting call by position, counting from 1 in the order `waiting` prints them.
198pub fn answer(
199 store: &SessionStore,
200 session: &str,
201 index: usize,
202 decision: &Decision,
203) -> Result<()> {
204 let waiting = waiting(store, session)?;
205 // `--index 0` used to be `saturating_sub(1)` == 0, so it silently answered the *first* call: an
206 // operator asking for nothing got the one thing they did not ask for (`#427`). The numbers a
207 // person sees in `eclipse approve` start at 1.
208 let Some(position) = index.checked_sub(1) else {
209 return Err(crate::Error::Session(
210 "call numbers start at 1: there is no call 0 to answer".into(),
211 ));
212 };
213 let Some(row) = waiting.get(position) else {
214 return Err(crate::Error::Session(format!(
215 "there is no waiting call {index} in {session}: {} waiting",
216 waiting.len()
217 )));
218 };
219 store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)
220}
221
222/// Answer every waiting call.
223pub fn answer_all(store: &SessionStore, session: &str, decision: &Decision) -> Result<usize> {
224 let waiting = waiting(store, session)?;
225 for row in &waiting {
226 store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)?;
227 }
228 Ok(waiting.len())
229}
230
231/// What the store says about one call. Used by the resumed run, which must run exactly what was
232/// approved and nothing else.
233///
234/// Three answers, not two: `None` is no row at all — a call the resumed tool made itself, which is
235/// a new question — and `Some(None)` is a row nobody has answered. Collapsing them made an
236/// unanswered row reach the live gate, which is the opposite of failing closed (`#556`).
237pub fn decision_for(
238 store: &SessionStore,
239 session: &str,
240 call_id: &str,
241) -> Result<Option<Option<Decision>>> {
242 Ok(store
243 .pending_calls(session)?
244 .into_iter()
245 .find(|row| row.call.call_id == call_id)
246 .map(|row| row.decision))
247}
248
249/// The store's answers, asked of the gate that replays a paused turn.
250///
251/// A resumed call is not asked of the user again: the answer is already in the row. But a call the
252/// resumed tool makes *itself* — a subagent's, or one a router re-dispatches — is a new decision
253/// with no row, and that one goes to the live gate as usual rather than being waved through by
254/// association. `Defer` for a row that has gone missing is the fail-closed answer: the transcript
255/// says this call was waiting, so nothing else may stand in for the answer.
256pub struct Recorded<'a> {
257 store: &'a SessionStore,
258 session: &'a str,
259 inner: &'a dyn crate::tools::Approver,
260}
261
262impl<'a> Recorded<'a> {
263 pub fn new(
264 store: &'a SessionStore,
265 session: &'a str,
266 inner: &'a dyn crate::tools::Approver,
267 ) -> Self {
268 Self {
269 store,
270 session,
271 inner,
272 }
273 }
274}
275
276#[async_trait::async_trait]
277impl crate::tools::Approver for Recorded<'_> {
278 async fn decide(&self, call: &Pending) -> Decision {
279 match decision_for(self.store, self.session, &call.call_id) {
280 Ok(Some(Some(decision))) => decision,
281 // The row exists and has no answer: the transcript says a person was asked, so nothing
282 // else may answer for them (#556).
283 Ok(Some(None)) => Decision::Defer,
284 // No row at all: a call the resumed tool made itself, which is a new question.
285 Ok(None) => self.inner.decide(call).await,
286 Err(_) => Decision::Defer,
287 }
288 }
289}
290
291#[cfg(test)]
292mod tests;