eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! `#657`: the `plan` tool — one list of steps, kept in the session, read back by every surface.
//!
//! The registry is every kind of act and not one of them held a plan, so compaction's only option
//! was to guess at one: `THREAD_WORDS` harvested lines that happened to contain "todo" or "still
//! need" into *Open Threads*, and the order was rebuilt from the last few messages each turn. On a
//! job with eight steps that is the difference between a list and a sample of sentences.
//!
//! This tool is deliberately the smallest thing that fixes that. It writes one row in the store the
//! session already owns — no file, no network, no process — which is also why it has no `Policy`
//! key in `ToolsConfig` and is registered unconditionally: a gate would have nothing to refuse, and
//! a new policy field is exactly what `#586`'s family of preset bugs invites. Hermes's todo tool is
//! registered the same way, and for the same reason.
//!
//! The rules live in [`crate::plans`], not here: this file parses arguments and renders the answer.
//! What it does *not* do is decide what a merge means or how many steps may be in progress, so
//! those two questions have one answer that a test can reach.

use crate::plans::{self, Plan, Status};
use crate::session::SessionStore;
use crate::tools::{CallScope, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};

pub struct PlanTool {
    store: SessionStore,
}

impl PlanTool {
    pub fn new(store: SessionStore) -> Self {
        Self { store }
    }

    /// The steps in an argument, or `None` when the caller wants to read.
    ///
    /// `items` absent is a read; `items: []` is a write that clears the plan. The two look alike in
    /// a diff of the arguments and are opposite in effect, so they are decided here once.
    fn parse_items(&self, args: &Value) -> Result<Option<Vec<crate::plans::Item>>, ToolError> {
        let Some(raw) = args.get("items") else {
            return Ok(None);
        };
        let list = raw.as_array().ok_or_else(|| {
            ToolError::InvalidArgs(
                "`items` must be a list of steps, or left out to read".to_string(),
            )
        })?;
        let mut items = Vec::with_capacity(list.len());
        for (index, entry) in list.iter().enumerate() {
            let position = index + 1;
            let object = entry.as_object().ok_or_else(|| {
                ToolError::InvalidArgs(format!("item {position} is not an object"))
            })?;
            let text = |key: &str| -> Result<String, ToolError> {
                match object.get(key) {
                    Some(Value::String(s)) => Ok(s.clone()),
                    Some(_) => Err(ToolError::InvalidArgs(format!(
                        "item {position}: `{key}` must be a string"
                    ))),
                    None if key == "content" => Ok(String::new()),
                    None => Ok(String::new()),
                }
            };
            let id = text("id")?;
            let content = text("content")?;
            let status = match object.get("status") {
                None | Some(Value::Null) => Status::Pending,
                Some(Value::String(word)) => Status::parse(word).ok_or_else(|| {
                    ToolError::InvalidArgs(format!(
                        "item {position} (`{id}`): `{word}` is not a status; use `pending`, \
                         `in_progress`, `done` or `cancelled`"
                    ))
                })?,
                Some(_) => {
                    return Err(ToolError::InvalidArgs(format!(
                        "item {position}: `status` must be a word"
                    )))
                }
            };
            let parent = match object.get("parent") {
                None | Some(Value::Null) => None,
                Some(Value::String(p)) if p.trim().is_empty() => None,
                Some(Value::String(p)) => Some(p.clone()),
                Some(_) => {
                    return Err(ToolError::InvalidArgs(format!(
                        "item {position}: `parent` must be the id of another step"
                    )))
                }
            };
            items.push(crate::plans::Item {
                id,
                content,
                status,
                parent,
            });
        }
        Ok(Some(items))
    }

    fn render(&self, plan: &Plan, demoted: &[String]) -> String {
        let counts = plan.counts();
        let (finished, total) = plan.progress();
        let mut out = format!("plan {finished}/{total}");
        match plan.current() {
            Some(current) => out.push_str(&format!(" · next {}", current.id)),
            None if total > 0 => out.push_str(" · none in progress"),
            None => {}
        }
        if plan.items.is_empty() {
            out.push_str("\n(no steps)");
        }
        for item in &plan.items {
            // The panel a surface draws is its own business; this is the list a model reads back,
            // so it is one line per step with the status in one column.
            out.push_str(&format!(
                "\n{} {} {}",
                item.status.mark(),
                item.id,
                item.content
            ));
            if let Some(parent) = &item.parent {
                out.push_str(&format!(" (in {parent})"));
            }
        }
        if !demoted.is_empty() {
            out.push_str(&format!(
                "\nonly one step can be `in_progress`: {} demoted to `pending` ({})",
                if demoted.len() == 1 {
                    "it was"
                } else {
                    "they were"
                },
                demoted.join(", ")
            ));
        }
        out.push_str(&format!(
            "\nrevision {} · {} pending, {} in progress, {} done, {} cancelled",
            plan.revision, counts.pending, counts.in_progress, counts.done, counts.cancelled
        ));
        out
    }
}

#[async_trait]
impl Tool for PlanTool {
    fn name(&self) -> &str {
        "plan"
    }

    fn description(&self) -> &str {
        "Keep the list of steps for the job in hand: what is left, in what order, and which step \
         is being done now. Call it with `items` to write, or omit `items` to read the list back. \
         List order is priority; exactly one step may be `in_progress` (a second is demoted to \
         `pending` and the result says which); `merge: true` patches steps by `id` instead of \
         replacing the whole list; `parent` puts a step inside a phase. Statuses: pending, \
         in_progress, done, cancelled. On a job with many parts, write one item per part so none \
         is silently dropped, and keep the list current as you go — it is what survives a \
         compaction."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "items":{"type":"array","description":"The whole list, in priority order. Omit to read. An empty list clears the plan.","items":{"type":"object","properties":{
                "id":{"type":"string","description":"A short unique id for the step, for example `#550` or `tests`. A merge patches by this."},
                "content":{"type":"string","description":"What the step is, in one line."},
                "status":{"type":"string","description":"pending, in_progress, done or cancelled. Default pending."},
                "parent":{"type":"string","description":"The id of the phase this step belongs to, if any."}
            },"required":["id","content"]}},
            "merge":{"type":"boolean","description":"Patch the steps named by `id` and append the new ones, instead of replacing the list. Default false."}
        }})
    }

    /// A plan writes one row in the session's own store and nothing else, so there is nothing to
    /// ask about. The policy is `allow` for the same reason; this makes the answer explicit.
    fn needs_approval(&self, _args: &Value) -> bool {
        false
    }

    fn describe_call(&self, args: &Value) -> String {
        match args.get("items").and_then(Value::as_array) {
            Some(items) => format!("plan · {} step(s)", items.len()),
            None => "plan · read".to_string(),
        }
    }

    /// A plan belongs to a session and only a run knows which one, so every dispatch arrives
    /// through [`Self::call_scoped`]. This form exists because the trait requires it: answering the
    /// question with an empty session would write a plan nobody can find.
    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "`plan` keeps a list per session, and this call names none".to_string(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let session = scope.run.session.clone();
        let Some(incoming) = self.parse_items(&args)? else {
            return match self.store.plan(&session).map_err(failed)? {
                Some(plan) => Ok(self.render(&plan, &[])),
                None => Ok(
                    "no plan in this session yet — call `plan` with `items` to write the steps"
                        .to_string(),
                ),
            };
        };
        // Refused before anything is written: a list with an empty step is a list that cannot be
        // worked, and a write that half-landed would leave the previous plan gone.
        plans::validate(&incoming).map_err(ToolError::InvalidArgs)?;
        let merge = args.get("merge").and_then(Value::as_bool).unwrap_or(false);
        let existing = self.store.plan(&session).map_err(failed)?;
        let mut items = match (merge, existing) {
            (true, Some(plan)) => plans::merge(&plan.items, &incoming),
            // A merge against no plan is a write: there is nothing to patch.
            _ => incoming,
        };
        let demoted = plans::one_in_progress(&mut items);
        let revision = self.store.set_plan(&session, &items).map_err(failed)?;
        Ok(self.render(&Plan { revision, items }, &demoted))
    }
}

fn failed(error: crate::error::Error) -> ToolError {
    ToolError::Failed(format!("{error}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::{AllowAll, RunScope, ToolRegistry};

    struct Fixture {
        _dir: tempfile::TempDir,
        store: SessionStore,
    }

    fn fixture() -> Fixture {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().to_path_buf());
        Fixture { _dir: dir, store }
    }

    async fn call(store: SessionStore, args: Value) -> Result<String, ToolError> {
        let tool = PlanTool::new(store);
        let registry = ToolRegistry::new(4096);
        let run = RunScope::new("s1");
        let scope = CallScope {
            approver: &AllowAll,
            run: &run,
            registry: &registry,
            call_id: None,
        };
        tool.call_scoped(args, &scope).await
    }

    #[tokio::test]
    async fn a_write_then_a_read_gives_the_same_list_back() {
        let f = fixture();
        let out = call(
            f.store.clone(),
            json!({"items":[
                {"id":"a","content":"read the audit","status":"done"},
                {"id":"b","content":"fix the writer","status":"in_progress"},
                {"id":"c","content":"release"}
            ]}),
        )
        .await
        .unwrap();
        assert!(out.starts_with("plan 1/3 · next b"), "{out}");
        assert!(out.contains("[x] a read the audit"), "{out}");
        assert!(out.contains("[~] b fix the writer"), "{out}");
        assert!(out.contains("[ ] c release"), "{out}");
        assert!(
            out.contains("revision 1 · 1 pending, 1 in progress, 1 done, 0 cancelled"),
            "{out}"
        );

        let read = call(f.store.clone(), json!({})).await.unwrap();
        assert_eq!(
            read, out,
            "a read must be the same list a write answered with, revision included"
        );
    }

    #[tokio::test]
    async fn every_write_bumps_the_revision_so_two_surfaces_can_tell() {
        let f = fixture();
        call(
            f.store.clone(),
            json!({"items":[{"id":"a","content":"one"}]}),
        )
        .await
        .unwrap();
        let second = call(
            f.store.clone(),
            json!({"items":[{"id":"a","content":"one","status":"done"}]}),
        )
        .await
        .unwrap();
        assert!(second.contains("revision 2"), "{second}");
    }

    #[tokio::test]
    async fn a_merge_patches_by_id_and_keeps_the_order() {
        let f = fixture();
        call(
            f.store.clone(),
            json!({"items":[
                {"id":"a","content":"first"},
                {"id":"b","content":"second"},
                {"id":"c","content":"third"}
            ]}),
        )
        .await
        .unwrap();
        let out = call(
            f.store.clone(),
            json!({"merge":true,"items":[{"id":"b","content":"second, done","status":"done"}]}),
        )
        .await
        .unwrap();
        assert!(out.contains("[x] b second, done"), "{out}");
        let order: Vec<&str> = out
            .lines()
            .filter(|l| l.starts_with('['))
            // `[x] id content` — the mark is three characters and a space, so the id starts at 4.
            .map(|l| l[4..].split_whitespace().next().unwrap())
            .collect();
        assert_eq!(order, ["a", "b", "c"], "b is still second: {out}");
        assert!(out.contains("plan 1/3"), "{out}");
    }

    #[tokio::test]
    async fn two_steps_in_progress_are_normalised_and_the_result_says_so() {
        let f = fixture();
        let out = call(
            f.store.clone(),
            json!({"items":[
                {"id":"a","content":"first","status":"in_progress"},
                {"id":"b","content":"second","status":"in_progress"}
            ]}),
        )
        .await
        .unwrap();
        assert!(out.contains("only one step can be `in_progress`"), "{out}");
        assert!(out.contains("demoted to `pending` (b)"), "{out}");
        assert!(out.contains("[ ] b second"), "{out}");
        assert!(out.contains("1 pending, 1 in progress"), "{out}");
    }

    #[tokio::test]
    async fn a_step_with_no_content_is_refused_and_the_list_is_untouched() {
        let f = fixture();
        call(
            f.store.clone(),
            json!({"items":[{"id":"a","content":"the real plan"}]}),
        )
        .await
        .unwrap();
        let refused = call(
            f.store.clone(),
            json!({"items":[{"id":"x","content":"ok"},{"id":"y","content":"   "}]}),
        )
        .await
        .unwrap_err();
        assert_eq!(
            refused.to_string(),
            "invalid arguments: item 2 (`y`) has no `content`; a step with nothing to do cannot be \
             done or dropped"
        );
        let read = call(f.store.clone(), json!({})).await.unwrap();
        assert!(read.contains("a the real plan"), "{read}");
        assert!(!read.contains(" x "), "nothing was written: {read}");
        assert!(
            read.contains("revision 1"),
            "and the revision did not move: {read}"
        );
    }

    #[tokio::test]
    async fn an_unknown_status_names_the_word_and_the_ones_to_use() {
        let f = fixture();
        let refused = call(
            f.store.clone(),
            json!({"items":[{"id":"a","content":"x","status":"blocked"}]}),
        )
        .await
        .unwrap_err();
        assert!(
            refused.to_string().contains("`blocked` is not a status"),
            "{refused}"
        );
        assert!(
            refused
                .to_string()
                .contains("`pending`, `in_progress`, `done` or `cancelled`"),
            "{refused}"
        );
    }

    #[tokio::test]
    async fn an_empty_list_clears_the_plan() {
        let f = fixture();
        call(
            f.store.clone(),
            json!({"items":[{"id":"a","content":"one"}]}),
        )
        .await
        .unwrap();
        let out = call(f.store.clone(), json!({"items":[]})).await.unwrap();
        assert!(out.starts_with("plan 0/0"), "{out}");
        assert!(out.contains("(no steps)"), "{out}");
        assert!(out.contains("revision 2"), "{out}");
    }

    #[tokio::test]
    async fn a_session_with_no_plan_says_so_rather_than_inventing_one() {
        let f = fixture();
        let out = call(f.store.clone(), json!({})).await.unwrap();
        assert_eq!(
            out,
            "no plan in this session yet — call `plan` with `items` to write the steps"
        );
    }

    #[tokio::test]
    async fn a_phase_is_a_step_and_its_children_name_it() {
        let f = fixture();
        let out = call(
            f.store.clone(),
            json!({"items":[
                {"id":"writer","content":"the writer cluster","status":"in_progress"},
                {"id":"#535","content":"array header ends a section","parent":"writer"}
            ]}),
        )
        .await
        .unwrap();
        assert!(
            out.contains("#535 array header ends a section (in writer)"),
            "{out}"
        );
    }
}