eclipse-core 0.14.0

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! The compaction harness (22d): measure the handoff instead of trusting it.
//!
//! Three questions live here, and none of them needs a model:
//!
//! * **Is it stable?** A compiler that is deterministic by accident still produces two
//!   different documents on two runs, two builds or two machines. The answer is a byte
//!   comparison of two fresh compiles, which is a thing a test can hold and a person can read.
//! * **What did it cost, and what did it keep?** There is no A/B partner any more: the
//!   model-written summary was deleted (decisions #12), so the baseline is the transcript
//!   itself. Cost is wall clock and size; retention is mechanical — every path, command,
//!   error name and blocked call the middle holds, found or not found in the rendered handoff.
//! * **Is every `[#N]` line actually readable at row N?** This is the one that matters most.
//!   The handoff *tells the model* that `session_search(around_message_id=N)` recovers what was
//!   omitted, so a line whose ref lands on a row that does not say that is the document lying
//!   about its own evidence. Every alphanumeric fragment of every log line is re-read from the
//!   row it cites; a fragment that is not there is a violation, not a rounding error.
//!
//! What is deliberately *not* here: the judgement pass. It is the one part that calls a model,
//! so it cannot be byte-compared, and the compiler half is what must hold at any transcript
//! size. `compile` is called with no `previous` handoff and no judgement, which is exactly the
//! deterministic body the loop ships when the pass is off or its answer is rejected.

use std::collections::HashMap;
use std::time::Instant;

use crate::message::{Message, Role};

use super::{
    call_summary, clean, facts, split_sections, strip_think, Facts, Limits, Options, LOG_HEADING,
};

/// The shortest fragment worth calling a claim. Two characters is "ok", "1", "in" — noise a
/// normalisation can move around; three is something a reader could check.
const MIN_FRAGMENT: usize = 3;

/// A ceiling for `clean`, whose only other job here is normalisation: big enough that it never
/// elides, small enough that `limit * 2 + 64` cannot overflow.
const WHOLE: usize = 1 << 40;

/// How many misses a tally names before it stops. A report that listed every miss at a
/// thousand-message transcript would be a second transcript.
const KEEP_MISSING: usize = 8;

// ---------------------------------------------------------------------------------------
// Reports
// ---------------------------------------------------------------------------------------

/// How many of a set of facts survived into the handoff.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Tally {
    pub total: usize,
    pub present: usize,
    pub missing: Vec<String>,
}

impl Tally {
    fn of<I: IntoIterator<Item = String>>(items: I, handoff: &str) -> Self {
        let mut tally = Tally::default();
        for item in items {
            tally.total += 1;
            if handoff.contains(&item) {
                tally.present += 1;
            } else if tally.missing.len() < KEEP_MISSING {
                tally.missing.push(item);
            }
        }
        tally
    }

    pub fn all_present(&self) -> bool {
        self.present == self.total
    }
}

/// Retention per ledger. Separate tallies rather than one number, because the four failures
/// mean different things: a missing path is a place the model can no longer look, a missing
/// error name is a diagnosis it will repeat, a missing command is work it will redo.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Retention {
    pub files: Tally,
    pub commands: Tally,
    pub errors: Tally,
    pub blocked: Tally,
}

impl Retention {
    /// (present, total) across every ledger.
    pub fn totals(&self) -> (usize, usize) {
        let all = [&self.files, &self.commands, &self.errors, &self.blocked];
        (
            all.iter().map(|t| t.present).sum(),
            all.iter().map(|t| t.total).sum(),
        )
    }

    pub fn ledgers(&self) -> [(&'static str, &Tally); 4] {
        [
            ("files", &self.files),
            ("commands", &self.commands),
            ("errors", &self.errors),
            ("blocked", &self.blocked),
        ]
    }
}

/// One log line that does not survive being re-read from the row it cites.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
    /// The row the line pointed at.
    pub at: u64,
    /// The whole log line, as it appears in the handoff.
    pub line: String,
    /// The fragment that could not be found, or the structural complaint when there is no
    /// fragment to name.
    pub fragment: String,
    pub why: String,
}

/// The Session Log, checked line by line against the transcript.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Faithfulness {
    pub lines: usize,
    /// Distinct fragments actually looked for, across all lines. Reported so "no violations"
    /// cannot be the answer of a check that never ran.
    pub fragments: usize,
    /// Log lines whose ref names no stored row. Only reachable from an in-memory transcript
    /// (`[tN]` refs), which nothing can be read back from — counted, not called a defect.
    pub unreferenced: usize,
    pub violations: Vec<Violation>,
}

impl Faithfulness {
    pub fn ok(&self) -> bool {
        self.violations.is_empty()
    }
}

/// Everything one run of the harness measured.
#[derive(Debug, Clone)]
pub struct Measurement {
    pub session: String,
    /// Rows in the middle window — the ones the handoff stands in for.
    pub messages: usize,
    /// Characters of transcript the handoff replaces (content plus tool-call arguments).
    pub middle_chars: usize,
    pub handoff_chars: usize,
    pub budget_chars: usize,
    pub compile_micros: u128,
    pub passes: usize,
    /// False when two compiles of the same input differ — a defect, not a measurement.
    pub identical: bool,
    pub faithfulness: Faithfulness,
    /// Only `compare` fills this: `verify` answers a question about the document, not about how
    /// much of the transcript survived into it.
    pub retention: Option<Retention>,
}

impl Measurement {
    /// Share of the middle's characters the document occupies. Above 1.0 the handoff is taller
    /// than what it replaces, which is worth seeing before a budget hides it.
    pub fn share(&self) -> f64 {
        if self.middle_chars == 0 {
            0.0
        } else {
            self.handoff_chars as f64 / self.middle_chars as f64
        }
    }

    pub fn millis(&self) -> f64 {
        self.compile_micros as f64 / 1000.0
    }
}

// ---------------------------------------------------------------------------------------
// Measuring
// ---------------------------------------------------------------------------------------

/// Compile `dropped` `passes` times and report what came out. Faithfulness is checked against
/// `rows` — the whole session — because a ref must resolve against the archive, not against the
/// slice the compiler happened to see.
pub fn measure(
    rows: &[Message],
    dropped: &[Message],
    session: &str,
    budget: usize,
    passes: usize,
    with_retention: bool,
) -> Measurement {
    let limits = Limits::default();

    let started = Instant::now();
    let first = super::compile(dropped, &Options::new(session, budget));
    let compile_micros = started.elapsed().as_micros();

    let mut identical = true;
    for _ in 1..passes.max(1) {
        // A fresh `Options` per pass: nothing carried over from the previous compile can be
        // what made this one agree.
        if super::compile(dropped, &Options::new(session, budget)) != first {
            identical = false;
        }
    }

    Measurement {
        session: session.to_string(),
        messages: dropped.len(),
        middle_chars: raw_chars(dropped),
        handoff_chars: first.chars().count(),
        budget_chars: budget,
        compile_micros,
        passes: passes.max(1),
        identical,
        faithfulness: faithfulness(&first, rows),
        retention: with_retention.then(|| retention(&first, &facts(dropped, &limits))),
    }
}

/// The `verify` question: same bytes twice, and refs that resolve.
pub fn verify(
    rows: &[Message],
    dropped: &[Message],
    session: &str,
    budget: usize,
    passes: usize,
) -> Measurement {
    measure(rows, dropped, session, budget, passes, false)
}

/// The `compare` question: what it cost and what it kept.
pub fn compare(rows: &[Message], dropped: &[Message], session: &str, budget: usize) -> Measurement {
    measure(rows, dropped, session, budget, 1, true)
}

/// Retention of the four ledgers against the transcript's own facts.
pub fn retention(handoff: &str, facts: &Facts) -> Retention {
    Retention {
        files: Tally::of(facts.files.iter().map(|(path, _)| path.clone()), handoff),
        commands: Tally::of(facts.commands.iter().cloned(), handoff),
        errors: Tally::of(facts.errors.iter().map(|(name, _)| name.clone()), handoff),
        // A blocked entry renders as `- {ref} {tool} `{target}` — status: excerpt`, so its head
        // is the identity and its tail is what the budget may have elided.
        blocked: Tally::of(
            facts.blocked.iter().map(|entry| head_of(entry).to_string()),
            handoff,
        ),
    }
}

fn head_of(entry: &str) -> &str {
    entry.split(" — ").next().unwrap_or(entry).trim()
}

/// Characters of transcript a handoff replaces: every message's content plus the arguments of
/// every call, which is what a drop would otherwise cost.
fn raw_chars(messages: &[Message]) -> usize {
    messages
        .iter()
        .map(|m| {
            m.content.as_deref().map(|c| c.chars().count()).unwrap_or(0)
                + m.tool_calls
                    .iter()
                    .map(|tc| {
                        tc.function.name.chars().count() + tc.function.arguments.chars().count()
                    })
                    .sum::<usize>()
        })
        .sum()
}

// ---------------------------------------------------------------------------------------
// Faithfulness: the Session Log, re-read row by row
// ---------------------------------------------------------------------------------------

/// What one line's check produced.
struct Checked {
    fragments: usize,
    violations: Vec<Violation>,
}

impl Checked {
    fn ok(fragments: usize) -> Self {
        Checked {
            fragments,
            violations: Vec::new(),
        }
    }

    fn bad(fragments: usize, violation: Violation) -> Self {
        Checked {
            fragments,
            violations: vec![violation],
        }
    }
}

/// Check every Session Log line against the row its `[#N]` cites.
pub fn faithfulness(handoff: &str, rows: &[Message]) -> Faithfulness {
    let limits = Limits::default();
    let index: HashMap<u64, &Message> = rows
        .iter()
        .filter_map(|m| m.seq.map(|seq| (seq, m)))
        .collect();
    // A result line names the tool that produced it, and that name lives on the *call* row —
    // this row only names it by id. Resolve the pairing once, up front.
    let calls: HashMap<&str, String> = rows
        .iter()
        .flat_map(|m| m.tool_calls.iter())
        .filter(|tc| !tc.id.is_empty())
        .map(|tc| (tc.id.as_str(), call_summary(tc, &limits).0))
        .collect();

    let mut report = Faithfulness::default();
    let (_, sections) = split_sections(handoff);
    let Some((_, log)) = sections.iter().find(|(heading, _)| heading == LOG_HEADING) else {
        return report;
    };

    for line in log.lines() {
        let Some((reference, rest)) = parse_ref(line) else {
            continue; // the marker paragraph and the "… N older log line(s) omitted" notes
        };
        report.lines += 1;
        let Ref::Row(seq) = reference else {
            // A `[tN]` line names a position in a transcript nobody stored. There is no row to
            // read it back from, and saying so is better than quietly not checking it.
            report.unreferenced += 1;
            continue;
        };
        let Some(row) = index.get(&seq) else {
            report.unreferenced += 1;
            continue;
        };

        let checked = if let Some(body) = rest.strip_prefix("→ ") {
            check_call(&seq, line, body, row, &limits)
        } else if let Some(body) = rest.strip_prefix("← ") {
            check_result(&seq, line, body, row, &calls)
        } else if let Some((role, body)) = rest.split_once(": ") {
            check_role(&seq, line, role, body, row)
        } else {
            Checked::bad(
                0,
                Violation {
                    at: seq,
                    line: line.to_string(),
                    fragment: rest.to_string(),
                    why: "the line has no shape the renderer produces".to_string(),
                },
            )
        };

        report.fragments += checked.fragments;
        report.violations.extend(checked.violations);
    }
    report
}

/// `[#12] user: …` → (12, "user: …"); `[t4] user: …` → a position, which names no row.
fn parse_ref(line: &str) -> Option<(Ref, &str)> {
    if let Some(rest) = line.strip_prefix("[#") {
        let (digits, after) = rest.split_once(']')?;
        return Some((Ref::Row(digits.parse::<u64>().ok()?), after.trim_start()));
    }
    let rest = line.strip_prefix("[t")?;
    let (digits, after) = rest.split_once(']')?;
    digits.parse::<usize>().ok()?;
    Some((Ref::Position, after.trim_start()))
}

/// The two kinds of citation a log line can carry.
enum Ref {
    Row(u64),
    Position,
}

fn check_role(seq: &u64, line: &str, role: &str, body: &str, row: &Message) -> Checked {
    let expected = match role {
        "user" => Role::User,
        "assistant" => Role::Assistant,
        other => {
            return Checked::bad(
                0,
                Violation {
                    at: *seq,
                    line: line.to_string(),
                    fragment: other.to_string(),
                    why: "the line names a role the compiler never writes".to_string(),
                },
            )
        }
    };
    let fragments = fragments_of(body);
    let mut violations = Vec::new();
    if row.role != expected {
        violations.push(Violation {
            at: *seq,
            line: line.to_string(),
            fragment: role.to_string(),
            why: format!("row {seq} is a {:?} row, not {role}", row.role),
        });
    }
    let hay = haystack(row, expected);
    for fragment in &fragments {
        if !hay.iter().any(|text| text.contains(fragment)) {
            violations.push(Violation {
                at: *seq,
                line: line.to_string(),
                fragment: fragment.clone(),
                why: format!("row {seq} does not contain it"),
            });
        }
    }
    Checked {
        fragments: fragments.len(),
        violations,
    }
}

fn check_call(seq: &u64, line: &str, body: &str, row: &Message, limits: &Limits) -> Checked {
    // `tool: \`target\``, or a bare `tool` when the call carried nothing quotable.
    let (name, target) = match body.split_once(": `") {
        Some((name, rest)) => (name.trim(), rest.strip_suffix('`').unwrap_or(rest)),
        None => (body.trim(), ""),
    };
    let matched = row.tool_calls.iter().any(|tc| {
        let (call_name, call_target) = call_summary(tc, limits);
        call_name == name && (target.is_empty() || call_target == target)
    });
    if matched {
        return Checked::ok(1);
    }
    Checked::bad(
        1,
        Violation {
            at: *seq,
            line: line.to_string(),
            fragment: name.to_string(),
            why: if row.tool_calls.is_empty() {
                format!("row {seq} is not a call row")
            } else {
                format!("no call on row {seq} names `{name}` with that target")
            },
        },
    )
}

fn check_result(
    seq: &u64,
    line: &str,
    body: &str,
    row: &Message,
    calls: &HashMap<&str, String>,
) -> Checked {
    let (name, rest) = match body.split_once(' ') {
        Some((name, rest)) => (name, rest),
        None => (body, ""),
    };
    let excerpt = rest.split_once(": ").map(|(_, e)| e).unwrap_or("");
    let fragments = fragments_of(excerpt);
    let mut violations = Vec::new();

    if let Some(id) = row.tool_call_id.as_deref() {
        if let Some(paired) = calls.get(id) {
            if paired != name {
                violations.push(Violation {
                    at: *seq,
                    line: line.to_string(),
                    fragment: name.to_string(),
                    why: format!("row {seq} answers a call to `{paired}`"),
                });
            }
        }
    }
    let hay = haystack(row, Role::Tool);
    for fragment in &fragments {
        if !hay.iter().any(|text| text.contains(fragment)) {
            violations.push(Violation {
                at: *seq,
                line: line.to_string(),
                fragment: fragment.clone(),
                why: format!("row {seq} does not contain it"),
            });
        }
    }
    Checked {
        fragments: fragments.len(),
        violations,
    }
}

// ---------------------------------------------------------------------------------------
// Reading a row the way the renderer read it
// ---------------------------------------------------------------------------------------

/// Every place a fragment could legitimately be found in this row.
///
/// Content goes through `clean`, the function the renderer used, so quotation and whitespace
/// differences cannot be mistaken for invention. Tool results are often JSON and the excerpt
/// the renderer quotes is a *decoded* string from inside it — so the JSON's own string values
/// are searched too, which is what stops an escaped newline from looking like a fabricated
/// sentence.
fn haystack(row: &Message, role: Role) -> Vec<String> {
    let raw = row.text_with_pictures();
    let raw = if role == Role::Assistant {
        strip_think(&raw)
    } else {
        raw.to_string()
    };
    let mut out = vec![normalise(&raw)];
    if let Ok(serde_json::Value::Object(map)) =
        serde_json::from_str::<serde_json::Value>(raw.trim())
    {
        for value in map.values() {
            let mut strings = Vec::new();
            collect_strings(value, &mut strings);
            for text in strings {
                out.push(normalise(&text));
            }
        }
    }
    out
}

fn collect_strings(value: &serde_json::Value, out: &mut Vec<String>) {
    match value {
        serde_json::Value::String(text) => out.push(text.clone()),
        serde_json::Value::Array(items) => items.iter().for_each(|v| collect_strings(v, out)),
        serde_json::Value::Object(map) => map.values().for_each(|v| collect_strings(v, out)),
        _ => {}
    }
}

fn normalise(text: &str) -> String {
    clean(text, WHOLE)
}

/// Distinct alphanumeric fragments of a line, in order of first appearance.
fn fragments_of(text: &str) -> Vec<String> {
    let mut seen: Vec<String> = Vec::new();
    for fragment in text.split(|c: char| !c.is_alphanumeric()) {
        if fragment.chars().count() < MIN_FRAGMENT {
            continue;
        }
        if !seen.iter().any(|s| s == fragment) {
            seen.push(fragment.to_string());
        }
    }
    seen
}

#[cfg(test)]
mod tests;