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
//! Guarantor-path test closing the same coverage-gap class TR-2/TR-3/TR-4/
//! TR-6/TR-7/TR-10's own `tr*_guarantor.rs` files close for their own
//! reductions (TR-9/T24, `/handoff`): a LIVE `Agent` (recorder + default
//! `ReductionPolicy`) records a real session; `reduce::handoff::build_handoff`
//! is applied over the recorded sidecar; the fresh reduction log AND the
//! handoff's projected view are persisted the way the CLI's `handoff`
//! command does (`SessionStore::save_reduction_log`/`save`); everything is
//! then **reloaded from disk** (never the live `Agent`/in-memory `Session`),
//! and `verify_log`/`invert` both run OFFLINE against that reloaded state.
//!
//! What this specifically proves, that `reduce_handoff.rs`'s in-memory tests
//! structurally cannot: the handoff's `ReductionLog` survives a real
//! `SidecarWriter` -> disk -> `SessionStore` round trip, and — the crux of
//! TR-9's "view-only, never in the sidecar" contract — the RELOADED SIDECAR
//! contains ZERO bytes of the handoff banner/objective text (it only ever
//! exists in the persisted VIEW's leading message, never in the sidecar),
//! and `invert`/`expand_reduction` restore every dropped (handoff-cleared)
//! turn byte-exact straight from that reloaded sidecar.
//!
//! No real model call anywhere: `PlainReplies` is a small deterministic
//! in-process fake provider.
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use async_trait::async_trait;
use supercode::reduce::handoff::build_handoff;
use supercode::reduce::{self, ReductionKind, ReductionPolicy};
use supercode::session::Session;
use supercode::sidecar::SidecarWriter;
use supercode::store::SessionStore;
use supercode::{Agent, ChatMessage, ChatRequest, Config, Provider, Usage};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"supercode-tr9-guarantor-{tag}-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::SeqCst)
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn filler(len: usize) -> String {
(0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}
/// Marker text unique enough that finding it anywhere outside the persisted
/// VIEW's own leading message is unambiguous proof of a leak.
const OBJECTIVE_MARKER: &str = "OBJECTIVE-MARKER-tr9-guarantor-6c1a";
/// A "secret" placed early in the fixture, expected to land inside a
/// handoff-cleared gap.
const SECRET: &str = "the incident id is INC-2026-0917";
struct PlainReplies {
calls: AtomicUsize,
}
#[async_trait]
impl Provider for PlainReplies {
async fn complete(
&self,
_req: &ChatRequest,
_on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
) -> supercode::Result<(ChatMessage, Usage)> {
let n = self.calls.fetch_add(1, Ordering::SeqCst);
Ok((
ChatMessage::assistant(format!("reply {n}: {}", filler(200))),
Usage::default(),
))
}
}
#[tokio::test]
async fn handoff_survives_live_agent_disk_reload_offline_verify_and_invert() {
let dir = temp_dir("dev02-dev04");
let store_dir = dir.join("store");
let store = SessionStore::open(&store_dir).unwrap();
let name = "tr9-handoff-guarantor";
let sidecar_path = store.sidecar_path(name);
// ---- LIVE: record a real session through a real Agent + sidecar ----
let config = Config::builder()
.cwd(dir.clone())
.system_prompt("you are a careful coding agent")
.build();
let mut agent = Agent::with_provider(
config,
Box::new(PlainReplies {
calls: AtomicUsize::new(0),
}),
);
let empty_session = Session::from_claude_code_str("").unwrap();
let writer = SidecarWriter::create(&sidecar_path, &empty_session).unwrap();
agent.set_recorder(writer);
agent.set_reduction_policy(ReductionPolicy::default());
agent
.send(format!("Please remember this: {SECRET}"))
.await
.unwrap();
for i in 0..8 {
agent
.send(format!("filler turn {i}, just say ack — {}", filler(100)))
.await
.unwrap();
}
// ---- Build the handoff over the LIVE recorder's own sidecar file ----
let sidecar_jsonl_live = std::fs::read_to_string(&sidecar_path).unwrap();
let sidecar_live = Session::from_sidecar_str(&sidecar_jsonl_live).unwrap();
let result = build_handoff(
&sidecar_live.messages,
&[],
2,
Some(&format!("continue the investigation. {OBJECTIVE_MARKER}")),
false,
None,
)
.unwrap();
assert!(
result
.log
.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::TurnsCleared { .. })),
"the secret's turn must be handoff-cleared: {:?}",
result.log
);
assert!(result.view[0]
.content
.as_deref()
.unwrap()
.contains(OBJECTIVE_MARKER));
// Persist the way the CLI's `handoff` command does.
store.save_reduction_log(name, &result.log).unwrap();
let jsonl: String = result
.view
.iter()
.filter_map(|m| serde_json::to_string(m).ok())
.collect::<Vec<_>>()
.join("\n");
store
.save(name, "handoff guarantor fixture", &jsonl)
.unwrap();
// --- OFFLINE from here: fresh reads from disk, no live Agent/Session ---
let sidecar_jsonl = store
.load_sidecar(name)
.unwrap()
.expect("sidecar must exist on disk");
let sidecar = Session::from_sidecar_str(&sidecar_jsonl).unwrap();
let log_reloaded = store
.load_reduction_log(name)
.unwrap()
.expect("reduction log must exist on disk");
assert_eq!(log_reloaded, result.log);
// THE CRUX (TR-9: "view-only, never in the sidecar"): the reloaded
// SIDECAR itself — the full-fidelity record `invert`/`expand_reduction`
// restore from — must never contain one byte of the handoff banner or
// objective text. It only ever exists in the persisted VIEW's leading
// message, never in the sidecar.
let sidecar_text = serde_json::to_string(&sidecar.messages).unwrap();
assert!(
!sidecar_text.contains("=== HANDOFF ==="),
"the reloaded sidecar must carry ZERO handoff banner text: {sidecar_text}"
);
assert!(
!sidecar_text.contains(OBJECTIVE_MARKER),
"the reloaded sidecar must carry ZERO objective text: {sidecar_text}"
);
// The reloaded PERSISTED VIEW (the `<name>.jsonl` transcript), by
// contrast, DOES carry it — proving the marker lives exactly where it
// should and nowhere else.
let persisted_view_jsonl = store.load(name).unwrap();
assert!(persisted_view_jsonl.contains("=== HANDOFF ==="));
assert!(persisted_view_jsonl.contains(OBJECTIVE_MARKER));
// The exact primitive `cli/main.rs`'s `show-reductions`/`convert`/
// `inspect`/`handoff` all call before doing anything else with a reduced
// session — anchored on sidecar bytes alone.
reduce::verify_log(&log_reloaded, &sidecar)
.expect("verify_log must pass clean against the reloaded-from-disk sidecar");
// `invert` restores the full original session byte-exact from the
// reloaded sidecar. Note: `ChatMessage`'s `sc.reduction` metadata NEVER
// serializes to the wire (by design — it must never leak into a request
// body or a persisted transcript), so it can't be recovered by simply
// re-parsing the persisted `<name>.jsonl` view back into `ChatMessage`s
// (every message's `metadata` would deserialize empty). This is exactly
// why `cli/main.rs`'s `inspect`/`convert`/`show-reductions` never do
// that either — they always FRESHLY reproject from the sidecar + the
// reloaded log (`reduce::project`/`project_messages`, which sets the
// metadata live in-memory) rather than deserializing a persisted view.
// Reprojecting from the reloaded sidecar + reloaded log under the SAME
// base policy `build_handoff` used must reproduce identically (prefix
// stability/determinism — the same guarantee every other `project_messages`
// caller relies on).
let base_policy = ReductionPolicy {
clear_turns_older_than: None,
..ReductionPolicy::default()
};
let (fresh_view, reprojected_log) =
reduce::project_messages(&sidecar.messages, &base_policy, &log_reloaded);
assert_eq!(
reprojected_log, log_reloaded,
"reprojecting from the reloaded sidecar with its own log must not invent new reductions"
);
let inverted = reduce::invert(&fresh_view, &log_reloaded, &sidecar)
.expect("invert must pass clean against the reloaded-from-disk sidecar");
// `fresh_view` is cardinality-parallel to the canonical session (no
// banner here — that's only ever added by `build_handoff` on top of a
// `project_messages` result, never reproduced by a bare reprojection),
// so a full `invert` restores it exactly.
assert_eq!(inverted.len(), sidecar.messages.len());
for (restored, original) in inverted.iter().zip(&sidecar.messages) {
assert_eq!(restored.content, original.content);
assert_eq!(restored.role, original.role);
}
// The secret itself is recoverable byte-exact from the restored turns —
// and never present anywhere in the reloaded sidecar's OWN handoff
// artifacts search path outside of this restore.
let restored_text = inverted
.iter()
.filter_map(|m| m.content.clone())
.collect::<Vec<_>>()
.join("\n");
assert!(restored_text.contains(SECRET));
// `expand_reduction` (TR-1) restores each dropped gap byte-exact too,
// resolved straight against the reloaded sidecar's own messages.
for id in &result.gap_ids {
let outcome =
reduce::rehydrate::expand_reduction(&log_reloaded, &sidecar.messages, None, id, None)
.unwrap();
assert!(!outcome.content.contains("HANDOFF"));
assert!(!outcome.content.contains(OBJECTIVE_MARKER));
}
// At least one gap must recover the secret (the fixture's construction
// guarantees the secret's turn is not in the keep-set with `--keep-last
// 2` and no explicit `--keep`).
let any_gap_has_secret = result.gap_ids.iter().any(|id| {
reduce::rehydrate::expand_reduction(&log_reloaded, &sidecar.messages, None, id, None)
.map(|o| o.content.contains(SECRET))
.unwrap_or(false)
});
assert!(any_gap_has_secret, "no gap recovered the secret text");
std::fs::remove_dir_all(&dir).ok();
}
// ---------------------------------------------------------------------------
// N>=2 `TurnsCleared` reprojection: the coverage gap this file exists to
// close, per the TR-9 skeptic pass.
// ---------------------------------------------------------------------------
/// `project_messages` was generalized (see its own A10 doc comment in
/// `reduce.rs`) to reapply MULTIPLE pre-existing `TurnsCleared` records —
/// sorted descending by `first` and re-spliced one at a time — because a
/// handoff keep-set is generally scattered (system prompt + a named middle
/// turn + keep-last), so the non-kept complement is generally several
/// disjoint gaps, not one. The test above (and every other handoff test in
/// this crate) either never reprojects at all, or reprojects a log carrying
/// only a SINGLE `TurnsCleared` record (no `--keep` token lands strictly
/// between the always-kept head and tail). This test forces a keep-set with
/// TWO disjoint gaps (one before, one after an explicitly-kept middle turn),
/// persists + reloads that 2-clear log from disk exactly like the CLI does,
/// and reprojects via `project_messages` against it — the N>=2
/// `existing_clears` reapply path (`reduce.rs`'s `if
/// !existing_clears.is_empty() { ... }` branch), exercised nowhere else.
#[tokio::test]
async fn handoff_multi_gap_log_reprojects_from_disk_via_n2_reapply_path() {
let dir = temp_dir("multigap");
let store_dir = dir.join("store");
let store = SessionStore::open(&store_dir).unwrap();
let name = "tr9-handoff-multigap";
let sidecar_path = store.sidecar_path(name);
const SECRET_A: &str = "the first incident id is INC-AAAA-0001";
const MID_MARKER: &str = "MID-KEEP-MARKER-tr9-multigap-71fe";
const SECRET_B: &str = "the second incident id is INC-BBBB-0002";
// ---- LIVE: record a real session whose keep-set (below) will carve out
// TWO disjoint gaps: one before the explicitly-kept middle turn, one
// between it and the deterministic keep-last tail. ----
let config = Config::builder()
.cwd(dir.clone())
.system_prompt("you are a careful coding agent")
.build();
let mut agent = Agent::with_provider(
config,
Box::new(PlainReplies {
calls: AtomicUsize::new(0),
}),
);
let empty_session = Session::from_claude_code_str("").unwrap();
let writer = SidecarWriter::create(&sidecar_path, &empty_session).unwrap();
agent.set_recorder(writer);
agent.set_reduction_policy(ReductionPolicy::default());
agent
.send(format!("Please remember this: {SECRET_A}"))
.await
.unwrap();
for i in 0..3 {
agent
.send(format!("filler turn A{i}, just say ack — {}", filler(80)))
.await
.unwrap();
}
agent
.send(format!(
"{MID_MARKER} — keep this middle turn verbatim, {}",
filler(40)
))
.await
.unwrap();
agent
.send(format!("Please also remember this: {SECRET_B}"))
.await
.unwrap();
agent
.send(format!("filler turn tail, just say ack — {}", filler(80)))
.await
.unwrap();
let sidecar_jsonl_live = std::fs::read_to_string(&sidecar_path).unwrap();
let sidecar_live = Session::from_sidecar_str(&sidecar_jsonl_live).unwrap();
let mid_idx = sidecar_live
.messages
.iter()
.position(|m| m.content.as_deref().is_some_and(|c| c.contains(MID_MARKER)))
.expect("the mid-marker turn must be present in the recorded sidecar");
// `--keep <mid_idx>` + `--keep-last 2` (the final filler turn): the
// middle turn is kept explicitly, sitting strictly between the
// always-kept tail and everything before it — guaranteeing two disjoint
// gaps regardless of exact message-per-turn counts.
let result = build_handoff(
&sidecar_live.messages,
&[mid_idx.to_string()],
2,
Some("continue the multi-gap investigation"),
false,
None,
)
.unwrap();
let clear_count = result
.log
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::TurnsCleared { .. }))
.count();
assert_eq!(
clear_count, 2,
"fixture must produce exactly two disjoint gaps (before and after the \
explicitly-kept middle turn): {:?}",
result.log
);
assert_eq!(result.gap_ids.len(), 2);
assert!(result.kept_indices.contains(&mid_idx));
// Persist sidecar + reduction log + view, exactly like the CLI's
// `handoff` command (`store.save_reduction_log`/`store.save`).
store.save_reduction_log(name, &result.log).unwrap();
let jsonl: String = result
.view
.iter()
.filter_map(|m| serde_json::to_string(m).ok())
.collect::<Vec<_>>()
.join("\n");
store
.save(name, "handoff multigap fixture", &jsonl)
.unwrap();
// --- OFFLINE from here: fresh reads from disk, no live Agent/Session ---
let sidecar_jsonl = store
.load_sidecar(name)
.unwrap()
.expect("sidecar must exist on disk");
let sidecar = Session::from_sidecar_str(&sidecar_jsonl).unwrap();
let log_reloaded = store
.load_reduction_log(name)
.unwrap()
.expect("reduction log must exist on disk");
assert_eq!(log_reloaded, result.log);
assert_eq!(
log_reloaded
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::TurnsCleared { .. }))
.count(),
2,
"the reloaded-from-disk log must still carry BOTH TurnsCleared records"
);
reduce::verify_log(&log_reloaded, &sidecar)
.expect("verify_log must pass clean against the reloaded-from-disk sidecar");
// THE CRUX (the coverage gap this test closes): reproject via
// `project_messages` against the reloaded, 2-clear prior log — the
// `existing_clears.len() >= 2` reapply branch in `reduce.rs`'s A10 step,
// which sorts every existing `TurnsCleared` record descending by `first`
// and re-splices each one in turn (mirroring `build_handoff`'s own
// last-gap-first splice order) rather than recomputing or widening any
// of them.
let base_policy = ReductionPolicy {
clear_turns_older_than: None,
..ReductionPolicy::default()
};
let (fresh_view, reprojected_log) =
reduce::project_messages(&sidecar.messages, &base_policy, &log_reloaded);
assert_eq!(
reprojected_log, log_reloaded,
"reprojecting a 2-clear prior log must reapply both records verbatim, \
never widen/recompute/invent"
);
// Prefix-stability / correctness: the reprojected view's cardinality
// matches exactly (each gap of length L collapses to exactly one stub,
// both gaps accounted for — no message wrongly dropped or duplicated).
let total_cleared: usize = log_reloaded
.reductions
.iter()
.filter_map(|r| match r.kind {
ReductionKind::TurnsCleared { first, last, .. } => Some(last - first + 1),
_ => None,
})
.sum();
assert_eq!(
fresh_view.len(),
sidecar.messages.len() - total_cleared + 2,
"both gaps must collapse to exactly one stub message each"
);
let view_text: String = fresh_view
.iter()
.filter_map(|m| m.content.clone())
.collect::<Vec<_>>()
.join("\n");
assert!(
view_text.contains(MID_MARKER),
"the explicitly-kept middle turn must survive reprojection verbatim"
);
assert!(
!view_text.contains(SECRET_A),
"gap 1's content must be stubbed, never leaked into the reprojected view"
);
assert!(
!view_text.contains(SECRET_B),
"gap 2's content must be stubbed, never leaked into the reprojected view"
);
// Each reapplied `TurnsCleared`'s stub must appear verbatim, EXACTLY
// once (never widened/recomputed into a different placeholder, never
// duplicated).
for r in log_reloaded
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::TurnsCleared { .. }))
{
let occurrences = fresh_view
.iter()
.filter(|m| m.content.as_deref() == Some(r.placeholder.as_str()))
.count();
assert_eq!(
occurrences, 1,
"the stub for reduction `{}` must appear exactly once in the \
reprojected view: {view_text}",
r.id
);
}
// A full `invert` restores every message byte-exact — BOTH gaps at once
// — straight from the reloaded sidecar.
let inverted = reduce::invert(&fresh_view, &log_reloaded, &sidecar)
.expect("invert must pass clean against the reloaded-from-disk sidecar");
assert_eq!(inverted.len(), sidecar.messages.len());
for (restored, original) in inverted.iter().zip(&sidecar.messages) {
assert_eq!(restored.content, original.content);
assert_eq!(restored.role, original.role);
}
let restored_text = inverted
.iter()
.filter_map(|m| m.content.clone())
.collect::<Vec<_>>()
.join("\n");
assert!(
restored_text.contains(SECRET_A),
"gap 1's dropped content must be byte-exact restorable via a full invert"
);
assert!(
restored_text.contains(SECRET_B),
"gap 2's dropped content must be byte-exact restorable via a full invert"
);
// `expand_reduction` (TR-1) restores EACH gap's dropped turns byte-exact
// directly too, resolved straight against the reloaded sidecar.
let mut gap_has_secret_a = false;
let mut gap_has_secret_b = false;
for id in &result.gap_ids {
let outcome =
reduce::rehydrate::expand_reduction(&log_reloaded, &sidecar.messages, None, id, None)
.unwrap();
assert!(!outcome.content.contains("HANDOFF"));
assert!(!outcome
.content
.contains("continue the multi-gap investigation"));
if outcome.content.contains(SECRET_A) {
gap_has_secret_a = true;
}
if outcome.content.contains(SECRET_B) {
gap_has_secret_b = true;
}
}
assert!(
gap_has_secret_a,
"one of the two gaps must recover SECRET_A byte-exact via expand_reduction"
);
assert!(
gap_has_secret_b,
"the OTHER of the two gaps must recover SECRET_B byte-exact via expand_reduction"
);
std::fs::remove_dir_all(&dir).ok();
}