Skip to main content

supercode_interchange/session/
mod.rs

1//! Natively load — and continue — real Claude Code and Codex sessions.
2//!
3//! Both tools persist their conversations as JSONL on disk:
4//!
5//! - **Claude Code**: `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`,
6//!   one line per event in the Anthropic message format, linked by
7//!   `uuid`/`parentUuid`.
8//! - **Codex**: `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`, where each line
9//!   is a `{timestamp, type, payload}` envelope and the `response_item` lines
10//!   form the canonical conversation.
11//!
12//! [`Session::load`] auto-detects the format and normalizes either one into a
13//! provider-neutral [`Vec<ChatMessage>`] that can be handed straight back to a
14//! model (via OpenRouter or any OpenAI-compatible endpoint) to continue.
15//!
16//! Provider-internal artifacts that don't replay across vendors — Anthropic
17//! `thinking` blocks, Codex `reasoning` items — are dropped during
18//! normalization.
19//!
20//! # Where this sits in supercode's priorities
21//!
22//! This module is the home of **feature 1 (translate between session formats)**
23//! and half of **feature 2 (emulate-to-continue)** — the load/emit surface for
24//! each harness ([`SessionFormat`], `from_*_str` loaders, `to_*_jsonl`
25//! emitters). See [`AGENTS.md`](../../../AGENTS.md) for the three ranked
26//! feature-priorities and the glue-tool positioning; the top priority is
27//! **feature 3 (continue losslessly *with massive token reduction*)**, which
28//! this fidelity work exists to make trustworthy. `opencode` + `pi` loaders
29//! are built against the frozen `docs/interop/opencode-pi-spec.md` contract
30//! — OpenCode additionally reads its native SQLite store (`opencode*.db`,
31//! PARITY-3/PARITY-16) via `rusqlite`, reconstructing the same envelope form
32//! [`Session::from_opencode_str`] already parses for the JSON-tree surfaces.
33
34use serde::{Deserialize, Serialize};
35use std::collections::{BTreeMap, HashMap, HashSet};
36use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
37use std::path::{Path, PathBuf};
38
39use rusqlite::Connection;
40use serde_json::Value;
41
42use crate::{
43    ChatMessage, Fidelity, FunctionCall, InterchangeError as Error, Result, Role, ToolCall,
44};
45
46mod claude_code;
47pub(crate) use claude_code::ClaudeAppendState;
48#[doc(hidden)]
49pub use claude_code::ClaudeReadIndex;
50mod codex;
51mod detect;
52mod gemini;
53mod goose;
54mod grok;
55mod helpers;
56mod hermes;
57mod native;
58mod openclaw;
59mod opencode;
60mod pi;
61
62// The per-harness files below are an internal file layout only: every item
63// keeps its original `crate::session::…` path through these re-exports, whose
64// visibility matches the most-visible item each module holds.
65pub(crate) use claude_code::*;
66use codex::*;
67pub use detect::*;
68use gemini::*;
69use grok::*;
70pub use helpers::*;
71pub use hermes::*;
72use native::*;
73pub use openclaw::*;
74pub use opencode::*;
75pub use pi::*;
76
77/// Which tool produced a session log.
78///
79/// This is **read-provenance**: a fact recovered when a log is loaded (stored
80/// in [`SessionMeta::source`], filled in by auto-detection in
81/// `detect_source`), describing which tool originally wrote the file on
82/// disk. It answers "where did this session come from?" — e.g. for
83/// `inspect`/`convert` display in the CLI.
84///
85/// It is deliberately distinct from [`SessionFormat`], even though the two
86/// enums' variant lists currently coincide: [`SessionFormat`] selects a
87/// serialization codec (what to parse/export *as*), while `SessionSource`
88/// records history (what wrote the file). The pair is intentionally kept
89/// separate rather than merged — a session loaded from one tool's log can
90/// still be exported in the other tool's format, and the two concepts could
91/// diverge further (e.g. a format that is readable but not attributable, or
92/// multiple versioned formats sharing one source).
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum SessionSource {
95    /// A `~/.claude/projects/.../<id>.jsonl` transcript.
96    ClaudeCode,
97    /// A `~/.codex/sessions/.../rollout-*.jsonl` file.
98    Codex,
99    /// An OpenCode session — multi-file JSON tree(s) or SQLite `opencode*.db`
100    /// (`docs/interop/opencode-pi-spec.md` §1.2). Detection and loading are
101    /// wave B; this variant exists now so `SessionSource`/`SessionFormat` stay
102    /// 1:1 per the frozen interop spec (§0).
103    OpenCode,
104    /// A `~/.pi/agent/sessions/--<enc-cwd>--/<iso>_<sessionId>.jsonl`
105    /// transcript (`docs/interop/opencode-pi-spec.md` §1.1) — line-oriented
106    /// JSONL like Claude Code/Codex, so it shares their byte-lossless native
107    /// round-trip property.
108    Pi,
109    /// A Grok session transcript stored as
110    /// `~/.grok/sessions/<percent-encoded-cwd>/<session-id>/chat_history.jsonl`.
111    Grok,
112    /// A Gemini CLI transcript stored under
113    /// `~/.gemini/tmp/<project>/chats/session-*.jsonl`.
114    Gemini,
115    /// A Goose session exported through `_goose/unstable/session/export`, or
116    /// reconstructed from Goose's `sessions/sessions.db` native store.
117    Goose,
118    /// An OpenClaw agent session (`~/.openclaw/agents/<agentId>/sessions/
119    /// <uuid>.jsonl`, openclaw >= 2026.7): pi session-format v3 with
120    /// openclaw dialect divergences — `type:"leaf"` navigation-control
121    /// entries that REDIRECT the active leaf (pi's last-entry anchor rule is
122    /// wrong for them), `appendMode:"side"` entries that never anchor, and
123    /// vendor-namespaced `__openclaw` message metadata. READ-ONLY provenance
124    /// (UNI-16): there is deliberately no `SessionFormat::OpenClaw` — the
125    /// write tier is a permanently skipped direct-DB/store path; loaded
126    /// sessions translate OUT through the other formats.
127    OpenClaw,
128    /// A Hermes Agent session read from its single SQLite store
129    /// (`~/.hermes/state.db`, `SCHEMA_VERSION = 22` at the 0.19.0 pin).
130    /// READ-ONLY provenance (UNI-15): no `SessionFormat::Hermes` exists —
131    /// writing into a live, shared, WAL, single-writer store stays gated by
132    /// UNI-22 (not fired; the schema churned 19->22 in one release) — loaded
133    /// sessions translate OUT through the other formats.
134    Hermes,
135    /// P5-3 safety-hardening fix (Fable-5 review, LOW "translation-fidelity
136    /// cosmetic"): a session that was never imported from ANY foreign
137    /// tool's log at all — authored directly by supercode's own agent loop,
138    /// with no foreign-tool prefix (`Session.raw` starts empty). Currently
139    /// only `crate::agent::Agent`'s `persist_subagent_transcript` (P5-3,
140    /// natively-spawned `spawn_subagent` children) uses this — before this
141    /// variant existed, that call site built its blank `Session` via
142    /// `Session::from_claude_code_str("")` purely as an "empty parser to
143    /// get a blank skeleton" trick, which left `meta.source ==
144    /// SessionSource::ClaudeCode` even though nothing Claude-Code-shaped
145    /// was ever involved, mislabeling a native supercode spawn as an
146    /// imported CC session on disk (and in any `inspect`/`convert` reading
147    /// it back). Never produced by auto-detection (`detect_source`) or any
148    /// `from_<tool>_str` loader — only by code that explicitly constructs
149    /// a `SessionMeta` with this source, so no existing imported-session
150    /// path can ever observe this variant appearing where it didn't before.
151    Native,
152}
153
154/// An on-disk session format supercode can both read and write.
155///
156/// Like an image editor that opens and exports several file formats, supercode
157/// keeps one canonical in-memory model ([`Session`]) and converts to/from each
158/// supported format on the edges.
159///
160/// This is a **write-target** / codec selector: a caller's request, passed to
161/// [`Session::load_str`], [`Session::to_jsonl`], and [`Session::save`],
162/// choosing which on-disk dialect to parse or emit. It answers "what format
163/// should I read/write?" — as opposed to [`SessionSource`], which records the
164/// provenance fact of what actually produced a loaded file. The two enums are
165/// intentionally kept separate (provenance fact vs. serialization choice) and
166/// should not be unified, even though their variants currently match
167/// one-to-one.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum SessionFormat {
170    /// Claude Code transcript JSONL.
171    ClaudeCode,
172    /// Codex rollout JSONL.
173    Codex,
174    /// OpenCode export-document / envelope JSONL (wave B; see
175    /// [`SessionSource::OpenCode`]).
176    OpenCode,
177    /// Pi session JSONL (see [`SessionSource::Pi`]).
178    Pi,
179    /// Grok `chat_history.jsonl` transcript.
180    Grok,
181    /// Gemini CLI session JSONL.
182    Gemini,
183    /// Goose native session-export JSON.
184    Goose,
185}
186
187impl SessionFormat {
188    /// The [`SessionSource`] a file of this format reports.
189    ///
190    /// This is the deliberate one-way bridge between the two concepts: a file
191    /// saved in this format will, when reloaded, report this provenance (see
192    /// `crates/harness/tests/session_saving.rs`), making the relationship
193    /// discoverable from the method itself.
194    pub fn source(self) -> SessionSource {
195        match self {
196            SessionFormat::ClaudeCode => SessionSource::ClaudeCode,
197            SessionFormat::Codex => SessionSource::Codex,
198            SessionFormat::OpenCode => SessionSource::OpenCode,
199            SessionFormat::Pi => SessionSource::Pi,
200            SessionFormat::Grok => SessionSource::Grok,
201            SessionFormat::Gemini => SessionSource::Gemini,
202            SessionFormat::Goose => SessionSource::Goose,
203        }
204    }
205}
206
207/// Metadata recovered from a session log.
208pub use crate::ontology::surface::{
209    CrossSurface, Recurrence, SurfaceKey, Trigger, WorkspaceKind, WorkspaceRef,
210};
211
212/// ORCH-6: the ORCH-3 conversation nouns as one additive wire block, carried
213/// by `harness.v1.sessions.discover` / `sessions.load` rows and by
214/// [`crate::catalog::SessionDescriptor`]. Every field is optional so an older
215/// client sees exactly the shape it already knows.
216#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
217pub struct OrchestrationNouns {
218    /// Why the session exists.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub trigger: Option<Trigger>,
221    /// Where the conversation is reached.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub surface: Option<SurfaceKey>,
224    /// Routed config home (Hermes profile / OpenClaw agent).
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub profile: Option<String>,
227    /// The job a recurring session belongs to.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub recurrence: Option<Recurrence>,
230    /// Moved-to-another-surface state.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub cross_surface: Option<CrossSurface>,
233    /// Typed workspace (the D2 precedence result).
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub workspace: Option<WorkspaceRef>,
236}
237
238impl OrchestrationNouns {
239    /// Read the nouns off a loaded session's metadata. `trigger` and
240    /// `workspace` always resolve — through [`SessionMeta::trigger_or_default`]
241    /// and [`SessionMeta::workspace`], never through a second derivation.
242    pub fn from_meta(meta: &SessionMeta) -> Self {
243        Self {
244            trigger: Some(meta.trigger_or_default()),
245            surface: meta.surface.clone(),
246            profile: meta.profile.clone(),
247            recurrence: meta.recurrence.clone(),
248            cross_surface: meta.cross_surface.clone(),
249            workspace: Some(meta.workspace_ref()),
250        }
251    }
252}
253
254#[derive(Debug, Clone)]
255#[non_exhaustive]
256pub struct SessionMeta {
257    /// The tool that wrote the log.
258    pub source: SessionSource,
259    /// The session/rollout id.
260    pub session_id: Option<String>,
261    /// The model the session was running.
262    pub model: Option<String>,
263    /// The working directory the session ran in.
264    pub cwd: Option<PathBuf>,
265    /// The system / base-instructions prompt, when the log records it.
266    pub system_prompt: Option<String>,
267    /// Verbatim source-format header records (the Codex `session_meta` /
268    /// `turn_context` lines), preserved so re-export can replay the exact header
269    /// the original tool expects rather than guessing its required fields.
270    pub codex_headers: Vec<Value>,
271    /// Exact source lines for Codex execution/provenance records that affect
272    /// continuation semantics but must not be replayed as active events after
273    /// a foreign-format hop. Each entry records its original physical-line
274    /// index, discriminant, and verbatim JSONL text. Foreign writers carry the
275    /// list in a namespaced extension; a later Codex export restores headers
276    /// from it while keeping compaction/rollback/review records non-operative,
277    /// avoiding a second rollback or compaction of the already-normalized view.
278    pub codex_provenance: Vec<Value>,
279    /// PARITY-23: generalized source-native residue records for NON-codex
280    /// sources — `{record_index, kind, raw}` entries captured at load time
281    /// (or restored from a portable v2 envelope) so cross-format hops can
282    /// return them exactly. Codex keeps its original dedicated store above.
283    pub native_residue: Vec<Value>,
284    /// The source format `native_residue` belongs to (e.g. `claude_code`).
285    pub native_residue_source: Option<String>,
286    /// The OpenCode analogue of [`Self::codex_headers`]
287    /// (`docs/interop/opencode-pi-spec.md` §1.2/§2.1): the verbatim
288    /// `SessionInfo` record (always element 0, or `Value::Null` if somehow
289    /// absent), plus any captured `session_diff`/`todo` side-records — each
290    /// wrapped as `{"key": [...], "value": ...}`, mirroring the envelope
291    /// shape `raw` uses, so a consumer can tell which storage key a header
292    /// record belongs to. These replay only via the direct-write fallback
293    /// (`Session::to_opencode_direct_write`); `opencode import` has no
294    /// ingestion path for `session_diff`/`todo` (S5).
295    pub opencode_headers: Vec<Value>,
296    /// Goose's native session-export object with `conversation` removed.
297    /// Goose stores sessions in SQLite but defines this JSON object as its
298    /// official import/export boundary. Keeping the shell lets an unchanged
299    /// direct round-trip remain byte exact while appended turns are spliced
300    /// into a stock-importable artifact without guessing native metadata.
301    pub goose_header: Option<Value>,
302    /// For a Claude Code subagent session: its `agentId` (the `agent-<id>` file
303    /// stem). `None` for top-level sessions.
304    pub agent_id: Option<String>,
305    /// For a subagent session: the `tool_use_id` of the parent `Task` call that
306    /// spawned it, recovered from the parent transcript's tool result. Best
307    /// effort — `None` if the link could not be established.
308    pub parent_tool_use_id: Option<String>,
309    /// Cross-file lineage keys for multi-file/multi-agent sessions (Codex
310    /// `parent_thread_id`, `forked_from_id`, `thread_source`, and the
311    /// `source.subagent.thread_spawn` fields `agent_role` / `agent_nickname` /
312    /// `depth`). Empty for a plain top-level session. Used by
313    /// [`Session::reconstruct_tree`] to nest children under their parents.
314    pub lineage: std::collections::BTreeMap<String, String>,
315    /// ORCH-3: why the session exists, when the source says.
316    pub trigger: Option<Trigger>,
317    /// ORCH-3: the conversation's surface identity, when it has one.
318    pub surface: Option<SurfaceKey>,
319    /// ORCH-3: routed config home (Hermes profile / OpenClaw agent / Codex profile).
320    pub profile: Option<String>,
321    /// ORCH-3: the job a recurring session belongs to.
322    pub recurrence: Option<Recurrence>,
323    /// ORCH-3: moved-to-another-surface state.
324    pub cross_surface: Option<CrossSurface>,
325}
326
327impl SessionMeta {
328    pub(crate) fn new(source: SessionSource) -> Self {
329        SessionMeta {
330            source,
331            session_id: None,
332            model: None,
333            cwd: None,
334            system_prompt: None,
335            codex_headers: Vec::new(),
336            codex_provenance: Vec::new(),
337            native_residue: Vec::new(),
338            native_residue_source: None,
339            opencode_headers: Vec::new(),
340            goose_header: None,
341            agent_id: None,
342            parent_tool_use_id: None,
343            lineage: std::collections::BTreeMap::new(),
344            trigger: None,
345            surface: None,
346            profile: None,
347            recurrence: None,
348            cross_surface: None,
349        }
350    }
351
352    /// The trigger, defaulting from what the loaders already know: a spawned
353    /// child (`agent_id` / a delegate lineage) is `Parent`; otherwise `Human`.
354    pub fn trigger_or_default(&self) -> Trigger {
355        if let Some(t) = self.trigger {
356            return t;
357        }
358        let delegate = self
359            .lineage
360            .get("hermes_lineage_kind")
361            .map(|k| k == "delegate")
362            .unwrap_or(false);
363        if self.agent_id.is_some() || self.parent_tool_use_id.is_some() || delegate {
364            Trigger::Parent
365        } else {
366            Trigger::Human
367        }
368    }
369
370    /// UNI-9 workspace with the D2 precedence: `repo` when a cwd exists, else
371    /// `channel` when the surface is a channel, else `none`. Derived, never stored.
372    pub fn workspace(&self) -> (WorkspaceKind, Option<String>) {
373        if let Some(cwd) = &self.cwd {
374            return (
375                WorkspaceKind::Repo,
376                Some(cwd.to_string_lossy().into_owned()),
377            );
378        }
379        if let Some(surface) = self.surface.as_ref().filter(|s| s.is_channel()) {
380            let label = match (&surface.platform, &surface.chat_id) {
381                (Some(p), Some(c)) => format!("{p}:{c}"),
382                (Some(p), None) => p.clone(),
383                _ => String::new(),
384            };
385            return (WorkspaceKind::Channel, Some(label));
386        }
387        (WorkspaceKind::None, None)
388    }
389
390    /// [`Self::workspace`] as the wire value. Naming only — the precedence
391    /// stays in `workspace()`.
392    pub fn workspace_ref(&self) -> WorkspaceRef {
393        let (kind, value) = self.workspace();
394        WorkspaceRef { kind, value }
395    }
396}
397
398/// A normalized, replayable conversation loaded from a tool's session log.
399#[derive(Debug, Clone)]
400pub struct Session {
401    /// Recovered metadata.
402    pub meta: SessionMeta,
403    /// The conversation, normalized to the OpenAI chat-completions shape.
404    pub messages: Vec<ChatMessage>,
405    /// Subagent (Task) sub-conversations. Claude Code stores these as separate
406    /// `<session>/subagents/agent-*.jsonl` files; loading a session by path now
407    /// discovers and attaches them here (each is a full [`Session`] whose
408    /// `meta.agent_id` / `meta.parent_tool_use_id` link it back to its spawn).
409    pub subagents: Vec<Session>,
410    /// Every original JSONL line of the source log, STRICT-VERBATIM (IX-1):
411    /// captured via `split_lines_verbatim`, not the blank-skipping/trimming
412    /// `non_empty_lines` parse view, so a blank line, a CRLF (`\r\n`)
413    /// terminator, or trailing whitespace on a line all survive bit-for-bit
414    /// rather than being dropped/normalized away. Normalization into
415    /// `messages` is still lossy by design (it targets the OpenAI replay
416    /// shape), but these raw lines retain *everything* — including records
417    /// with no canonical representation (e.g. Claude `file-history-snapshot`)
418    /// — so a round-trip through the supercode-native format
419    /// ([`Session::to_native_jsonl`]) is byte-lossless for the line-oriented
420    /// formats (Claude Code/Codex/Pi), for ANY input (see
421    /// [`Self::raw_trailing_newline`] for the one piece of information a line
422    /// list alone can't carry).
423    pub raw: Vec<String>,
424    /// Whether the source text `raw` was captured from ended with a trailing
425    /// `\n`. `raw`'s line list alone can't distinguish a source ending with a
426    /// trailing newline from one that doesn't (both split into the same
427    /// lines) — this flag carries that fact out-of-band so
428    /// [`Self::to_native_jsonl`]/[`Self::from_native_str`] can reproduce the
429    /// original source bytes exactly, including the presence/absence of a
430    /// final newline. `true` for a `Session` whose `raw` isn't captured
431    /// verbatim from real source text (e.g. OpenCode's re-synthesized
432    /// export-document `raw`, or a `Session` assembled programmatically) —
433    /// matching the historical always-terminated-by-newline behavior for
434    /// those cases.
435    pub raw_trailing_newline: bool,
436    /// How many of `messages` (and, symmetrically, of `raw` — see below) came
437    /// from parsing the imported log, as opposed to being appended after
438    /// import. Set once, at the end of [`Self::from_claude_code_str`] /
439    /// [`Self::from_codex_str`], to `messages.len()` at that moment — i.e.
440    /// before [`Self::from_native_str`]'s subsequent loop reattaches any
441    /// appended [`crate::sidecar::NativeTurn`] records onto `messages`/`raw`.
442    /// That loop pushes exactly one `raw` line and one message per appended
443    /// turn, so the two lists grow in lockstep from here on: the raw-prefix
444    /// boundary A12's [`Self::to_jsonl_spliced`] needs is always recoverable
445    /// as `raw.len() - (messages.len() - imported_message_count)`, without a
446    /// second counter. `None` only when a `Session` is constructed some other
447    /// way than through those two loaders — splicing then has no boundary to
448    /// honor and treats every message as imported (equivalent to
449    /// `Some(messages.len())`).
450    /// A bounded display-history projection uses this field for the total
451    /// number of normalized messages observed before its in-memory window was
452    /// applied. Such a semantic view is never a continuation source, and all
453    /// splice callers clamp the value to `messages.len()`.
454    pub imported_message_count: Option<usize>,
455    /// Whether `raw` was captured strict-verbatim from real source text
456    /// (`true`) or re-synthesized by this crate (`false`) — the fact
457    /// [`Self::raw_verbatim`]'s callers need to know before claiming a
458    /// same-format `convert` is byte-identical (PARITY-AUDIT.md P006/P007).
459    /// `true` for every line-oriented loader (`from_claude_code_str`,
460    /// `from_codex_str`, `from_pi_str`) and OpenCode's own ENVELOPE read
461    /// surface (`from_opencode_str`'s per-line loop) — each of those splits
462    /// `raw` directly out of the source text via `split_lines_verbatim`, so
463    /// replaying it reproduces the original bytes exactly. `false` for
464    /// OpenCode's EXPORT-DOCUMENT read surface
465    /// (`Session::from_opencode_export_doc`): a pretty-printed
466    /// `{info, messages:[...]}` document has no per-line envelope structure
467    /// of its own, so `raw` there is one envelope line RE-SYNTHESIZED per
468    /// record — faithful in value, but not the original document's bytes.
469    /// A `Session` assembled programmatically (not through a `from_*_str`
470    /// loader) also defaults to `false` — no real source text was captured
471    /// at all.
472    pub raw_is_verbatim: bool,
473    /// PARITY-15: how many non-empty lines of the source text FAILED to
474    /// deserialize at all (a genuinely malformed/truncated JSON line — not
475    /// a well-formed-but-unmodeled record type, which is a normal,
476    /// intentional "skip", tracked separately by `crate::audit`). Every
477    /// line-oriented loader tolerates a stray corrupt line rather than
478    /// hard-failing the whole load (a single bad line must not make an
479    /// otherwise-healthy multi-thousand-line session unloadable) — but that
480    /// tolerance used to be completely invisible: `Session::load` returned
481    /// `Ok` either way, with no signal that anything was skipped. This
482    /// count is what lets a caller (the CLI, `inspect`/`convert`) surface
483    /// that loss loudly instead of silently. `0` for a cleanly-parsed file,
484    /// and for a `Session` assembled programmatically.
485    pub parse_error_lines: usize,
486    /// Named degradations a [`Fidelity::Semantic`] load accepted instead of
487    /// failing — the same "say exactly what was given up" residue list
488    /// `harness.v1.sessions.export` already reports for artifacts.
489    ///
490    /// ALWAYS empty for a lossless load: every stricter fidelity refuses a
491    /// transcript it cannot reconstruct exactly, which is what keeps
492    /// continuation/transfer/export guarantees intact. A non-empty list means
493    /// this session is a read-only VIEW ([`Session::load_with_fidelity`] with
494    /// [`Fidelity::Semantic`]) and must not be used as a continuation source.
495    pub load_residue: Vec<String>,
496}
497
498impl Session {
499    /// The fidelity this reconstruction actually achieved.
500    ///
501    /// Same rule the export path applies to an artifact: named residue means
502    /// [`Fidelity::Semantic`]; otherwise a verbatim source capture is
503    /// [`Fidelity::ByteLossless`] and a re-synthesized one is
504    /// [`Fidelity::ValueLossless`]. A subagent's residue counts as this
505    /// session's: the whole reconstruction is only as faithful as its least
506    /// faithful part, and each child still reports its own residue where it
507    /// was measured.
508    pub fn load_fidelity(&self) -> Fidelity {
509        let own = if !self.load_residue.is_empty() {
510            Fidelity::Semantic
511        } else if self.raw_is_verbatim {
512            Fidelity::ByteLossless
513        } else {
514            Fidelity::ValueLossless
515        };
516        if own != Fidelity::Semantic
517            && self
518                .subagents
519                .iter()
520                .any(|subagent| subagent.load_fidelity() == Fidelity::Semantic)
521        {
522            return Fidelity::Semantic;
523        }
524        own
525    }
526
527    /// Assemble a session from supercode's own flat store transcript (one
528    /// [`ChatMessage`] per JSONL line). These files are the native working
529    /// format written by Supercode's native session store, not a foreign
530    /// harness log, so routing them through format auto-detection would
531    /// misclassify them as an empty Claude Code session.
532    pub fn from_native_messages(messages: Vec<ChatMessage>) -> Session {
533        Session {
534            meta: SessionMeta::new(SessionSource::Native),
535            messages,
536            subagents: Vec::new(),
537            raw: Vec::new(),
538            raw_trailing_newline: true,
539            imported_message_count: None,
540            raw_is_verbatim: false,
541            parse_error_lines: 0,
542            load_residue: Vec::new(),
543        }
544    }
545
546    /// Load a session, auto-detecting whether it's a Claude Code or Codex log
547    /// — or, when `path` looks like a SQLite database, a real OpenCode
548    /// `opencode*.db` store (PARITY-3/PARITY-16): that check runs BEFORE any
549    /// UTF-8 text read, so a binary `.db` file is routed to
550    /// [`Self::from_opencode_sqlite`] instead of failing on a raw "stream
551    /// did not contain valid UTF-8" error (the confirmed footgun these items
552    /// close — see [`looks_like_sqlite`] and the UTF-8 diagnostic reader).
553    ///
554    /// A DIRECTORY is also accepted directly: `path` is probed with
555    /// [`detect_opencode_storage_surface`] BEFORE the SQLite/UTF-8 file
556    /// checks below (both of which assume a file and would otherwise surface
557    /// a cryptic "Is a directory" `io::Error` — the confirmed footgun this
558    /// closes). This lets `inspect`/`convert`/`resume` accept an OpenCode
559    /// DATA-ROOT directly (e.g. `~/.local/share/opencode`), matching what
560    /// `audit --format opencode` already does. A resolved `Sqlite` surface
561    /// loads exactly like pointing `load` at that `opencode*.db` file
562    /// directly (most-recently-updated top-level session). The legacy
563    /// `JsonTreeA`/`JsonTreeB` surfaces are classifier-only (see
564    /// [`OpenCodeStorageSurface`]) — there's no direct-JSON-tree loader, so
565    /// that case returns a clear error naming the `.db` file / `audit` as the
566    /// way in, rather than silently doing nothing or crashing.
567    pub fn load(path: impl AsRef<Path>) -> Result<Session> {
568        Self::load_with_fidelity(path, Fidelity::ByteLossless)
569    }
570
571    /// Load a session at a declared [`Fidelity`].
572    ///
573    /// [`Fidelity::Semantic`] is the READ-ONLY VIEW mode: a transcript whose
574    /// record graph cannot be reconstructed exactly (the everyday case for a
575    /// Claude Code session that has been compacted or resumed across files,
576    /// where a live record's `parentUuid` names a record that was pruned)
577    /// still loads, stitched best-effort in transcript order, and names what
578    /// it gave up in [`Session::load_residue`]. Every stricter level keeps
579    /// the historical behavior — refuse loudly — because a continuation,
580    /// transfer or export built on a guessed graph is exactly the loss
581    /// supercode exists to prevent. Callers that go on to RESUME a session
582    /// must therefore use [`Session::load`].
583    pub fn load_with_fidelity(path: impl AsRef<Path>, fidelity: Fidelity) -> Result<Session> {
584        Self::load_with_fidelity_and_subagents(path, fidelity, true)
585    }
586
587    /// Load only the selected session's own transcript at a declared fidelity.
588    ///
589    /// This is the read-only frontend path: Claude Code can place hundreds of
590    /// child transcripts beside a parent, but a chat viewport displaying the
591    /// parent must not eagerly parse and transport that entire child tree.
592    /// Translation, continuation, export, and the ordinary [`Self::load`]
593    /// path keep attaching every subagent unchanged.
594    #[doc(hidden)]
595    pub fn load_parent_with_fidelity(
596        path: impl AsRef<Path>,
597        fidelity: Fidelity,
598    ) -> Result<Session> {
599        Self::load_with_fidelity_and_subagents(path, fidelity, false)
600    }
601
602    /// Load a bounded, parent-only transcript for human display.
603    ///
604    /// Unlike the continuation loader, Codex compaction records do not erase
605    /// earlier visible assistant turns here: the native rollout still holds
606    /// those records, and a scrollback view should show what the human saw,
607    /// not only the compacted context the next model call will receive.
608    #[doc(hidden)]
609    pub fn load_display_view(
610        path: impl AsRef<Path>,
611        fidelity: Fidelity,
612        message_limit: usize,
613    ) -> Result<Session> {
614        let path = path.as_ref();
615        if path.is_dir() || looks_like_sqlite(path) {
616            let mut session = Self::load_parent_with_fidelity(path, fidelity)?;
617            truncate_session_messages(&mut session, message_limit);
618            return Ok(session);
619        }
620        let mut read_limit = message_limit.max(1);
621        let mut previous_window_len = 0usize;
622        let (mut session, omitted_prefix) = loop {
623            let (source, text, omitted_prefix) = read_display_jsonl(path, read_limit)?;
624            let mut candidate = match source {
625                Some(SessionSource::Codex) => Self::from_codex_display_str(&text, message_limit)?,
626                Some(SessionSource::Gemini) => {
627                    let mut session = Self::from_gemini_str(&text)?;
628                    session.raw_is_verbatim = false;
629                    session.load_residue.push(
630                        "display history is a bounded native-record projection, not a complete Gemini artifact"
631                            .to_string(),
632                    );
633                    session
634                }
635                Some(SessionSource::Pi) => Self::from_pi_str(&text)?,
636                Some(SessionSource::Grok) => {
637                    let mut session = Self::from_grok_str(&text)?;
638                    session.capture_grok_path_metadata(path);
639                    session
640                }
641                Some(SessionSource::OpenCode) => Self::from_opencode_str(&text)?,
642                _ => Self::from_claude_code_str_with_fidelity(&text, fidelity)?,
643            };
644            let observed_messages = candidate
645                .imported_message_count
646                .unwrap_or(candidate.messages.len())
647                .max(candidate.messages.len());
648            let human_turns = candidate
649                .messages
650                .iter()
651                .filter(|message| message.role == Role::User)
652                .count();
653            let window_len = text.len();
654            let sufficient =
655                !omitted_prefix || (observed_messages > message_limit.max(1) && human_turns >= 2);
656            // 16 KiB/message with a 64 MiB ceiling means 4096 is the first
657            // read limit that cannot grow the native byte window further.
658            // Smaller repeated lengths can be the intentional 4 MiB floor;
659            // keep doubling through that plateau instead of declaring a
660            // false pagination end.
661            let byte_window_exhausted = window_len <= previous_window_len && read_limit >= 4096;
662            if sufficient || byte_window_exhausted {
663                if omitted_prefix {
664                    // The prefix is known to contain more native history even
665                    // when this bounded window cannot cheaply normalize its
666                    // exact size. Never turn that into a false end-of-history.
667                    candidate.imported_message_count =
668                        Some(observed_messages.max(message_limit.max(1).saturating_add(1)));
669                }
670                break (candidate, omitted_prefix);
671            }
672            previous_window_len = window_len;
673            read_limit = read_limit.saturating_mul(2);
674        };
675        if omitted_prefix {
676            session.load_residue.push(
677                "older native records remain outside this bounded display window".to_string(),
678            );
679        }
680        truncate_session_messages(&mut session, message_limit);
681        Ok(session)
682    }
683
684    fn load_with_fidelity_and_subagents(
685        path: impl AsRef<Path>,
686        fidelity: Fidelity,
687        include_subagents: bool,
688    ) -> Result<Session> {
689        let path = path.as_ref();
690        if path.is_dir() {
691            return match detect_opencode_storage_surface(path) {
692                Some((OpenCodeStorageSurface::Sqlite, db_path)) => {
693                    Self::from_opencode_sqlite(&db_path, None)
694                }
695                Some((
696                    OpenCodeStorageSurface::JsonTreeA | OpenCodeStorageSurface::JsonTreeB,
697                    _,
698                )) => Err(crate::Error::Other(format!(
699                    "{} is an OpenCode data root using a legacy JSON storage tree, which \
700                         supercode does not load directly — point `inspect`/`convert`/`resume` \
701                         at the store's `opencode*.db` SQLite file if this install has one, or \
702                         use `audit --format opencode {}` instead",
703                    path.display(),
704                    path.display()
705                ))),
706                None => Err(crate::Error::Other(format!(
707                    "{} is a directory, but no session file or OpenCode store was found in it \
708                     (expected an `opencode*.db` SQLite file, or an OpenCode legacy JSON storage \
709                     tree)",
710                    path.display()
711                ))),
712            };
713        }
714        if looks_like_sqlite(path) {
715            // Two SQLite-backed stores exist: OpenCode's (schema_meta-free
716            // key/value envelope db) and Hermes's `state.db` (UNI-15). The
717            // fingerprint check is cheap and read-only.
718            if let Ok(conn) = Connection::open_with_flags(
719                path,
720                rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY
721                    | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
722            ) {
723                if hermes_sqlite_fingerprint(&conn) {
724                    drop(conn);
725                    return Self::from_hermes_sqlite(path, None);
726                }
727            }
728            return Self::from_opencode_sqlite(path, None);
729        }
730        let text = read_utf8_or_diagnose(path)?;
731        match detect_source(&text) {
732            Some(SessionSource::Codex) => Self::from_codex_str(&text),
733            Some(SessionSource::Pi) => Self::from_pi_str(&text),
734            Some(SessionSource::OpenClaw) => {
735                let mut session = Self::from_openclaw_str(&text)?;
736                if session.meta.profile.is_none() {
737                    session.meta.profile = openclaw_agent_id_from_path(path);
738                }
739                Ok(session)
740            }
741            Some(SessionSource::Grok) => {
742                let mut session = Self::from_grok_str(&text)?;
743                session.capture_grok_path_metadata(path);
744                Ok(session)
745            }
746            Some(SessionSource::Gemini) => Self::from_gemini_str(&text),
747            Some(SessionSource::Goose) => Self::from_goose_str(&text),
748            // IX-3: a detected OpenCode session must route to its own
749            // loader, not the Claude Code fallback below
750            // (`docs/interop/build-followups.md`).
751            Some(SessionSource::OpenCode) => Self::from_opencode_str(&text),
752            _ => {
753                let mut session = Self::from_claude_code_str_with_fidelity(&text, fidelity)?;
754                if include_subagents {
755                    session.attach_claude_subagents(path, &text, fidelity)?;
756                }
757                Ok(session)
758            }
759        }
760    }
761
762    /// Reconstruct multi-file subagent trees from a flat set of loaded sessions.
763    ///
764    /// Codex stores subagents as separate rollout files linked to their parent
765    /// by `lineage["parent_thread_id"]` (→ the parent's `session_id`). Given a
766    /// collection of sessions, this nests each child into its parent's
767    /// [`Session::subagents`] and returns only the roots. Children whose parent
768    /// isn't in the set are returned as roots themselves (best effort).
769    pub fn reconstruct_tree(sessions: Vec<Session>) -> Vec<Session> {
770        use std::collections::HashMap;
771        // Index each session's position by its session_id.
772        let mut idx: HashMap<String, usize> = HashMap::new();
773        for (i, s) in sessions.iter().enumerate() {
774            if let Some(id) = &s.meta.session_id {
775                idx.insert(id.clone(), i);
776            }
777        }
778        // Determine each session's parent (by index), if present in the set.
779        let parent_of: Vec<Option<usize>> = sessions
780            .iter()
781            .map(|s| {
782                s.meta
783                    .lineage
784                    .get("parent_thread_id")
785                    .and_then(|p| idx.get(p).copied())
786            })
787            .collect();
788
789        // Move children into parents, deepest-first so chains nest correctly.
790        let mut slots: Vec<Option<Session>> = sessions.into_iter().map(Some).collect();
791        let mut order: Vec<usize> = (0..slots.len()).collect();
792        order.sort_by_key(|&i| std::cmp::Reverse(depth_of(i, &parent_of)));
793        for i in order {
794            if let Some(p) = parent_of[i] {
795                if p != i {
796                    if let Some(child) = slots[i].take() {
797                        if let Some(parent) = slots[p].as_mut() {
798                            parent.subagents.push(child);
799                        } else {
800                            slots[i] = Some(child); // parent already moved; keep as root
801                        }
802                    }
803                }
804            }
805        }
806        slots.into_iter().flatten().collect()
807    }
808
809    /// Parse a session of a known format from an in-memory JSONL string.
810    pub fn load_str(jsonl: &str, format: SessionFormat) -> Result<Session> {
811        match format {
812            SessionFormat::ClaudeCode => Self::from_claude_code_str(jsonl),
813            SessionFormat::Codex => Self::from_codex_str(jsonl),
814            SessionFormat::Pi => Self::from_pi_str(jsonl),
815            SessionFormat::OpenCode => Self::from_opencode_str(jsonl),
816            SessionFormat::Grok => Self::from_grok_str(jsonl),
817            SessionFormat::Gemini => Self::from_gemini_str(jsonl),
818            SessionFormat::Goose => Self::from_goose_str(jsonl),
819        }
820    }
821
822    /// Serialize this session to JSONL in the given format.
823    ///
824    /// The conversation is synthesized from the canonical messages, so this
825    /// works for sessions loaded from *either* tool as well as ones supercode
826    /// built itself. Converting between formats (e.g. Codex → Claude Code) is an
827    /// "export": format-specific framing that has no slot in the target may be
828    /// dropped, but the user/assistant/tool conversation is preserved.
829    pub fn to_jsonl(&self, format: SessionFormat) -> Result<String> {
830        match format {
831            SessionFormat::ClaudeCode => Ok(self.to_claude_code_jsonl()),
832            SessionFormat::Codex => Ok(self.to_codex_jsonl()),
833            SessionFormat::Pi => Ok(self.to_pi_jsonl()),
834            SessionFormat::OpenCode => self.to_opencode_jsonl(),
835            SessionFormat::Grok => Ok(self.to_grok_jsonl()),
836            SessionFormat::Gemini => Ok(self.to_gemini_jsonl()),
837            SessionFormat::Goose => Ok(self.to_goose_json()),
838        }
839    }
840
841    /// Export back to `format`, replaying the imported `raw` prefix
842    /// **verbatim** — original uuids/ids, real timestamps, and
843    /// loader-skipped records (e.g. Claude Code `file-history-snapshot`) that
844    /// [`Self::to_jsonl`]'s full synthesis discards or fakes — when `format`
845    /// is the session's own origin (`format.source() == self.meta.source`,
846    /// see [`SessionFormat::source`]) and there is a `raw` prefix to replay.
847    /// Only messages appended *after* import (tracked by
848    /// [`Self::imported_message_count`]) are synthesized, chained onto the
849    /// last original record found in the raw prefix.
850    ///
851    /// `session_id` of `Some(new)` rewrites the session id on every emitted
852    /// line, raw and synthesized alike (`sessionId` for Claude Code,
853    /// `session_meta.payload.id` for Codex); `None` leaves ids as recorded.
854    ///
855    /// Cross-format export (no verbatim prefix exists in the target dialect,
856    /// by definition) and a session with no `raw` lines both fall back
857    /// unchanged to [`Self::to_jsonl`] — full synthesis, same output as
858    /// today. A12 (SPEC.md §6): this turns "export back to origin" from
859    /// *semantic* to *near-byte* fidelity for the dominant hop-back case;
860    /// cross-format stays at the documented semantic tier.
861    pub fn to_jsonl_spliced(
862        &self,
863        format: SessionFormat,
864        session_id: Option<&str>,
865    ) -> Result<String> {
866        if self.parse_error_lines > 0
867            || self
868                .subagents
869                .iter()
870                .any(|subagent| subagent.parse_error_lines > 0)
871        {
872            return Err(Error::InvalidSession(
873                "refusing spliced export because the loaded session contains parse loss"
874                    .to_string(),
875            ));
876        }
877        if self.raw.is_empty() || format.source() != self.meta.source {
878            if let Some(session_id) = session_id {
879                let mut rewritten = self.clone();
880                rewritten.meta.session_id = Some(session_id.to_string());
881                return rewritten.to_jsonl(format);
882            }
883            return self.to_jsonl(format);
884        }
885        match format {
886            SessionFormat::ClaudeCode => Ok(self.to_claude_code_jsonl_spliced(session_id)),
887            SessionFormat::Codex => Ok(self.to_codex_jsonl_spliced(session_id)),
888            SessionFormat::Pi => self.to_pi_jsonl_spliced(session_id),
889            SessionFormat::OpenCode => self.to_opencode_jsonl_spliced(session_id),
890            SessionFormat::Grok => Ok(self.to_grok_jsonl_spliced()),
891            SessionFormat::Gemini => Ok(self.to_gemini_jsonl_spliced(session_id)),
892            SessionFormat::Goose => Ok(self.to_goose_json_spliced(session_id)),
893        }
894    }
895
896    /// Write this session to `path` in the given format.
897    pub fn save(&self, path: impl AsRef<Path>, format: SessionFormat) -> Result<()> {
898        std::fs::write(path.as_ref(), self.to_jsonl(format)?)?;
899        Ok(())
900    }
901
902    /// Reconstruct the exact source bytes this `Session` was loaded from,
903    /// out of [`Self::raw`] + [`Self::raw_trailing_newline`] (the exact
904    /// inverse of the strict-verbatim capture those two fields record — see
905    /// `join_lines_verbatim`).
906    ///
907    /// For a genuinely line-oriented source (Claude Code, Codex, Pi, and an
908    /// OpenCode *envelope*-form JSONL), `raw` is captured verbatim from the
909    /// original text, so this reproduces the original file byte-for-byte —
910    /// the P008/P009 diagonal-convert fix (`convert <file> --to
911    /// <same-format>` is byte-identical to `<file>`) is built on exactly
912    /// this. The one documented exception is an OpenCode **export-document**
913    /// source (a single pretty-printed JSON value, not JSONL): `raw` there
914    /// is RE-SYNTHESIZED as one envelope line per record (see
915    /// `from_opencode_export_doc`'s contract), so this returns a
916    /// verbatim reproduction of THAT captured representation rather than the
917    /// original pretty-printed document — a known, narrow residue, not a
918    /// silent loss (the same records are all still present).
919    pub fn raw_verbatim(&self) -> String {
920        join_lines_verbatim(&self.raw, self.raw_trailing_newline)
921    }
922
923    /// P5-5 (design §2 module 21 `session.tree`, §2.1 D-6 "session.tree →
924    /// core.session(tree-addressable transcript)"): materialize this
925    /// session's linear [`Self::messages`] into a native in-place
926    /// [`crate::session_tree::SessionTree`] — the bridge a caller uses the
927    /// FIRST time it wants to run a tree operation (rewind/branch/label)
928    /// against an otherwise-linear [`Session`]. `created_at_ms` stamps every
929    /// synthesized node (see
930    /// [`crate::session_tree::SessionTree::from_linear`]'s doc comment for
931    /// why a single timestamp is used: the source linear messages carry no
932    /// per-turn timestamp of their own here).
933    ///
934    /// This does not mutate `self` or persist anything — see
935    /// the composition layer's session-store tree writer for persistence, and
936    /// [`Self::apply_session_tree`] for the inverse bridge.
937    pub fn to_session_tree(&self, created_at_ms: i64) -> crate::session_tree::SessionTree {
938        crate::session_tree::SessionTree::from_linear(&self.messages, created_at_ms)
939    }
940
941    /// P5-5: the inverse of [`Self::to_session_tree`] — overwrite
942    /// [`Self::messages`] with `tree`'s ACTIVE branch's linear projection
943    /// (C7's "tree-with-linear-projection": this is exactly what keeps every
944    /// existing linear consumer — the agent loop, exporters — working
945    /// unchanged after a tree operation runs). Nothing else on `self`
946    /// (`meta`, `raw`, ...) is touched.
947    ///
948    /// **Fail-closed.** Propagates [`crate::session_tree::SessionTree::linear_projection`]'s
949    /// `Err` rather than applying anything — a structurally-corrupt tree
950    /// (a cycle, a dangling leaf, an active branch pointing at nothing) must
951    /// error, not silently overwrite [`Self::messages`] with an empty `Vec`.
952    /// `self` is left untouched on `Err` (the assignment only happens after
953    /// the projection has already succeeded).
954    pub fn apply_session_tree(&mut self, tree: &crate::session_tree::SessionTree) -> Result<()> {
955        self.messages = tree.linear_projection()?;
956        Ok(())
957    }
958}
959
960/// Read `path` as UTF-8 text, translating a non-UTF-8 failure into a clear,
961/// format-aware diagnostic (PARITY-16) instead of the raw "stream did not
962/// contain valid UTF-8" `io::Error` — named path, and what supercode DOES
963/// accept there. Binary SQLite input never reaches this function: callers
964/// check [`looks_like_sqlite`] first and route to
965/// [`Session::from_opencode_sqlite`] instead.
966pub(super) fn read_utf8_or_diagnose(path: &Path) -> Result<String> {
967    let bytes = std::fs::read(path)?;
968    String::from_utf8(bytes).map_err(|_| {
969        crate::Error::Other(format!(
970            "{} is not valid UTF-8 text, and is not a recognized OpenCode SQLite store \
971             (no `SQLite format 3` header) — supercode reads Claude Code / Codex / Pi / \
972             OpenCode session logs as UTF-8 JSONL, or an OpenCode `opencode*.db` SQLite file",
973            path.display()
974        ))
975    })
976}
977
978/// Read only the portion of a JSONL transcript a bounded scrollback can use.
979///
980/// The first record carries durable session metadata (especially for Codex),
981/// while the trailing window carries the messages the viewport will render.
982/// Full lossless loaders intentionally continue to read every byte.
983pub(super) fn read_display_jsonl(
984    path: &Path,
985    message_limit: usize,
986) -> Result<(Option<SessionSource>, String, bool)> {
987    const MIN_TAIL_BYTES: u64 = 4 * 1024 * 1024;
988    const MAX_TAIL_BYTES: u64 = 64 * 1024 * 1024;
989    const BYTES_PER_MESSAGE: u64 = 16 * 1024;
990
991    let mut first = String::new();
992    BufReader::new(std::fs::File::open(path)?).read_line(&mut first)?;
993    let source = detect_source(&first);
994    if !matches!(
995        source,
996        Some(SessionSource::ClaudeCode | SessionSource::Codex | SessionSource::Gemini)
997    ) {
998        let text = read_utf8_or_diagnose(path)?;
999        return Ok((detect_source(&text), text, false));
1000    }
1001
1002    let mut file = std::fs::File::open(path)?;
1003    let file_len = file.metadata()?.len();
1004    let requested = (message_limit.max(1) as u64)
1005        .saturating_mul(BYTES_PER_MESSAGE)
1006        .clamp(MIN_TAIL_BYTES, MAX_TAIL_BYTES);
1007    if file_len <= requested {
1008        let text = read_utf8_or_diagnose(path)?;
1009        return Ok((source, text, false));
1010    }
1011
1012    let start = file_len - requested;
1013    file.seek(SeekFrom::Start(start))?;
1014    let mut bytes = Vec::with_capacity(requested as usize);
1015    file.read_to_end(&mut bytes)?;
1016    // The window normally starts in the middle of a JSON record. Discard that
1017    // partial prefix so every line passed to the existing parsers is valid.
1018    if let Some(newline) = bytes.iter().position(|byte| *byte == b'\n') {
1019        bytes.drain(..=newline);
1020    }
1021    let mut tail = String::from_utf8(bytes).map_err(|_| {
1022        crate::Error::Other(format!(
1023            "{} contains non-UTF-8 data in its display window",
1024            path.display()
1025        ))
1026    })?;
1027    if start > 0 {
1028        // Always recover the human boundary immediately before the byte
1029        // window, even when the window already contains newer prompts. A
1030        // long run of large tool records can otherwise make the numeric tail
1031        // begin in one old turn while its only retained users belong to much
1032        // newer turns. The display projector then (correctly) hides the
1033        // orphaned activity, making pagination appear inert.
1034        //
1035        // Search backward independently of the render window and retain only
1036        // two complete human JSONL records. The search grows geometrically but
1037        // never reads more than the same 64 MiB hard ceiling as the display
1038        // window, and none of the intervening tool bytes are normalized or
1039        // sent over RPC.
1040        let max_search_bytes = start.min(MAX_TAIL_BYTES);
1041        let mut search_bytes = requested.min(max_search_bytes);
1042        let anchors = loop {
1043            let search_start = start - search_bytes;
1044            file.seek(SeekFrom::Start(search_start))?;
1045            let mut search = Vec::with_capacity(search_bytes as usize);
1046            (&mut file).take(search_bytes).read_to_end(&mut search)?;
1047            if search_start > 0 {
1048                if let Some(newline) = search.iter().position(|byte| *byte == b'\n') {
1049                    search.drain(..=newline);
1050                } else {
1051                    search.clear();
1052                }
1053            }
1054            // `start` normally cuts the record whose remainder the tail
1055            // reader discarded. Exclude its incomplete prefix here too.
1056            if let Some(newline) = search.iter().rposition(|byte| *byte == b'\n') {
1057                search.truncate(newline + 1);
1058            } else {
1059                search.clear();
1060            }
1061            let anchors = std::str::from_utf8(&search)
1062                .ok()
1063                .map(|search| {
1064                    let mut found = search
1065                        .lines()
1066                        .rev()
1067                        .filter(|line| native_display_human_line(line, source))
1068                        .take(2)
1069                        .map(str::to_string)
1070                        .collect::<Vec<_>>();
1071                    found.reverse();
1072                    found
1073                })
1074                .unwrap_or_default();
1075            if anchors.len() >= 2 || search_start == 0 || search_bytes == max_search_bytes {
1076                break anchors;
1077            }
1078            search_bytes = search_bytes.saturating_mul(2).min(max_search_bytes);
1079        };
1080        if !anchors.is_empty() {
1081            tail = format!("{}\n{tail}", anchors.join("\n"));
1082        }
1083    }
1084    let text = if matches!(source, Some(SessionSource::Codex | SessionSource::Gemini)) {
1085        format!("{first}{tail}")
1086    } else {
1087        tail
1088    };
1089    Ok((source, text, true))
1090}
1091
1092#[cfg(test)]
1093mod orchestration_noun_tests {
1094    use super::*;
1095
1096    #[test]
1097    fn hermes_key_parses_profile_and_surface() {
1098        let (s, p) = parse_hermes_session_key("agent:coder:telegram:group:-100777:55:u9").unwrap();
1099        assert_eq!(p.as_deref(), Some("coder"));
1100        assert_eq!(s.platform.as_deref(), Some("telegram"));
1101        assert_eq!(s.kind.as_deref(), Some("group"));
1102        assert_eq!(s.chat_id.as_deref(), Some("-100777"));
1103        assert_eq!(s.thread_id.as_deref(), Some("55"));
1104        assert_eq!(s.participant_id.as_deref(), Some("u9"));
1105        let (_, p) = parse_hermes_session_key("agent:main:telegram:dm:1").unwrap();
1106        assert!(p.is_none());
1107        assert!(parse_hermes_session_key("cron:abc").is_none());
1108    }
1109
1110    #[test]
1111    fn openclaw_keys_parse_every_documented_shape() {
1112        let (a, s, t, r) =
1113            parse_openclaw_session_key("agent:design:slack:channel:C1:thread:T2").unwrap();
1114        assert_eq!(a.as_deref(), Some("design"));
1115        assert_eq!(s.platform.as_deref(), Some("slack"));
1116        assert_eq!(s.chat_id.as_deref(), Some("C1"));
1117        assert_eq!(s.thread_id.as_deref(), Some("T2"));
1118        assert_eq!(t, Trigger::Channel);
1119        assert!(r.is_none());
1120        let (a, s, t, _) = parse_openclaw_session_key("agent:main:main").unwrap();
1121        assert_eq!(a.as_deref(), Some("main"));
1122        assert_eq!(s.kind.as_deref(), Some("main"));
1123        assert_eq!(t, Trigger::Unknown);
1124        let (_, _, t, r) = parse_openclaw_session_key("cron:job-7").unwrap();
1125        assert_eq!(t, Trigger::Cron);
1126        assert_eq!(r.unwrap().job_id, "job-7");
1127        assert_eq!(
1128            parse_openclaw_session_key("hook:gmail:m1").unwrap().2,
1129            Trigger::Webhook
1130        );
1131        assert_eq!(
1132            parse_openclaw_session_key("acp-bridge:u").unwrap().2,
1133            Trigger::Api
1134        );
1135        assert!(parse_openclaw_session_key("garbage").is_none());
1136    }
1137
1138    #[test]
1139    fn hermes_source_and_cron_ids_classify() {
1140        assert_eq!(hermes_trigger_for_source("telegram"), Trigger::Channel);
1141        assert_eq!(hermes_trigger_for_source("cli"), Trigger::Human);
1142        assert_eq!(hermes_trigger_for_source("acp"), Trigger::Human);
1143        assert_eq!(hermes_trigger_for_source("api_server"), Trigger::Api);
1144        assert_eq!(hermes_trigger_for_source("cron"), Trigger::Cron);
1145        assert_eq!(hermes_trigger_for_source(""), Trigger::Unknown);
1146        assert_eq!(
1147            hermes_cron_job_id("cron_job42_20260902_120000").as_deref(),
1148            Some("job42")
1149        );
1150        assert_eq!(
1151            hermes_cron_job_id("cron_a_b_20260902_120000").as_deref(),
1152            Some("a_b")
1153        );
1154        assert!(hermes_cron_job_id("cron_job42_2026_1200").is_none());
1155        assert!(hermes_cron_job_id("adf8a015").is_none());
1156    }
1157
1158    #[test]
1159    fn workspace_precedence_repo_over_channel_over_none() {
1160        let mut meta = SessionMeta::new(SessionSource::Hermes);
1161        assert_eq!(meta.workspace().0, WorkspaceKind::None);
1162        meta.surface = Some(SurfaceKey {
1163            platform: Some("telegram".into()),
1164            chat_id: Some("1".into()),
1165            ..Default::default()
1166        });
1167        assert_eq!(
1168            meta.workspace(),
1169            (WorkspaceKind::Channel, Some("telegram:1".into()))
1170        );
1171        meta.cwd = Some(PathBuf::from("/w"));
1172        assert_eq!(meta.workspace().0, WorkspaceKind::Repo);
1173        assert_eq!(meta.trigger_or_default(), Trigger::Human);
1174        meta.agent_id = Some("a".into());
1175        assert_eq!(meta.trigger_or_default(), Trigger::Parent);
1176    }
1177
1178    #[test]
1179    fn openclaw_agent_id_comes_from_the_agents_directory() {
1180        let p = std::path::Path::new("/home/u/.openclaw/agents/design/sessions/x.jsonl");
1181        assert_eq!(openclaw_agent_id_from_path(p).as_deref(), Some("design"));
1182        assert!(openclaw_agent_id_from_path(std::path::Path::new("/tmp/x.jsonl")).is_none());
1183    }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use super::*;
1189
1190    #[test]
1191    fn a_new_user_message_slides_the_display_tail_without_becoming_its_only_anchor() {
1192        let mut messages = vec![
1193            ChatMessage::user("original prompt"),
1194            ChatMessage::assistant("one"),
1195            ChatMessage::assistant("two"),
1196            ChatMessage::assistant("three"),
1197            ChatMessage::assistant("four"),
1198            ChatMessage::assistant("five"),
1199            ChatMessage::user("new prompt"),
1200        ];
1201
1202        truncate_messages_with_anchor(&mut messages, 4, Vec::new());
1203
1204        assert_eq!(messages.len(), 4);
1205        assert_eq!(messages[0].content.as_deref(), Some("original prompt"));
1206        assert_eq!(messages[3].content.as_deref(), Some("new prompt"));
1207    }
1208
1209    #[test]
1210    fn a_tool_heavy_current_turn_keeps_the_previous_and_current_user_anchors() {
1211        let mut messages = vec![
1212            ChatMessage::user("previous prompt"),
1213            ChatMessage::assistant("previous answer"),
1214            ChatMessage::user("current prompt"),
1215            ChatMessage::assistant("tool one"),
1216            ChatMessage::assistant("tool two"),
1217            ChatMessage::assistant("tool three"),
1218            ChatMessage::assistant("tool four"),
1219            ChatMessage::assistant("tool five"),
1220        ];
1221
1222        truncate_messages_with_anchor(&mut messages, 4, Vec::new());
1223
1224        assert_eq!(messages.len(), 4);
1225        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
1226        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
1227        assert_eq!(messages[3].content.as_deref(), Some("tool five"));
1228    }
1229
1230    #[test]
1231    fn a_preceding_user_anchor_is_restored_when_dedup_shrinks_below_the_limit() {
1232        let mut messages = vec![
1233            ChatMessage::user("current prompt"),
1234            ChatMessage::assistant("tool one"),
1235            ChatMessage::assistant("tool two"),
1236        ];
1237
1238        truncate_messages_with_anchor(&mut messages, 4, vec![ChatMessage::user("previous prompt")]);
1239
1240        assert_eq!(messages.len(), 4);
1241        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
1242        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
1243    }
1244
1245    #[test]
1246    fn a_tool_heavy_turn_restores_two_users_that_both_left_the_retention_buffer() {
1247        let mut messages = vec![
1248            ChatMessage::assistant("tool one"),
1249            ChatMessage::assistant("tool two"),
1250            ChatMessage::assistant("tool three"),
1251            ChatMessage::assistant("tool four"),
1252        ];
1253
1254        truncate_messages_with_anchor(
1255            &mut messages,
1256            4,
1257            vec![
1258                ChatMessage::user("previous prompt"),
1259                ChatMessage::user("current prompt"),
1260            ],
1261        );
1262
1263        assert_eq!(messages.len(), 4);
1264        assert_eq!(messages[0].content.as_deref(), Some("previous prompt"));
1265        assert_eq!(messages[1].content.as_deref(), Some("current prompt"));
1266        assert_eq!(messages[3].content.as_deref(), Some("tool four"));
1267    }
1268
1269    #[test]
1270    fn a_loaded_boundary_anchor_survives_several_newer_user_turns() {
1271        let mut messages = vec![
1272            ChatMessage::assistant("older tool one"),
1273            ChatMessage::assistant("older tool two"),
1274            ChatMessage::user("recent prompt one"),
1275            ChatMessage::assistant("recent answer one"),
1276            ChatMessage::user("recent prompt two"),
1277            ChatMessage::assistant("recent answer two"),
1278            ChatMessage::user("current prompt"),
1279            ChatMessage::assistant("current tool"),
1280        ];
1281
1282        truncate_messages_with_anchor(
1283            &mut messages,
1284            6,
1285            vec![ChatMessage::user("loaded earlier boundary")],
1286        );
1287
1288        assert_eq!(messages.len(), 6);
1289        assert_eq!(
1290            messages[0].content.as_deref(),
1291            Some("loaded earlier boundary"),
1292            "newer user prompts must not replace the prompt that owns the retained activity",
1293        );
1294        assert_eq!(messages[4].content.as_deref(), Some("current prompt"));
1295        assert_eq!(messages[5].content.as_deref(), Some("current tool"));
1296    }
1297
1298    #[test]
1299    fn a_bounded_byte_window_recovers_preceding_users_even_when_its_tail_has_users() {
1300        let nonce = std::time::SystemTime::now()
1301            .duration_since(std::time::UNIX_EPOCH)
1302            .unwrap()
1303            .as_nanos();
1304        let path = std::env::temp_dir().join(format!(
1305            "supercode-display-boundary-{}-{nonce}.jsonl",
1306            std::process::id()
1307        ));
1308        let user = |text: &str| {
1309            format!(
1310                r#"{{"type":"response_item","payload":{{"type":"message","role":"user","content":[{{"type":"input_text","text":"{text}"}}]}}}}"#,
1311            )
1312        };
1313        let lines = [
1314            r#"{"type":"session_meta","payload":{"id":"session-1"}}"#.to_string(),
1315            user("preceding boundary"),
1316            format!(
1317                r#"{{"type":"event_msg","payload":{{"type":"token_count","noise":"{}"}}}}"#,
1318                "x".repeat(5 * 1024 * 1024)
1319            ),
1320            user("newer prompt one"),
1321            user("newer prompt two"),
1322        ];
1323        std::fs::write(&path, format!("{}\n", lines.join("\n"))).unwrap();
1324
1325        let (_, text, omitted_prefix) = read_display_jsonl(&path, 120).unwrap();
1326        std::fs::remove_file(&path).unwrap();
1327
1328        assert!(omitted_prefix);
1329        assert!(text.contains("preceding boundary"));
1330        assert!(text.contains("newer prompt one"));
1331        assert!(text.contains("newer prompt two"));
1332    }
1333}