Skip to main content

mj_controller/
sessionwiki.rs

1//! Publishing Mjolnir's own checkpointed sessions into the user's SessionWiki
2//! index, and the daemon-side job that keeps that index current.
3//!
4//! SessionWiki keeps one searchable index of AI coding sessions across every
5//! tool a user runs. Mjolnir links it as a library and registers
6//! [`MjolnirAdapter`] beside SessionWiki's built-in adapters, so a Mjolnir
7//! session is searchable next to a Claude Code or Codex one. The adapter is a
8//! "shared store" adapter: checkpoints are not one-file-per-session in a shape
9//! SessionWiki can parse, so the indexer enumerates sessions by key and asks
10//! this adapter to parse the ones whose checkpoint changed.
11
12mod harness_adapters;
13pub(crate) mod history;
14mod provenance;
15pub mod tags;
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::time::Instant;
22
23use anyhow::{Context, Result};
24use chrono::{DateTime, Utc};
25
26use mj_client::daemon::{
27    WikiHitBlock, WikiHitTranscript, WikiIndexState, WikiRow, WikiSessionInfo, WikiSessionStatus,
28    WikiStatus,
29};
30use mj_core::config::HarnessKind;
31use mj_core::state::{SessionRecord, State};
32use sessionwiki::adapters::{Adapter, Discovered, Store};
33use sessionwiki::model::{Message, Role, Session};
34
35use crate::controller::Controller;
36use crate::controller::checkpoint::managed_checkpoint_archive_name;
37use harness_adapters::HarnessAdapter;
38
39/// The tool name every Mjolnir instance publishes under. One name means one
40/// search partition; reconciliation is scoped per instance instead (see
41/// [`Adapter::reconcile_scope`]).
42const TOOL: &str = "mjolnir";
43
44/// One checkpoint archive on disk, reduced to what indexing needs.
45struct ArchiveFile {
46    path: PathBuf,
47    frontier: u64,
48    /// Modification time in epoch seconds, SessionWiki's change token.
49    token: i64,
50}
51
52/// What indexing needs from controller state: which sessions exist, which of
53/// them are sub-agent children, and which are still running with their
54/// conversation in the daemon's own database rather than in a checkpoint.
55#[derive(Default)]
56struct Sessions {
57    records: BTreeMap<String, SessionRecord>,
58    subagent_ids: BTreeSet<String>,
59    /// Session id to change token, for sessions indexed from the projection.
60    live: BTreeMap<String, i64>,
61}
62
63impl Sessions {
64    fn of(state: &State) -> Self {
65        Self {
66            records: state.sessions.clone(),
67            subagent_ids: state.subagents.keys().cloned().collect(),
68            live: live_tokens(state),
69        }
70    }
71}
72
73/// The change token of every session whose transcript is still only in the
74/// daemon's database: its activity watermark in whole seconds.
75///
76/// A stopped session keeps being indexed from its checkpoint, which never
77/// changes again. Everything else is indexed from the projection, so a running
78/// session is findable before it has ever been closed.
79fn live_tokens(state: &State) -> BTreeMap<String, i64> {
80    let activity = match crate::database::load_transcribed_session_activity() {
81        Ok(activity) => activity,
82        Err(error) => {
83            tracing::warn!(%error, "could not read session activity for SessionWiki");
84            return BTreeMap::new();
85        }
86    };
87    state
88        .sessions
89        .iter()
90        .filter(|(_, record)| record.state != mj_core::state::SessionState::Stopped)
91        .filter_map(|(session_id, _)| {
92            let watermark = activity.get(session_id)?;
93            Some((session_id.clone(), watermark.unwrap_or_default() / 1000))
94        })
95        .collect()
96}
97
98/// Mjolnir's sessions, as SessionWiki sees them.
99pub struct MjolnirAdapter {
100    sessions_dir: PathBuf,
101    sessions: std::sync::Mutex<Sessions>,
102    /// Re-read controller state when the indexer reaches this adapter.
103    reload: bool,
104}
105
106impl MjolnirAdapter {
107    /// A fixed view of the given state, which is what a caller with a state in
108    /// hand wants.
109    pub fn from_state(state: &State) -> Self {
110        Self {
111            sessions_dir: mj_core::config::sessions_dir(),
112            sessions: std::sync::Mutex::new(Sessions::of(state)),
113            reload: false,
114        }
115    }
116
117    /// The same, but re-reading controller state when the indexer reaches this
118    /// adapter.
119    ///
120    /// One sync pass walks every other tool's store first, which can take
121    /// minutes on a large corpus. Without the reload, sessions that closed
122    /// during that walk would be indexed with no record: no project, no start
123    /// time, and the title guessed from the first prompt. Their checkpoints do
124    /// not change afterwards, so nothing would ever correct them.
125    pub fn reloading(state: &State) -> Self {
126        Self {
127            reload: true,
128            ..Self::from_state(state)
129        }
130    }
131
132    /// Mjolnir's own metadata for every session this adapter knows about, to
133    /// be stored in the index beside the transcripts.
134    ///
135    /// Read from the adapter's own snapshot rather than from the controller
136    /// state the sync loaded, because [`MjolnirAdapter::reloading`] replaces
137    /// that snapshot when the indexer reaches this adapter. A session that
138    /// closed during a long first pass is indexed from the reloaded state, so
139    /// its metadata has to come from the same state that produced its row.
140    pub fn indexed_tags(&self) -> BTreeMap<String, tags::MjTags> {
141        let sessions = self
142            .sessions
143            .lock()
144            .unwrap_or_else(std::sync::PoisonError::into_inner);
145        sessions
146            .records
147            .iter()
148            .map(|(session_id, record)| {
149                (
150                    session_id.clone(),
151                    tags::MjTags {
152                        target: Some(record.target_template_id.clone()).filter(|id| !id.is_empty()),
153                        profile: Some(record.last_profile.clone()).filter(|id| !id.is_empty()),
154                        harness: Some(record.harness_kind.id().to_owned()),
155                    },
156                )
157            })
158            .collect()
159    }
160
161    fn reload(&self) {
162        if !self.reload {
163            return;
164        }
165        match Controller::load() {
166            Ok(controller) => {
167                *self
168                    .sessions
169                    .lock()
170                    .unwrap_or_else(std::sync::PoisonError::into_inner) =
171                    Sessions::of(&controller.state)
172            }
173            Err(error) => {
174                tracing::warn!(%error, "could not refresh session records for SessionWiki")
175            }
176        }
177    }
178
179    /// The conversation of a stopped session, read from its newest checkpoint,
180    /// with the title the checkpoint recorded.
181    fn checkpointed_transcript(&self, session_id: &str) -> Result<IndexedTranscript> {
182        let (newest, _) = self.newest_archives();
183        let archive = newest
184            .get(session_id)
185            .with_context(|| format!("no checkpoint archive for session {session_id}"))?;
186        let snapshot = mj_checkpoint::archive::read_archive_verified(&archive.path)
187            .with_context(|| format!("read checkpoint {}", archive.path.display()))?
188            .canonical_session()
189            .with_context(|| format!("read the transcript of session {session_id}"))?;
190        let mut evidence = provenance::Evidence::default();
191        for item in &snapshot.transcript {
192            if let mj_core::archive::CanonicalTranscriptBody::Tool { call, .. } = &item.body {
193                evidence.observe(call, item.created_at_ms);
194            }
195        }
196        let messages = summary_messages(mj_transcript::summary::TranscriptSummary::from_snapshot(
197            &snapshot,
198        ));
199        Ok(IndexedTranscript {
200            messages,
201            title: snapshot.session.session_title.clone(),
202            evidence,
203        })
204    }
205
206    /// The conversation of a session that has not stopped, read from the
207    /// daemon's own projection. It is the same conversation the checkpoint
208    /// would hold, minus whatever has not happened yet.
209    fn projected_transcript(&self, session_id: &str) -> Result<IndexedTranscript> {
210        let projection = crate::database::load_materialized_session(session_id)
211            .with_context(|| format!("read the stored transcript of session {session_id}"))?
212            .with_context(|| format!("no stored transcript for session {session_id}"))?;
213        let mut evidence = provenance::Evidence::default();
214        for item in &projection.transcript {
215            if let mj_core::state::TranscriptBody::Tool { call, .. } = &item.body {
216                evidence.observe(call, item.created_at_ms);
217            }
218        }
219        Ok(IndexedTranscript {
220            messages: projected_messages(&projection),
221            title: projection.session_title.clone(),
222            evidence,
223        })
224    }
225
226    /// The stable key for one session: its checkpoint directory and id. The
227    /// directory is per instance, which is what scopes reconciliation.
228    fn key_for(&self, session_id: &str) -> String {
229        format!("{}/{session_id}", self.sessions_dir.display())
230    }
231
232    /// The newest checkpoint of every session in the directory, by session id.
233    ///
234    /// `had_error` is true when the directory exists but could not be read in
235    /// full; the indexer then skips deletion reconciliation rather than
236    /// archiving every Mjolnir session off a partial listing.
237    fn newest_archives(&self) -> (BTreeMap<String, ArchiveFile>, bool) {
238        let mut newest: BTreeMap<String, ArchiveFile> = BTreeMap::new();
239        let mut had_error = false;
240        let entries = match std::fs::read_dir(&self.sessions_dir) {
241            Ok(entries) => entries,
242            Err(error) => {
243                if self.sessions_dir.exists() {
244                    tracing::debug!(
245                        directory = %self.sessions_dir.display(),
246                        %error,
247                        "could not list the checkpoint directory for SessionWiki"
248                    );
249                    had_error = true;
250                }
251                return (newest, had_error);
252            }
253        };
254        for entry in entries {
255            let Ok(entry) = entry else {
256                had_error = true;
257                continue;
258            };
259            let Some((session_id, frontier)) = checkpoint_archive_session(&entry.file_name())
260            else {
261                continue;
262            };
263            let token = entry
264                .metadata()
265                .ok()
266                .and_then(|metadata| metadata.modified().ok())
267                .and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok())
268                .map(|age| age.as_secs() as i64)
269                .unwrap_or(0);
270            let candidate = ArchiveFile {
271                path: entry.path(),
272                frontier,
273                token,
274            };
275            match newest.get(&session_id) {
276                Some(existing) if existing.frontier >= candidate.frontier => {}
277                _ => {
278                    newest.insert(session_id, candidate);
279                }
280            }
281        }
282        (newest, had_error)
283    }
284}
285
286struct IndexedTranscript {
287    messages: Vec<Message>,
288    title: Option<String>,
289    evidence: provenance::Evidence,
290}
291
292/// The session a checkpoint file name belongs to, with its generation.
293///
294/// Managed checkpoints carry a frontier and a nonce; an imported archive is
295/// named for its session alone and counts as generation zero.
296fn checkpoint_archive_session(name: &std::ffi::OsStr) -> Option<(String, u64)> {
297    if let Some(parsed) = managed_checkpoint_archive_name(name) {
298        return Some((parsed.session_id, parsed.frontier));
299    }
300    let stem = name
301        .to_str()
302        .and_then(|name| name.strip_suffix(".hel.zip"))?;
303    mj_core::config::validate_id("session", stem)
304        .is_ok()
305        .then(|| (stem.to_owned(), 0))
306}
307
308/// A running session's conversation, as SessionWiki stores it.
309fn projected_messages(projection: &mj_core::state::MaterializedSession) -> Vec<Message> {
310    summary_messages(mj_transcript::summary::TranscriptSummary::from_materialized(projection))
311}
312
313fn summary_messages(summary: mj_transcript::summary::TranscriptSummary) -> Vec<Message> {
314    use mj_transcript::summary::SummaryRole;
315    summary
316        .entries
317        .into_iter()
318        .filter_map(|entry| {
319            let role = match entry.role {
320                SummaryRole::User => Role::User,
321                SummaryRole::Assistant => Role::Assistant,
322                SummaryRole::Tool => Role::Tool,
323                SummaryRole::Plan => return None,
324            };
325            message(role, entry.body(), entry.created_at_ms)
326        })
327        .collect()
328}
329
330/// One indexed message, or nothing when the item carried no text.
331fn message(role: Role, text: String, created_at_ms: i64) -> Option<Message> {
332    let text = text.trim().to_owned();
333    (!text.is_empty()).then(|| Message {
334        role,
335        text,
336        ts: DateTime::from_timestamp_millis(created_at_ms),
337    })
338}
339
340fn parse_time(value: &str) -> Option<DateTime<Utc>> {
341    DateTime::parse_from_rfc3339(value)
342        .ok()
343        .map(|time| time.with_timezone(&Utc))
344}
345
346impl Adapter for MjolnirAdapter {
347    fn name(&self) -> &'static str {
348        TOOL
349    }
350
351    fn root(&self) -> Option<PathBuf> {
352        Some(self.sessions_dir.clone())
353    }
354
355    /// Unused: this is a shared-store adapter, so the indexer enumerates
356    /// sessions through [`Adapter::store`] instead of walking files.
357    fn discover(&self) -> Discovered {
358        Discovered {
359            files: Vec::new(),
360            had_error: false,
361        }
362    }
363
364    fn parse(&self, _path: &Path) -> Result<Session> {
365        anyhow::bail!("Mjolnir sessions are parsed by key, not by file")
366    }
367
368    fn store(&self) -> Option<Store> {
369        self.reload();
370        let (newest, had_error) = self.newest_archives();
371        let mut files = Vec::with_capacity(newest.len());
372        let mut tokens: BTreeMap<String, i64> = BTreeMap::new();
373        for (session_id, archive) in newest {
374            tokens.insert(session_id, archive.token);
375            files.push(archive.path);
376        }
377        // A session that is still running is indexed from the projection, and
378        // its own token replaces any checkpoint token it has: the conversation
379        // has moved on since that checkpoint was written. Listing it also
380        // keeps reconciliation from archiving a running session.
381        let sessions = self
382            .sessions
383            .lock()
384            .unwrap_or_else(std::sync::PoisonError::into_inner);
385        let live = sessions.live.clone();
386        tokens.extend(live);
387        // A rename changes the record and not the conversation, so the
388        // record's own last update is part of the change token. Without it a
389        // renamed session would keep its old title in the index for as long as
390        // its transcript stood still.
391        for (session_id, token) in tokens.iter_mut() {
392            let updated = sessions
393                .records
394                .get(session_id)
395                .and_then(|record| parse_time(&record.updated_at))
396                .map(|updated| updated.timestamp());
397            if let Some(updated) = updated {
398                *token = (*token).max(updated);
399            }
400        }
401        let keys = tokens
402            .into_iter()
403            .map(|(session_id, token)| {
404                (
405                    self.key_for(&session_id),
406                    token
407                        .saturating_mul(1024)
408                        .saturating_add(i64::from(mj_transcript::summary::SUMMARY_VERSION)),
409                )
410            })
411            .collect();
412        Some(Store {
413            keys,
414            files,
415            had_error,
416        })
417    }
418
419    /// Every Mjolnir instance publishes under one tool name, so this instance
420    /// speaks only for keys under its own checkpoint directory. Without the
421    /// scope, two instances would archive each other's rows on every sync.
422    fn reconcile_scope(&self) -> Option<String> {
423        Some(format!("{}/", self.sessions_dir.display()))
424    }
425
426    fn parse_key(&self, key: &str) -> Result<Session> {
427        let session_id = key.rsplit('/').next().unwrap_or_default();
428        anyhow::ensure!(!session_id.is_empty(), "no session id in key {key:?}");
429        let sessions = self
430            .sessions
431            .lock()
432            .unwrap_or_else(std::sync::PoisonError::into_inner);
433        let IndexedTranscript {
434            messages,
435            title: snapshot_title,
436            evidence,
437        } = if sessions.live.contains_key(session_id) {
438            self.projected_transcript(session_id)?
439        } else {
440            self.checkpointed_transcript(session_id)?
441        };
442        let record = sessions.records.get(session_id);
443
444        let title = record
445            .and_then(|record| record.session_title_override.clone())
446            .or_else(|| record.and_then(|record| record.acp_session_title.clone()))
447            .or_else(|| snapshot_title.clone())
448            .unwrap_or_else(|| {
449                messages
450                    .iter()
451                    .find(|message| message.role == Role::User)
452                    .map(|message| message.text.chars().take(80).collect())
453                    .unwrap_or_default()
454            });
455
456        Ok(Session {
457            id: session_id.to_owned(),
458            tool: TOOL,
459            path: PathBuf::from(key),
460            project: record
461                .and_then(|record| record.project_directory.as_ref())
462                .map(|directory| directory.display().to_string())
463                .unwrap_or_default(),
464            started: record.and_then(|record| parse_time(&record.created_at)),
465            ended: record.and_then(|record| parse_time(&record.updated_at)),
466            title,
467            subagent: sessions.subagent_ids.contains(session_id),
468            messages,
469            touched: evidence.paths.into_iter().collect(),
470            edits: evidence.edits,
471        })
472    }
473}
474
475/// The Mjolnir adapter handed to the indexer while the sync keeps its own
476/// handle on it.
477///
478/// The indexer takes `Box<dyn Adapter>` and consumes the list, but the sync has
479/// to ask the same adapter for its final session snapshot once the walk is over
480/// (see [`MjolnirAdapter::indexed_tags`]). Sharing the adapter is the only way
481/// both can hold it.
482struct SharedMjolnirAdapter(Arc<MjolnirAdapter>);
483
484impl Adapter for SharedMjolnirAdapter {
485    fn name(&self) -> &'static str {
486        self.0.name()
487    }
488
489    fn root(&self) -> Option<PathBuf> {
490        self.0.root()
491    }
492
493    fn discover(&self) -> Discovered {
494        self.0.discover()
495    }
496
497    fn parse(&self, path: &Path) -> Result<Session> {
498        self.0.parse(path)
499    }
500
501    fn store(&self) -> Option<Store> {
502        self.0.store()
503    }
504
505    fn parse_key(&self, key: &str) -> Result<Session> {
506        self.0.parse_key(key)
507    }
508
509    fn reconcile_scope(&self) -> Option<String> {
510        self.0.reconcile_scope()
511    }
512}
513
514/// The daemon's SessionWiki sync job.
515///
516/// Triggers coalesce: a request while a sync is running marks a rerun instead
517/// of queueing a second one, so a burst of closing sessions costs one extra
518/// pass. Syncs are single-flight because SessionWiki holds a write transaction
519/// per adapter batch, and two writers only produce a busy error.
520pub struct WikiIndexer {
521    inner: Arc<Indexer>,
522}
523
524#[derive(Default)]
525struct Indexer {
526    /// Held for the whole of one run: this is what makes syncs single-flight.
527    running: tokio::sync::Mutex<()>,
528    notify: tokio::sync::Notify,
529    /// A trigger arrived; the worker has not consumed it yet.
530    requested: AtomicBool,
531    /// At least one waiting trigger asked for a full sync.
532    full_requested: AtomicBool,
533    /// A sync pass is running now. A surface shows this as "topping up", so a
534    /// user knows more results may arrive.
535    in_flight: AtomicBool,
536    last_success: std::sync::Mutex<Option<Success>>,
537}
538
539#[derive(Clone, Copy)]
540struct Success {
541    at: Instant,
542    epoch_seconds: i64,
543}
544
545impl WikiIndexer {
546    /// Start the background sync worker. Without a Tokio runtime (some tests
547    /// build a runtime state without one) the indexer stays inert.
548    pub fn spawn() -> Self {
549        let inner = Arc::new(Indexer::default());
550        if let Ok(handle) = tokio::runtime::Handle::try_current() {
551            let worker = Arc::clone(&inner);
552            handle.spawn(async move { worker.run().await });
553        }
554        Self { inner }
555    }
556
557    /// Ask for a sync. Returns immediately; the work happens in the background.
558    pub fn request_sync(&self, full: bool) {
559        if full {
560            self.inner.full_requested.store(true, Ordering::Release);
561        }
562        self.inner.requested.store(true, Ordering::Release);
563        self.inner.notify.notify_one();
564    }
565
566    /// Run a sync and wait for it, joining a sync already in flight.
567    pub async fn sync_now(&self, full: bool) -> Result<()> {
568        self.inner.sync(full).await
569    }
570
571    /// The state of the index and whether a sync is running, for the surfaces
572    /// that say so while the first build is under way.
573    pub fn status(&self) -> WikiStatus {
574        WikiStatus {
575            state: index_state(),
576            topping_up: self.inner.in_flight.load(Ordering::Acquire)
577                || self.inner.requested.load(Ordering::Acquire),
578        }
579    }
580
581    /// When the last sync succeeded, for callers that trigger on staleness.
582    pub fn last_success(&self) -> Option<Instant> {
583        self.inner
584            .last_success
585            .lock()
586            .unwrap_or_else(std::sync::PoisonError::into_inner)
587            .map(|success| success.at)
588    }
589}
590
591impl Indexer {
592    async fn run(self: Arc<Self>) {
593        loop {
594            self.notify.notified().await;
595            while self.requested.swap(false, Ordering::AcqRel) {
596                let full = self.full_requested.swap(false, Ordering::AcqRel);
597                if let Err(error) = self.sync(full).await {
598                    self.report(&error);
599                    // A failure waits for the next trigger rather than
600                    // retrying straight away: a busy index stays busy for as
601                    // long as the other writer holds it, and a spin would only
602                    // add to the contention.
603                    break;
604                }
605            }
606        }
607    }
608
609    /// Log a failed sync at the level its cause deserves. A busy index is an
610    /// expected collision with another writer, not a fault: mark a rerun and
611    /// say so only in debug output.
612    fn report(&self, error: &anyhow::Error) {
613        if crate::database::is_busy_error(error) {
614            self.requested.store(true, Ordering::Release);
615            tracing::debug!(%error, "the SessionWiki index was busy; retrying on the next trigger");
616        } else {
617            tracing::warn!(%error, "could not sync sessions into SessionWiki");
618        }
619    }
620
621    async fn sync(&self, full: bool) -> Result<()> {
622        let _guard = self.running.lock().await;
623        let since = if full {
624            None
625        } else {
626            self.last_success
627                .lock()
628                .unwrap_or_else(std::sync::PoisonError::into_inner)
629                // A minute of overlap covers checkpoints written while the
630                // previous run was reading the directory.
631                .map(|success| success.epoch_seconds - 60)
632        };
633        let started = Instant::now();
634        self.in_flight.store(true, Ordering::Release);
635        let ran = tokio::task::spawn_blocking(move || sync_blocking(since)).await;
636        self.in_flight.store(false, Ordering::Release);
637        let ran = ran.context("run the SessionWiki sync")??;
638        if ran {
639            *self
640                .last_success
641                .lock()
642                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Success {
643                at: started,
644                epoch_seconds: Utc::now().timestamp(),
645            });
646        }
647        Ok(())
648    }
649}
650
651/// One synchronous sync pass. Returns false when this process must not touch
652/// the index, so a refused run never records a success it did not have.
653fn sync_blocking(since: Option<i64>) -> Result<bool> {
654    if !index_is_writable() {
655        return Ok(false);
656    }
657    let controller =
658        Controller::load().context("load controller state for the SessionWiki sync")?;
659    // Mjolnir's own sessions go first: a cold index walks every other tool's
660    // store for many minutes, and a just-closed session should not wait on it.
661    let mjolnir = Arc::new(MjolnirAdapter::reloading(&controller.state));
662    let mut adapters: Vec<Box<dyn sessionwiki::adapters::Adapter>> =
663        vec![Box::new(SharedMjolnirAdapter(Arc::clone(&mjolnir)))];
664    adapters.extend(native_adapters(&controller.config));
665    let mut connection = sessionwiki::index::open().context("open the SessionWiki index")?;
666    sessionwiki::index::sync_with(&mut connection, &adapters, since)
667        .context("sync the SessionWiki index")?;
668    write_session_tags(&mut connection, &mjolnir.indexed_tags())
669        .context("store Mjolnir's session metadata in the SessionWiki index")?;
670    provenance::backfill(&mut connection, &mjolnir).context("backfill Mjolnir file provenance")?;
671    if since.is_none() {
672        // A full pass has walked every store, so the index is complete enough
673        // for a search to be trusted. The marker is what a later daemon reads
674        // instead of walking the corpus again to find out.
675        record_first_build();
676    }
677    Ok(true)
678}
679
680/// Store each session's target, profile and harness in the index, in one
681/// transaction.
682///
683/// Every session is written on every sync rather than only the changed ones:
684/// the write is a delete and three inserts, which is nothing beside the
685/// transcript indexing in the same pass, and it is what makes a Move or a
686/// profile switch show up without tracking which records changed. It is also
687/// what gives sessions indexed before this existed their metadata, with no
688/// migration and no re-index.
689fn write_session_tags(
690    connection: &mut rusqlite::Connection,
691    session_tags: &BTreeMap<String, tags::MjTags>,
692) -> Result<()> {
693    if session_tags.is_empty() {
694        return Ok(());
695    }
696    let transaction = connection
697        .transaction()
698        .context("open a transaction for the session metadata")?;
699    for (session_id, session) in session_tags {
700        if session.is_empty() {
701            continue;
702        }
703        tags::write(&transaction, session_id, session)?;
704    }
705    transaction
706        .commit()
707        .context("commit the session metadata")?;
708    Ok(())
709}
710
711/// The non-Mjolnir adapters this install indexes.
712///
713/// Mjolnir's configured harness profiles decide which harness homes are
714/// indexed, not the stock `~/.codex` and `~/.claude` locations. A user who
715/// runs several profile homes expects every session Mjolnir can start to be
716/// searchable, and a home no profile names is not Mjolnir's to walk. So the
717/// stock Codex and Claude adapters are dropped and one adapter per enabled
718/// profile home takes their place; every other built-in adapter is kept as is.
719///
720/// Kimi Code, Grok Build and Muse have no SessionWiki adapter at all, so
721/// Mjolnir supplies one per enabled profile home of its own (see
722/// [`harness_adapters`]). Without them those sessions would never appear in
723/// the Resume dialog's search.
724///
725/// Each per-home adapter reports a reconcile scope covering only its own root,
726/// so a sync of one install never archives the rows of another.
727fn native_adapters(config: &mj_core::config::Config) -> Vec<Box<dyn Adapter>> {
728    // Two profiles may share one home, and two harnesses may share one home
729    // path without sharing sessions, so the kind is part of the identity.
730    let mut seen: BTreeSet<(HarnessKind, &Path)> = BTreeSet::new();
731    let mut adapters: Vec<Box<dyn Adapter>> = Vec::new();
732    for (_, profile) in config.enabled_profiles() {
733        // A second adapter for the same home would only walk it twice.
734        if !seen.insert((profile.kind, profile.home.as_path())) {
735            continue;
736        }
737        let adapter: Box<dyn Adapter> = match profile.kind {
738            HarnessKind::Codex => {
739                Box::new(sessionwiki::adapters::Codex::in_home(profile.home.clone()))
740            }
741            HarnessKind::Claude => Box::new(sessionwiki::adapters::ClaudeCode::in_home(
742                profile.home.clone(),
743            )),
744            kind => match HarnessAdapter::in_home(kind, profile.home.clone()) {
745                Some(adapter) => Box::new(adapter),
746                None => continue,
747            },
748        };
749        adapters.push(adapter);
750    }
751    adapters.extend(
752        sessionwiki::adapters::all()
753            .into_iter()
754            .filter(|adapter| !matches!(adapter.name(), "codex" | "claude-code")),
755    );
756    adapters
757}
758
759// ---------------------------------------------------------------------------
760// Which index, and whether it may be touched
761// ---------------------------------------------------------------------------
762
763/// Whether this process may open the index at all.
764///
765/// Indexing is always on, so a process that never resolved where its index
766/// belongs must not reach for one: it would walk the user's real session
767/// stores and write the user's real index. Only Mjolnir's own startup resolves
768/// it (see `mj_core::config::apply_instance_flag`), so this refuses every unit
769/// test that builds a daemon runtime directly and every other embedder, unless
770/// it names an index of its own with `SESSIONWIKI_DATA`.
771fn index_is_isolated() -> bool {
772    static SAID: AtomicBool = AtomicBool::new(false);
773    if mj_core::config::session_index_is_resolved()
774        || std::env::var_os(mj_core::config::SESSION_INDEX_ENV).is_some()
775    {
776        return true;
777    }
778    if !SAID.swap(true, Ordering::AcqRel) {
779        tracing::debug!(
780            "this process did not resolve a session index location; SessionWiki is not used"
781        );
782    }
783    false
784}
785
786/// Whether the index on disk was written by a SessionWiki at another schema
787/// version.
788///
789/// SessionWiki's own `open` drops and rebuilds its whole cache when the file's
790/// `user_version` differs from the version it was built with, which on a large
791/// corpus costs tens of minutes. Mjolnir will not do that to a user who also
792/// runs the `sessionwiki` command: it reads the version without SessionWiki and
793/// stands aside.
794fn index_version_mismatch() -> bool {
795    static SAID: AtomicBool = AtomicBool::new(false);
796    let Ok(path) = sessionwiki::index::db_path() else {
797        return false;
798    };
799    if !path.exists() {
800        return false;
801    }
802    let version = rusqlite::Connection::open_with_flags(
803        &path,
804        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_URI,
805    )
806    .and_then(|connection| connection.pragma_query_value(None, "user_version", |row| row.get(0)));
807    let version: i64 = match version {
808        Ok(version) => version,
809        Err(error) => {
810            tracing::debug!(%error, "could not read the SessionWiki index schema version");
811            return false;
812        }
813    };
814    // Zero is an index SessionWiki has not finished creating; it is not a
815    // different version.
816    let mismatch = version != 0 && version != sessionwiki::index::SCHEMA_VERSION;
817    if mismatch && !SAID.swap(true, Ordering::AcqRel) {
818        tracing::warn!(
819            found = version,
820            expected = sessionwiki::index::SCHEMA_VERSION,
821            path = %path.display(),
822            "the SessionWiki index was written by another version;              Mjolnir will not open it, because opening it would rebuild it.              Install the matching sessionwiki command"
823        );
824    }
825    mismatch
826}
827
828fn index_is_writable() -> bool {
829    index_is_isolated() && !index_version_mismatch()
830}
831
832/// The file recording that one full sync has completed, holding the schema
833/// version it completed at.
834fn first_build_marker() -> PathBuf {
835    mj_core::config::data_dir().join("sessionwiki-built")
836}
837
838fn record_first_build() {
839    let path = first_build_marker();
840    let version = sessionwiki::index::SCHEMA_VERSION.to_string();
841    if std::fs::read_to_string(&path).is_ok_and(|held| held.trim() == version) {
842        return;
843    }
844    if let Err(error) = std::fs::write(&path, &version) {
845        tracing::warn!(%error, path = %path.display(), "could not record the first SessionWiki build");
846    }
847}
848
849/// Whether this index has completed a full build at this schema version.
850fn first_build_is_done() -> bool {
851    std::fs::read_to_string(first_build_marker())
852        .is_ok_and(|held| held.trim() == sessionwiki::index::SCHEMA_VERSION.to_string())
853        && sessionwiki::index::db_path().is_ok_and(|path| path.exists())
854}
855
856/// What a surface should say about this index right now.
857pub fn index_state() -> WikiIndexState {
858    if !index_is_isolated() {
859        return WikiIndexState::Indexing;
860    }
861    if index_version_mismatch() {
862        return WikiIndexState::VersionMismatch;
863    }
864    if first_build_is_done() {
865        WikiIndexState::Ready
866    } else {
867        WikiIndexState::Indexing
868    }
869}
870
871// ---------------------------------------------------------------------------
872// Queries and restore
873// ---------------------------------------------------------------------------
874
875/// The largest page a caller may ask a wiki query for.
876pub const MAX_WIKI_LIMIT: usize = 200;
877/// The page size a caller that names none gets.
878pub const DEFAULT_WIKI_LIMIT: usize = 50;
879/// SessionWiki's full-text index needs three characters; shorter queries fall
880/// back to a substring scan.
881const MIN_FULLTEXT_QUERY: usize = 3;
882/// How stale the index may be before a query triggers a background sync.
883pub const SYNC_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
884
885/// Whether a query should trigger a bounded background sync before it answers.
886pub fn sync_is_stale(last_success: Option<Instant>) -> bool {
887    last_success.is_none_or(|at| at.elapsed() >= SYNC_STALE_AFTER)
888}
889
890/// One page of the index, newest first or best match first.
891///
892/// `live` is the set of session ids this daemon still holds, which is what
893/// decides whether a Mjolnir row names a session the user can simply resume.
894/// Runs SQLite work, so callers on the async runtime wrap it in
895/// `spawn_blocking`.
896pub fn query_rows(query: &str, limit: usize, live: &BTreeSet<String>) -> Result<Vec<WikiRow>> {
897    let limit = limit.clamp(1, MAX_WIKI_LIMIT);
898    if !index_is_writable() {
899        // Nothing to answer from: either this process has no index of its own
900        // or the one on disk is at another version. The status beside the rows
901        // says which.
902        return Ok(Vec::new());
903    }
904    let connection = open_readonly()?;
905    let query = query.trim();
906    if query.is_empty() {
907        let rows = sessionwiki::index::recent(&connection, limit, None, None, None, false)
908            .context("list recent SessionWiki sessions")?;
909        let mut rows: Vec<WikiRow> = rows
910            .into_iter()
911            .map(|row| wiki_row(row, None, live))
912            .collect();
913        fill_session_tags(&connection, &mut rows)?;
914        return Ok(rows);
915    }
916    let hits = if query.chars().count() < MIN_FULLTEXT_QUERY {
917        sessionwiki::index::search_like(&connection, query, limit, None, None)
918    } else {
919        sessionwiki::index::search(&connection, query, limit, None, None)
920    }
921    .context("search the SessionWiki index")?;
922    let mut rows: Vec<WikiRow> = hits
923        .into_iter()
924        .map(|hit| wiki_row(hit.row, Some(hit.snippet), live))
925        .collect();
926    // SessionWiki searches message text alone, so a session known by a title
927    // or a project that is never said out loud would be unfindable. Those
928    // matches follow the full-text ones rather than displacing them.
929    let found: BTreeSet<String> = rows.iter().map(|row| row.id.clone()).collect();
930    for row in named_like(&connection, query)? {
931        if rows.len() >= limit {
932            break;
933        }
934        if found.contains(&row.session_id) {
935            continue;
936        }
937        rows.push(wiki_row(row, None, live));
938    }
939    fill_session_tags(&connection, &mut rows)?;
940    Ok(rows)
941}
942
943/// Fill in the target, profile and harness of every Mjolnir row on this page
944/// from the index's own tags, in one query.
945///
946/// Only Mjolnir writes those tags, so a row from another tool keeps `None` and
947/// is not even asked about.
948fn fill_session_tags(connection: &rusqlite::Connection, rows: &mut [WikiRow]) -> Result<()> {
949    let ids: Vec<&str> = rows
950        .iter()
951        .filter(|row| row.tool == TOOL)
952        .map(|row| row.id.as_str())
953        .collect();
954    let found = tags::read(connection, &ids).context("read the indexed session metadata")?;
955    for row in rows.iter_mut().filter(|row| row.tool == TOOL) {
956        let Some(session) = found.get(&row.id) else {
957            continue;
958        };
959        row.target = session.target.clone();
960        row.profile = session.profile.clone();
961        row.harness = session.harness.clone();
962    }
963    Ok(())
964}
965
966/// How far back a title or project match looks. Those columns have no index of
967/// their own, so this is a scan of the most recent sessions rather than of the
968/// whole corpus.
969const NAME_SCAN_LIMIT: usize = 2_000;
970
971/// Indexed sessions whose title or project contains the query, ignoring case.
972fn named_like(
973    connection: &rusqlite::Connection,
974    query: &str,
975) -> Result<Vec<sessionwiki::index::SessionRow>> {
976    let needle = query.to_lowercase();
977    let rows = sessionwiki::index::recent(connection, NAME_SCAN_LIMIT, None, None, None, false)
978        .context("list recent SessionWiki sessions")?;
979    Ok(rows
980        .into_iter()
981        .filter(|row| {
982            row.title.to_lowercase().contains(&needle)
983                || row.project.to_lowercase().contains(&needle)
984        })
985        .collect())
986}
987
988/// The briefing for one indexed session, or `None` when the id names none.
989pub fn brief(id: &str, max_chars: usize) -> Result<Option<String>> {
990    if !index_is_writable() {
991        return Ok(None);
992    }
993    let connection = open_readonly()?;
994    let Some(row) = row_by_id(&connection, id)? else {
995        return Ok(None);
996    };
997    let session = sessionwiki::index::session_from_index(&connection, &row)
998        .context("read an indexed session")?;
999    Ok(Some(sessionwiki::commands::brief_markdown(
1000        &session, max_chars, true,
1001    )))
1002}
1003
1004/// The passages of one indexed session that match `query`, or `None` when the
1005/// id names no indexed session.
1006///
1007/// Every matching message is returned with `context_messages` neighbours on
1008/// each side; overlapping groups are merged and each group's first block says
1009/// how many messages were skipped before it. Each block's text is capped at
1010/// `per_message_chars` characters, keeping the window around its first match.
1011pub fn transcript_hits(
1012    id: &str,
1013    query: &str,
1014    context_messages: usize,
1015    per_message_chars: usize,
1016) -> Result<Option<WikiHitTranscript>> {
1017    if !index_is_writable() {
1018        return Ok(None);
1019    }
1020    let connection = open_readonly()?;
1021    let Some(row) = row_by_id(&connection, id)? else {
1022        return Ok(None);
1023    };
1024    let session = sessionwiki::index::session_from_index(&connection, &row)
1025        .context("read an indexed session")?;
1026    Ok(Some(hit_transcript(
1027        &session,
1028        query,
1029        context_messages,
1030        per_message_chars,
1031    )))
1032}
1033
1034/// The matching passages of one loaded session, converted from SessionWiki's
1035/// own grep. Pure, so the conversion can be tested without an index on disk.
1036///
1037/// Matching, redaction and the excerpt window are `sessionwiki::grep`'s, so the
1038/// `sessionwiki grep` CLI and this preview report the same hits. Tool output
1039/// never anchors a passage: it is machine chatter the reader did not write,
1040/// a hit buried in it would open the preview on a wall of command output, and
1041/// the preview collapses tool runs anyway. Tool messages still appear as
1042/// context around a real match.
1043fn hit_transcript(
1044    session: &Session,
1045    query: &str,
1046    context_messages: usize,
1047    per_message_chars: usize,
1048) -> WikiHitTranscript {
1049    let found = sessionwiki::grep::grep_session(
1050        session,
1051        query,
1052        &sessionwiki::grep::GrepOpts {
1053            context_messages,
1054            chars: per_message_chars,
1055            max_matches: None,
1056            anchor_roles: vec![Role::User, Role::Assistant],
1057        },
1058    );
1059    WikiHitTranscript {
1060        blocks: found
1061            .hits
1062            .into_iter()
1063            .map(|hit| WikiHitBlock {
1064                role: role_name(hit.role).to_owned(),
1065                text: hit.text,
1066                hits: hit.matches,
1067                omitted_before: hit.omitted_before,
1068                truncated: hit.truncated,
1069            })
1070            .collect(),
1071        omitted_after: found.omitted_after,
1072    }
1073}
1074
1075fn role_name(role: Role) -> &'static str {
1076    match role {
1077        Role::User => "user",
1078        Role::Assistant => "assistant",
1079        Role::Tool => "tool",
1080    }
1081}
1082
1083/// What a restore needs from the index: the transcript as a snapshot the
1084/// compaction pipeline accepts, plus the title and project of the session it
1085/// came from.
1086pub struct ArchivedSession {
1087    pub title: String,
1088    /// The project directory the session ran in, when the row names one that
1089    /// still exists.
1090    pub project_directory: Option<PathBuf>,
1091    pub snapshot: mj_core::archive::CanonicalSessionSnapshot,
1092}
1093
1094/// Load one indexed session for restore, or `None` when the id names none.
1095pub fn archived_session(id: &str) -> Result<Option<ArchivedSession>> {
1096    if !index_is_writable() {
1097        return Ok(None);
1098    }
1099    let connection = open_readonly()?;
1100    let Some(row) = row_by_id(&connection, id)? else {
1101        return Ok(None);
1102    };
1103    let session = sessionwiki::index::session_from_index(&connection, &row)
1104        .context("read an indexed session")?;
1105    let snapshot = snapshot_of(&session)?;
1106    Ok(Some(ArchivedSession {
1107        title: session.title.clone(),
1108        project_directory: project_directory_of(&session.project),
1109        snapshot,
1110    }))
1111}
1112
1113// ---------------------------------------------------------------------------
1114// The archive job
1115// ---------------------------------------------------------------------------
1116
1117/// The stopped sessions that `archive_after_days = older_than_days` has caught,
1118/// children before their parents.
1119///
1120/// A session qualifies when its record is `Stopped`, its last update is at
1121/// least that many days old, and every sub-agent child it still has is being
1122/// archived in the same pass. The child rule is what keeps the pass from
1123/// destroying a session it did not choose: archiving a parent tears its
1124/// children down with it, so a child that is still running, or stopped but not
1125/// yet old enough, holds its parent back until the next pass.
1126///
1127/// Pure over controller state, so the rule can be tested without a daemon.
1128pub fn sessions_ready_to_archive(
1129    sessions: &BTreeMap<String, SessionRecord>,
1130    subagents: &BTreeMap<String, mj_core::subagent::SubagentRecord>,
1131    now: DateTime<Utc>,
1132    older_than_days: u32,
1133) -> Vec<String> {
1134    let cutoff = now - chrono::Duration::days(i64::from(older_than_days));
1135    let aged = |session_id: &String| {
1136        sessions.get(session_id).is_some_and(|record| {
1137            record.state == mj_core::state::SessionState::Stopped
1138                && parse_time(&record.updated_at).is_some_and(|updated| updated <= cutoff)
1139        })
1140    };
1141    let selected: BTreeSet<String> = sessions
1142        .keys()
1143        .filter(|session_id| aged(session_id))
1144        .filter(|session_id| {
1145            subagents
1146                .values()
1147                .filter(|child| &&child.parent_session_id == session_id)
1148                // A child whose record is already gone holds nothing open.
1149                .filter(|child| sessions.contains_key(&child.child_session_id))
1150                .all(|child| aged(&child.child_session_id))
1151        })
1152        .cloned()
1153        .collect();
1154    let mut ordered: Vec<String> = selected.iter().cloned().collect();
1155    ordered.sort_by_key(|session_id| std::cmp::Reverse(ancestor_depth(session_id, subagents)));
1156    ordered
1157}
1158
1159/// How many sub-agent parents a session has above it. Deeper sessions are
1160/// archived first so a parent never tears down a child the pass still has to
1161/// visit.
1162fn ancestor_depth(
1163    session_id: &str,
1164    subagents: &BTreeMap<String, mj_core::subagent::SubagentRecord>,
1165) -> usize {
1166    let mut depth = 0;
1167    let mut current = session_id;
1168    // Bounded by the map: a cycle cannot outlive one pass over every entry.
1169    while let Some(parent) = subagents
1170        .get(current)
1171        .map(|child| child.parent_session_id.as_str())
1172    {
1173        depth += 1;
1174        if depth > subagents.len() {
1175            break;
1176        }
1177        current = parent;
1178    }
1179    depth
1180}
1181
1182/// How much disk Mjolnir's own copies of sessions use, and how much an
1183/// `archive_after_days` value would free. "Mjolnir's own copy" is the
1184/// checkpoint archive plus the session's image attachments; the conversation
1185/// itself lives in the SessionWiki index and is not counted, because archiving
1186/// keeps it. The type lives in `mj-core` so the terminal UI can name it too.
1187pub use mj_core::state::ArchiveSpacePreview;
1188
1189/// The space every session uses now and, when `older_than_days` is set, the
1190/// space archiving after that many days would reclaim.
1191///
1192/// The reclaim figure uses the archive job's own selection rule but not its
1193/// "is it indexed yet" gate: that gate depends on how far the hourly index
1194/// sync has got, so applying it would make the estimate swing between zero and
1195/// the true value while the first index builds. This answers what the policy
1196/// would reclaim, not what the next tick happens to reclaim.
1197///
1198/// Walks the filesystem, so callers on the async runtime must run it in a
1199/// blocking task.
1200pub fn archive_space_preview(older_than_days: Option<u32>) -> Result<ArchiveSpacePreview> {
1201    let controller =
1202        Controller::load().context("load the session records to size their storage")?;
1203    Ok(archive_space_over(
1204        &mj_core::config::sessions_dir(),
1205        &controller.state.sessions,
1206        &controller.state.subagents,
1207        Utc::now(),
1208        older_than_days,
1209    ))
1210}
1211
1212/// The sizing itself, over given records and a given sessions directory, so it
1213/// can be tested without the live data directory.
1214fn archive_space_over(
1215    sessions_root: &Path,
1216    sessions: &BTreeMap<String, SessionRecord>,
1217    subagents: &BTreeMap<String, mj_core::subagent::SubagentRecord>,
1218    now: DateTime<Utc>,
1219    older_than_days: Option<u32>,
1220) -> ArchiveSpacePreview {
1221    let mut preview = ArchiveSpacePreview {
1222        sessions: sessions.len(),
1223        bytes: sessions
1224            .iter()
1225            .map(|(session_id, record)| session_bytes(sessions_root, session_id, record))
1226            .sum(),
1227        reclaimable_sessions: 0,
1228        reclaimable_bytes: 0,
1229    };
1230    if let Some(days) = older_than_days {
1231        let aged = sessions_ready_to_archive(sessions, subagents, now, days);
1232        preview.reclaimable_sessions = aged.len();
1233        preview.reclaimable_bytes = aged
1234            .iter()
1235            .filter_map(|session_id| {
1236                sessions
1237                    .get(session_id)
1238                    .map(|record| session_bytes(sessions_root, session_id, record))
1239            })
1240            .sum();
1241    }
1242    preview
1243}
1244
1245/// What archiving one session would free: its checkpoint archive and its
1246/// attachments. Anything already missing counts as zero.
1247fn session_bytes(sessions_root: &Path, session_id: &str, record: &SessionRecord) -> u64 {
1248    let checkpoint = record
1249        .checkpoint
1250        .as_ref()
1251        .and_then(|checkpoint| std::fs::metadata(&checkpoint.archive_path).ok())
1252        .filter(|metadata| metadata.is_file())
1253        .map(|metadata| metadata.len())
1254        .unwrap_or(0);
1255    let attachments = sessions_root
1256        .join(session_id)
1257        .join(mj_core::attachment::ATTACHMENT_DIR);
1258    let attachments = crate::import::claude::directory_size(&attachments).unwrap_or(0);
1259    checkpoint.saturating_add(attachments)
1260}
1261
1262/// Which of `session_ids` the index holds under this instance's own key, with
1263/// at least one message and not already archived.
1264///
1265/// This is the gate the archive job will not cross: Mjolnir only deletes its
1266/// own copy of a conversation SessionWiki has actually stored. Runs SQLite
1267/// work, so callers on the async runtime wrap it in `spawn_blocking`.
1268pub fn indexed_with_messages(session_ids: &[String]) -> Result<BTreeSet<String>> {
1269    if !index_is_writable() {
1270        // An index this daemon will not open holds nothing it may act on, and
1271        // the archive job deletes data, so it must find nothing here.
1272        return Ok(BTreeSet::new());
1273    }
1274    let connection = open_readonly()?;
1275    let sessions_dir = mj_core::config::sessions_dir();
1276    let mut indexed = BTreeSet::new();
1277    for session_id in session_ids {
1278        let key = format!("{}/{session_id}", sessions_dir.display());
1279        let rows = sessionwiki::index::resolve(&connection, session_id)
1280            .context("look up a stopped session in the SessionWiki index")?;
1281        if rows
1282            .iter()
1283            .any(|row| row.tool == TOOL && row.path == key && row.msg_count > 0 && !row.archived)
1284        {
1285            indexed.insert(session_id.clone());
1286        }
1287    }
1288    Ok(indexed)
1289}
1290
1291fn open_readonly() -> Result<rusqlite::Connection> {
1292    sessionwiki::index::open_readonly().context("open the SessionWiki index")
1293}
1294
1295/// The one row an id names exactly. `resolve` matches prefixes, which is right
1296/// for a person typing and wrong for a client passing an id back.
1297fn row_by_id(
1298    connection: &rusqlite::Connection,
1299    id: &str,
1300) -> Result<Option<sessionwiki::index::SessionRow>> {
1301    Ok(sessionwiki::index::resolve(connection, id)
1302        .context("look up an indexed session")?
1303        .into_iter()
1304        .find(|row| row.session_id == id))
1305}
1306
1307fn wiki_row(
1308    row: sessionwiki::index::SessionRow,
1309    snippet: Option<String>,
1310    live: &BTreeSet<String>,
1311) -> WikiRow {
1312    // Only this daemon's own sessions can be live here, and only under the key
1313    // shape the adapter writes: the checkpoint directory and the session id.
1314    let hel_session_id = (row.tool == TOOL)
1315        .then(|| row.path.rsplit('/').next().unwrap_or_default().to_owned())
1316        .filter(|session_id| live.contains(session_id));
1317    let native_id = sessionwiki::index::native_id_of(&row.path);
1318    WikiRow {
1319        id: row.session_id,
1320        tool: row.tool,
1321        project: row.project,
1322        title: row.title,
1323        started: row.started,
1324        msgs: row.msg_count,
1325        preview: row.preview,
1326        archived: row.archived,
1327        native_id,
1328        snippet,
1329        hel_session_id,
1330        // Filled in by `fill_session_tags` from the index's own tags; the row
1331        // itself does not carry them.
1332        target: None,
1333        profile: None,
1334        harness: None,
1335    }
1336}
1337
1338/// The project a restored session should open.
1339///
1340/// A Mjolnir session runs in a managed worktree under the repository it was
1341/// started from, and that worktree is gone once the session is archived. The
1342/// repository above it is what the user still has, so a worktree path is
1343/// reduced to it. Any other path is used as it stands, and a path that no
1344/// longer exists is left for the caller to replace.
1345fn project_directory_of(project: &str) -> Option<PathBuf> {
1346    if project.trim().is_empty() {
1347        return None;
1348    }
1349    let path = PathBuf::from(project);
1350    let repository = path
1351        .ancestors()
1352        .find(|ancestor| ancestor.file_name().is_some_and(|name| name == ".mj"))
1353        .and_then(std::path::Path::parent)
1354        .map(std::path::Path::to_path_buf)
1355        .unwrap_or(path);
1356    repository.is_dir().then_some(repository)
1357}
1358
1359/// Rebuild an indexed transcript as a canonical snapshot.
1360///
1361/// The snapshot is only ever read by the compaction pipeline, which wants
1362/// turns: a user message opens a turn and assistant and tool items attach to
1363/// it. Messages before the first user message therefore have nowhere to go and
1364/// are dropped, and a session with no user message at all cannot be restored.
1365fn snapshot_of(
1366    session: &sessionwiki::model::Session,
1367) -> Result<mj_core::archive::CanonicalSessionSnapshot> {
1368    use mj_core::archive::{
1369        CanonicalExecutionState, CanonicalSessionSnapshot, CanonicalSessionState,
1370        CanonicalTranscriptBody, CanonicalTranscriptItem,
1371    };
1372
1373    let started_ms = session
1374        .started
1375        .map(|time| time.timestamp_millis())
1376        .unwrap_or_default();
1377    let mut transcript: Vec<CanonicalTranscriptItem> = Vec::new();
1378    for message in &session.messages {
1379        let text = message.text.trim();
1380        if text.is_empty() {
1381            continue;
1382        }
1383        // Compaction attaches assistant and tool items to the open turn, so an
1384        // item before the first user message would be dropped anyway.
1385        if transcript.is_empty() && message.role != Role::User {
1386            continue;
1387        }
1388        let position = transcript.len() as u64 + 1;
1389        let body = match message.role {
1390            Role::User => CanonicalTranscriptBody::User {
1391                content: vec![serde_json::json!({"type": "text", "text": text})],
1392            },
1393            Role::Assistant => CanonicalTranscriptBody::Agent {
1394                chunks: vec![serde_json::json!({
1395                    "content": {"type": "text", "text": text}
1396                })],
1397                streaming: false,
1398            },
1399            // New indexes retain the shared projection; legacy rows contain only a title.
1400            Role::Tool => {
1401                let (call, terminal_outputs) = mj_transcript::summary::indexed_tool_call(
1402                    text,
1403                    &format!("wiki-tool-{position}"),
1404                );
1405                CanonicalTranscriptBody::Tool {
1406                    call,
1407                    terminal_outputs,
1408                    terminal_refs: Vec::new(),
1409                    presentation: None,
1410                }
1411            }
1412        };
1413        let created_at_ms = message
1414            .ts
1415            .map(|time| time.timestamp_millis())
1416            .unwrap_or(started_ms);
1417        transcript.push(CanonicalTranscriptItem {
1418            stable_id: format!("wiki-{position}"),
1419            position,
1420            // The validator wants an ordinal on agent messages and on nothing
1421            // else; one event per item makes the item's own position right.
1422            latest_content_event_ordinal: matches!(body, CanonicalTranscriptBody::Agent { .. })
1423                .then_some(position),
1424            created_at_ms,
1425            last_changed_at_ms: created_at_ms,
1426            body,
1427        });
1428    }
1429    anyhow::ensure!(
1430        !transcript.is_empty(),
1431        "the archived session has no prompt to restore from"
1432    );
1433
1434    let event_frontier = transcript.len() as u64;
1435    let last_activity_at_ms = transcript.last().map(|item| item.last_changed_at_ms);
1436    Ok(CanonicalSessionSnapshot {
1437        event_frontier,
1438        // Not a relay frontier, so there is no recorded digest to carry. It has
1439        // to be a well-formed non-genesis digest, and deriving it from the
1440        // session makes two restores of one session agree.
1441        event_frontier_digest: {
1442            use sha2::Digest;
1443            mj_core::hex::lower_hex(sha2::Sha256::digest(
1444                format!("sessionwiki:{}", session.id).as_bytes(),
1445            ))
1446        },
1447        session: CanonicalSessionState {
1448            execution: CanonicalExecutionState::Idle,
1449            last_activity_at_ms,
1450            session_title: Some(session.title.clone()).filter(|title| !title.trim().is_empty()),
1451            configuration: BTreeMap::new(),
1452        },
1453        transcript,
1454        queued_prompts: Vec::new(),
1455    })
1456}
1457
1458// ---------------------------------------------------------------------------
1459// Continuing an indexed session
1460// ---------------------------------------------------------------------------
1461
1462/// What continuing one indexed session means.
1463///
1464/// An agent that found a session with SessionWiki should not have to know
1465/// whose session it was, so the branch lives here and `mj resume --wiki` takes
1466/// it on the agent's behalf.
1467#[derive(Debug, Clone, PartialEq, Eq)]
1468pub enum WikiContinuation {
1469    /// A Mjolnir session this daemon still has a record of: resume it.
1470    Resume { session_id: String },
1471    /// A Mjolnir session whose record the archive job destroyed: start a new
1472    /// session seeded with a compacted hand-off.
1473    Restore { wiki_id: String },
1474    /// Another tool's session: import it, then resume what the import made.
1475    Import {
1476        harness: HarnessKind,
1477        native_session_id: String,
1478    },
1479}
1480
1481/// How to continue the indexed session a row describes.
1482///
1483/// Pure over the row so the branch can be tested without an index:
1484/// `path` is the row's stored path and `has_record` says whether controller
1485/// state still holds a session with this id.
1486pub fn wiki_continuation(
1487    wiki_id: &str,
1488    tool: &str,
1489    path: &Path,
1490    has_record: bool,
1491) -> Result<WikiContinuation> {
1492    if tool == TOOL {
1493        // `MjolnirAdapter::parse_key` names the session by its own Mjolnir id,
1494        // so a Mjolnir row's SessionWiki id is the session id.
1495        return Ok(match has_record {
1496            true => WikiContinuation::Resume {
1497                session_id: wiki_id.to_owned(),
1498            },
1499            false => WikiContinuation::Restore {
1500                wiki_id: wiki_id.to_owned(),
1501            },
1502        });
1503    }
1504    let harness = harness_adapters::harness_for_tool(tool)
1505        .with_context(|| format!("Mjolnir cannot continue a {tool} session"))?;
1506    let native_session_id = crate::import::native_session_id_from_path(harness, path)
1507        .with_context(|| {
1508            format!(
1509                "no {tool} session id in the indexed path {}",
1510                path.display()
1511            )
1512        })?;
1513    Ok(WikiContinuation::Import {
1514        harness,
1515        native_session_id,
1516    })
1517}
1518
1519/// What one indexed session is, as far as continuing it is concerned.
1520///
1521/// Read through [`wiki_session`]; the daemon serves it for `mj resume --wiki`
1522/// and for `mj sessions --session` when the id names no Mjolnir session.
1523pub fn wiki_session(
1524    wiki_id: &str,
1525    known_sessions: &BTreeSet<String>,
1526) -> Result<Option<WikiSessionInfo>> {
1527    if !index_is_writable() {
1528        return Ok(None);
1529    }
1530    let connection = open_readonly()?;
1531    let Some(row) = row_by_id(&connection, wiki_id)? else {
1532        return Ok(None);
1533    };
1534    let is_mjolnir = row.tool == TOOL;
1535    let mjolnir_session_id = is_mjolnir.then(|| row.session_id.clone());
1536    let has_record = mjolnir_session_id
1537        .as_deref()
1538        .is_some_and(|session_id| known_sessions.contains(session_id));
1539    let status = match (is_mjolnir, has_record) {
1540        (false, _) => WikiSessionStatus::Native,
1541        (true, true) => WikiSessionStatus::Mine,
1542        (true, false) => WikiSessionStatus::Archived,
1543    };
1544    let tags = match is_mjolnir {
1545        true => tags::read(&connection, &[row.session_id.as_str()])
1546            .context("read the indexed session metadata")?
1547            .remove(&row.session_id)
1548            .unwrap_or_default(),
1549        false => tags::MjTags::default(),
1550    };
1551    let harness = tags
1552        .harness
1553        .as_deref()
1554        .and_then(|id| id.parse::<HarnessKind>().ok())
1555        .or_else(|| {
1556            (!is_mjolnir)
1557                .then(|| harness_adapters::harness_for_tool(&row.tool))
1558                .flatten()
1559        });
1560    Ok(Some(WikiSessionInfo {
1561        wiki_id: row.session_id,
1562        tool: row.tool,
1563        path: PathBuf::from(row.path),
1564        status,
1565        mjolnir_session_id,
1566        profile_id: tags.profile,
1567        target_template_id: tags.target,
1568        harness,
1569        title: row.title,
1570        project: row.project,
1571    }))
1572}
1573
1574#[cfg(test)]
1575mod tests {
1576    use std::collections::BTreeMap;
1577    use std::path::Path;
1578
1579    /// The dispatch `mj resume --wiki` takes, over rows built by hand: the
1580    /// branch has to be right without an index behind it.
1581    mod continuation {
1582        use super::super::{WikiContinuation, wiki_continuation};
1583        use mj_core::config::HarnessKind;
1584        use std::path::Path;
1585
1586        #[test]
1587        fn a_mjolnir_row_with_a_record_is_resumed_and_one_without_is_restored() {
1588            let path = Path::new("/home/user/.local/share/mj/sessions/session-7");
1589            assert_eq!(
1590                wiki_continuation("session-7", "mjolnir", path, true).unwrap(),
1591                WikiContinuation::Resume {
1592                    session_id: "session-7".to_owned(),
1593                }
1594            );
1595            assert_eq!(
1596                wiki_continuation("session-7", "mjolnir", path, false).unwrap(),
1597                WikiContinuation::Restore {
1598                    wiki_id: "session-7".to_owned(),
1599                }
1600            );
1601        }
1602
1603        #[test]
1604        fn a_claude_code_row_is_imported_with_the_uuid_from_its_path() {
1605            let path = Path::new(
1606                "/home/user/.claude/projects/-home-user-app/7f3a1c20-0b11-4a55-9e0d-2c8a5d6f1b44.jsonl",
1607            );
1608            assert_eq!(
1609                wiki_continuation("abc123", "claude-code", path, false).unwrap(),
1610                WikiContinuation::Import {
1611                    harness: HarnessKind::Claude,
1612                    native_session_id: "7f3a1c20-0b11-4a55-9e0d-2c8a5d6f1b44".to_owned(),
1613                }
1614            );
1615        }
1616
1617        /// A Codex rollout's file name is a timestamp and the thread UUID, so
1618        /// the stem alone is not the id `mj import codex --session` takes.
1619        #[test]
1620        fn a_codex_row_is_imported_with_the_uuid_from_its_rollout_name() {
1621            let path = Path::new(
1622                "/home/user/.codex/sessions/2026/09/18/rollout-2026-09-18T09-15-00-7f3a1c20-0b11-4a55-9e0d-2c8a5d6f1b44.jsonl",
1623            );
1624            assert_eq!(
1625                wiki_continuation("abc123", "codex", path, false).unwrap(),
1626                WikiContinuation::Import {
1627                    harness: HarnessKind::Codex,
1628                    native_session_id: "7f3a1c20-0b11-4a55-9e0d-2c8a5d6f1b44".to_owned(),
1629                }
1630            );
1631        }
1632
1633        #[test]
1634        fn an_unknown_tool_is_an_error_that_names_it() {
1635            let error = wiki_continuation("abc123", "opencode", Path::new("/tmp/s.jsonl"), false)
1636                .unwrap_err();
1637            assert!(
1638                format!("{error:#}").contains("opencode"),
1639                "the error has to name the tool: {error:#}"
1640            );
1641        }
1642    }
1643
1644    use mj_checkpoint::archive::{
1645        ArchiveInput, BundleManifest, CanonicalExecutionState, CanonicalSessionSnapshot,
1646        CanonicalSessionState, CanonicalTranscriptBody, CanonicalTranscriptItem, SessionManifest,
1647        TargetManifest, write_archive_atomic,
1648    };
1649
1650    use super::*;
1651
1652    fn item(position: u64, body: CanonicalTranscriptBody) -> CanonicalTranscriptItem {
1653        // Only an agent message carries a content ordinal; the snapshot
1654        // validator rejects one on any other item and demands one here.
1655        let streamed = matches!(body, CanonicalTranscriptBody::Agent { .. });
1656        CanonicalTranscriptItem {
1657            stable_id: format!("item-{position}"),
1658            position,
1659            latest_content_event_ordinal: streamed.then_some(position),
1660            created_at_ms: 1_700_000_000_000 + i64::try_from(position).unwrap(),
1661            last_changed_at_ms: 1_700_000_000_000 + i64::try_from(position).unwrap(),
1662            body,
1663        }
1664    }
1665
1666    /// A managed checkpoint with one prompt, one reply, one tool call, and one
1667    /// thought, which is every transcript shape the adapter decides about.
1668    fn write_archive(directory: &Path, session_id: &str, frontier: u64) {
1669        let path = directory.join(format!(
1670            "{session_id}-{frontier}-archive-{}.hel.zip",
1671            "0".repeat(32)
1672        ));
1673        write_archive_atomic(
1674            &path,
1675            &ArchiveInput {
1676                session: SessionManifest {
1677                    id: session_id.into(),
1678                    title: "indexed session".into(),
1679                    harness_kind: mj_core::config::HarnessKind::Codex,
1680                    profile_id: "codex".into(),
1681                    native_session_id: "native-session".into(),
1682                    created_at: "2026-09-01T00:00:00Z".into(),
1683                    checkpointed_at: "2026-09-01T01:00:00Z".into(),
1684                    hel_version: "test".into(),
1685                    relay_version: "test".into(),
1686                    adapter_version: "test".into(),
1687                },
1688                target: TargetManifest {
1689                    template_id: "local".into(),
1690                    target_kind: "local-bare".into(),
1691                    details: BTreeMap::new(),
1692                },
1693                bundle: BundleManifest {
1694                    id: "project".into(),
1695                    primary_repository: "project".into(),
1696                },
1697                canonical_session: CanonicalSessionSnapshot {
1698                    event_frontier: 4,
1699                    event_frontier_digest: "a".repeat(64),
1700                    session: CanonicalSessionState {
1701                        execution: CanonicalExecutionState::Idle,
1702                        last_activity_at_ms: Some(1_700_000_000_004),
1703                        session_title: Some("snapshot title".into()),
1704                        configuration: BTreeMap::new(),
1705                    },
1706                    transcript: vec![
1707                        item(
1708                            1,
1709                            CanonicalTranscriptBody::User {
1710                                content: vec![serde_json::json!({
1711                                    "type": "text",
1712                                    "text": "index this session"
1713                                })],
1714                            },
1715                        ),
1716                        item(
1717                            2,
1718                            CanonicalTranscriptBody::Thought {
1719                                chunks: vec![serde_json::json!({
1720                                    "content": {"type": "text", "text": "pondering"}
1721                                })],
1722                                streaming: false,
1723                            },
1724                        ),
1725                        item(
1726                            3,
1727                            CanonicalTranscriptBody::Tool {
1728                                call: serde_json::json!({
1729                                    "toolCallId": "call-1",
1730                                    "title": "Edit config.toml",
1731                                    "kind": "edit",
1732                                    "status": "completed",
1733                                    "locations": [{"path": "/old/container/config.toml"}]
1734                                }),
1735                                terminal_outputs: Vec::new(),
1736                                terminal_refs: Vec::new(),
1737                                presentation: None,
1738                            },
1739                        ),
1740                        item(
1741                            4,
1742                            CanonicalTranscriptBody::Agent {
1743                                chunks: vec![serde_json::json!({
1744                                    "content": {"type": "text", "text": "done"}
1745                                })],
1746                                streaming: false,
1747                            },
1748                        ),
1749                    ],
1750                    queued_prompts: Vec::new(),
1751                },
1752                native_artifacts: Vec::new(),
1753                repositories: Vec::new(),
1754            },
1755        )
1756        .unwrap();
1757    }
1758
1759    fn adapter(directory: &Path, session_id: &str) -> MjolnirAdapter {
1760        adapter_with_live(directory, session_id, BTreeMap::new())
1761    }
1762
1763    fn adapter_with_live(
1764        directory: &Path,
1765        session_id: &str,
1766        live: BTreeMap<String, i64>,
1767    ) -> MjolnirAdapter {
1768        let record = SessionRecord {
1769            id: session_id.into(),
1770            ..record_template()
1771        };
1772        MjolnirAdapter {
1773            sessions_dir: directory.to_path_buf(),
1774            sessions: std::sync::Mutex::new(Sessions {
1775                records: BTreeMap::from([(session_id.to_owned(), record)]),
1776                subagent_ids: BTreeSet::new(),
1777                live,
1778            }),
1779            reload: false,
1780        }
1781    }
1782
1783    fn record_template() -> SessionRecord {
1784        SessionRecord {
1785            build_cache: None,
1786            container_workspace: None,
1787            mjolnir_subagents: None,
1788            create_managed_worktree: None,
1789            workspace_id: mj_core::workspace::DEFAULT_WORKSPACE_ID.to_owned(),
1790            archived: false,
1791            container_cpus: None,
1792            container_memory: None,
1793            id: "0123456789abcdef0123456789abcdef".into(),
1794            title: "indexed session".into(),
1795            harness_kind: mj_core::config::HarnessKind::Codex,
1796            last_profile: "codex".into(),
1797            bundle_id: "project".into(),
1798            project_directory: Some(PathBuf::from("/home/dev/project")),
1799            managed_worktree: None,
1800            target_template_id: "local-bare".into(),
1801            resource_allocation: None,
1802            additional_mounts: Vec::new(),
1803            state: mj_core::state::SessionState::Stopped,
1804            target: None,
1805            native_session_id: Some("native-session".into()),
1806            acp_session_title: Some("the harness title".into()),
1807            session_title_override: None,
1808            created_at: "2026-09-01T00:00:00Z".into(),
1809            updated_at: "2026-09-01T01:00:00Z".into(),
1810            viewed_through_event_ordinal: 0,
1811            draft_input: String::new(),
1812            last_error: None,
1813            last_checkpoint_error: None,
1814            checkpoint: None,
1815        }
1816    }
1817
1818    #[test]
1819    fn the_newest_checkpoint_of_each_session_is_one_indexed_key() {
1820        let directory = tempfile::tempdir().unwrap();
1821        let session_id = "0123456789abcdef0123456789abcdef";
1822        write_archive(directory.path(), session_id, 1);
1823        write_archive(directory.path(), session_id, 7);
1824        let adapter = adapter(directory.path(), session_id);
1825
1826        let store = adapter.store().expect("the adapter is a shared store");
1827        let key = format!("{}/{session_id}", directory.path().display());
1828        assert_eq!(
1829            store
1830                .keys
1831                .iter()
1832                .map(|(key, _)| key.as_str())
1833                .collect::<Vec<_>>(),
1834            vec![key.as_str()]
1835        );
1836        assert!(!store.had_error);
1837        assert_eq!(store.files.len(), 1);
1838        assert!(
1839            store.files[0]
1840                .file_name()
1841                .unwrap()
1842                .to_str()
1843                .unwrap()
1844                .contains("-7-archive-"),
1845            "the newest checkpoint is the one indexed: {:?}",
1846            store.files[0]
1847        );
1848        assert_eq!(
1849            adapter.reconcile_scope(),
1850            Some(format!("{}/", directory.path().display()))
1851        );
1852
1853        let session = adapter.parse_key(&key).unwrap();
1854        assert_eq!(session.id, session_id);
1855        assert_eq!(session.tool, "mjolnir");
1856        assert_eq!(session.path, PathBuf::from(&key));
1857        assert_eq!(session.project, "/home/dev/project");
1858        assert_eq!(session.title, "the harness title");
1859        assert!(!session.subagent);
1860        assert_eq!(
1861            session.messages.iter().map(|m| m.role).collect::<Vec<_>>(),
1862            vec![Role::User, Role::Tool, Role::Assistant]
1863        );
1864        assert_eq!(session.messages[0].text, "index this session");
1865        let tool: serde_json::Value = serde_json::from_str(&session.messages[1].text).unwrap();
1866        assert_eq!(tool["name"], "Edit");
1867        assert_eq!(tool["call"]["title"], "Edit config.toml");
1868        assert_eq!(session.messages[2].text, "done");
1869        assert_eq!(session.touched, vec!["/old/container/config.toml"]);
1870    }
1871
1872    #[test]
1873    fn provenance_backfill_repairs_an_unchanged_checkpoint_without_rebuilding_the_index() {
1874        let _held = tags::testing::lock();
1875        let (_index_dir, mut connection) = tags::testing::isolated_index();
1876        let directory = tempfile::tempdir().unwrap();
1877        write_archive(directory.path(), "old-session", 4);
1878        let source = adapter(directory.path(), "old-session");
1879        let key = source.key_for("old-session");
1880        tags::testing::index_row(&connection, "old-session", "mjolnir");
1881        connection
1882            .execute(
1883                "UPDATE files SET path = ?1 WHERE session_id = 'old-session'",
1884                [&key],
1885            )
1886            .unwrap();
1887        provenance::backfill(&mut connection, &source).unwrap();
1888        assert_eq!(
1889            sessionwiki::index::files_for(&connection, "old-session").unwrap(),
1890            vec!["/old/container/config.toml"]
1891        );
1892        provenance::backfill(&mut connection, &source).unwrap();
1893        assert_eq!(
1894            sessionwiki::index::sessions_for_file(&connection, "config.toml", 20)
1895                .unwrap()
1896                .len(),
1897            1
1898        );
1899    }
1900
1901    fn projection(session_id: &str) -> mj_core::state::MaterializedSession {
1902        use mj_core::transcript::{TranscriptBody, TranscriptItem};
1903        let mut projected = mj_core::state::MaterializedSession::empty(session_id);
1904        let mut push = |position: u64, body: TranscriptBody| {
1905            let streamed = matches!(body, TranscriptBody::Agent { .. });
1906            projected
1907                .transcript
1908                .push(std::sync::Arc::new(TranscriptItem {
1909                    stable_id: format!("item-{position}"),
1910                    position,
1911                    latest_content_event_ordinal: streamed.then_some(position),
1912                    created_at_ms: 1_700_000_000_000 + i64::try_from(position).unwrap(),
1913                    last_changed_at_ms: 1_700_000_000_000 + i64::try_from(position).unwrap(),
1914                    body,
1915                }));
1916        };
1917        push(
1918            1,
1919            TranscriptBody::User {
1920                content: vec![serde_json::json!({"type": "text", "text": "still talking"})],
1921            },
1922        );
1923        push(
1924            2,
1925            TranscriptBody::Thought {
1926                chunks: vec![serde_json::json!({"content": {"type": "text", "text": "hmm"}})],
1927                streaming: false,
1928            },
1929        );
1930        push(
1931            3,
1932            TranscriptBody::Tool {
1933                call: serde_json::json!({"toolCallId": "c1", "title": "Read README.md"}),
1934                terminal_outputs: Vec::new(),
1935                terminal_refs: Vec::new(),
1936                presentation: None,
1937            },
1938        );
1939        push(
1940            4,
1941            TranscriptBody::Agent {
1942                chunks: vec![serde_json::json!({"content": {"type": "text", "text": "reading"}})],
1943                streaming: false,
1944            },
1945        );
1946        projected.session_title = Some("the live title".into());
1947        projected
1948    }
1949
1950    /// A session that has never been checkpointed is indexed from the
1951    /// daemon's own projection, with the same roles a checkpoint would give.
1952    #[test]
1953    fn a_running_session_is_indexed_from_its_stored_transcript() {
1954        let session_id = "0123456789abcdef0123456789abcdef";
1955        let messages = projected_messages(&projection(session_id));
1956        assert_eq!(
1957            messages.iter().map(|m| m.role).collect::<Vec<_>>(),
1958            vec![Role::User, Role::Tool, Role::Assistant]
1959        );
1960        assert_eq!(messages[0].text, "still talking");
1961        assert_eq!(messages[2].text, "reading");
1962        let tool: serde_json::Value = serde_json::from_str(&messages[1].text).unwrap();
1963        assert_eq!(tool["name"], "Read");
1964        assert_eq!(tool["call"]["title"], "Read README.md");
1965    }
1966
1967    /// A running session is listed under the same key as a stopped one, with
1968    /// its own change token, so it is searchable before it is ever closed and
1969    /// reconciliation never archives it. When it stops, the key stays and the
1970    /// checkpoint becomes its source.
1971    #[test]
1972    fn a_running_session_is_listed_with_its_own_change_token() {
1973        let directory = tempfile::tempdir().unwrap();
1974        let running = "0123456789abcdef0123456789abcdef";
1975        let never_checkpointed = "fedcba9876543210fedcba9876543210";
1976        write_archive(directory.path(), running, 3);
1977        let live = adapter_with_live(
1978            directory.path(),
1979            running,
1980            BTreeMap::from([
1981                (running.to_owned(), 1_900_000_000),
1982                (never_checkpointed.to_owned(), 1_900_000_001),
1983            ]),
1984        );
1985
1986        let store = live.store().expect("the adapter is a shared store");
1987        let key_of = |session_id: &str| format!("{}/{session_id}", directory.path().display());
1988        assert_eq!(
1989            store.keys,
1990            vec![
1991                (
1992                    key_of(running),
1993                    1_900_000_000 * 1024 + i64::from(mj_transcript::summary::SUMMARY_VERSION)
1994                ),
1995                (
1996                    key_of(never_checkpointed),
1997                    1_900_000_001 * 1024 + i64::from(mj_transcript::summary::SUMMARY_VERSION)
1998                ),
1999            ],
2000            "a live session's own token replaces the checkpoint's"
2001        );
2002
2003        // Once it stops it leaves the live set, and the checkpoint's own
2004        // modification time is the token again.
2005        let stopped = adapter(directory.path(), running);
2006        let keys = stopped.store().expect("a shared store").keys;
2007        assert_eq!(keys.len(), 1);
2008        assert_eq!(keys[0].0, key_of(running));
2009        assert_ne!(keys[0].1, 1_900_000_000);
2010        assert_eq!(
2011            stopped.parse_key(&key_of(running)).unwrap().title,
2012            "the harness title",
2013            "a stopped session is parsed from its checkpoint"
2014        );
2015    }
2016
2017    /// Renaming a session leaves its conversation untouched, so only the
2018    /// record's own last update can tell the index the title moved.
2019    #[test]
2020    fn a_rename_moves_a_session_change_token() {
2021        let directory = tempfile::tempdir().unwrap();
2022        let session_id = "0123456789abcdef0123456789abcdef";
2023        write_archive(directory.path(), session_id, 1);
2024        let adapter = adapter(directory.path(), session_id);
2025        let before = adapter.store().expect("a shared store").keys[0].1;
2026
2027        {
2028            let mut sessions = adapter.sessions.lock().unwrap();
2029            let record = sessions.records.get_mut(session_id).unwrap();
2030            record.session_title_override = Some("the new name".into());
2031            record.updated_at = "2099-01-01T00:00:00Z".into();
2032        }
2033        let after = adapter.store().expect("a shared store").keys[0].1;
2034        assert!(
2035            after > before,
2036            "a renamed session is re-indexed: {before} then {after}"
2037        );
2038        assert_eq!(
2039            adapter
2040                .parse_key(&format!("{}/{session_id}", directory.path().display()))
2041                .unwrap()
2042                .title,
2043            "the new name"
2044        );
2045    }
2046
2047    fn indexed(messages: Vec<(Role, &str)>) -> sessionwiki::model::Session {
2048        Session {
2049            id: "0123456789abcdef0123456789abcdef".into(),
2050            tool: "mjolnir",
2051            path: PathBuf::from("/sessions/0123456789abcdef0123456789abcdef"),
2052            project: "/home/dev/project".into(),
2053            started: DateTime::from_timestamp_millis(1_700_000_000_000),
2054            ended: None,
2055            title: "the archived session".into(),
2056            subagent: false,
2057            messages: messages
2058                .into_iter()
2059                .map(|(role, text)| Message {
2060                    role,
2061                    text: text.to_owned(),
2062                    ts: None,
2063                })
2064                .collect(),
2065            touched: Vec::new(),
2066            edits: Vec::new(),
2067        }
2068    }
2069
2070    /// A hit is found whatever the case of the query or of the transcript, and
2071    /// the reported range covers the matched text in the returned block.
2072    #[test]
2073    fn transcript_hits_locates_case_insensitive_matches() {
2074        let session = indexed(vec![
2075            (Role::User, "Make the Tests green"),
2076            (Role::Assistant, "the tests are green now"),
2077        ]);
2078
2079        let found = hit_transcript(&session, "TESTS", 0, 4_000);
2080
2081        assert_eq!(found.blocks.len(), 2, "both messages contain the query");
2082        assert_eq!(found.blocks[0].role, "user");
2083        let (start, end) = found.blocks[0].hits[0];
2084        assert_eq!(&found.blocks[0].text[start..end], "Tests");
2085        let (start, end) = found.blocks[1].hits[0];
2086        assert_eq!(&found.blocks[1].text[start..end], "tests");
2087        assert!(!found.blocks[0].truncated);
2088        assert_eq!(found.omitted_after, 0);
2089    }
2090
2091    /// Context messages come back around each hit, with the gap between two
2092    /// groups counted rather than silently closed.
2093    #[test]
2094    fn transcript_hits_keeps_context_and_marks_omissions() {
2095        let session = indexed(vec![
2096            (Role::User, "zero"),
2097            (Role::Assistant, "one needle one"),
2098            (Role::Tool, "two"),
2099            (Role::User, "three"),
2100            (Role::Assistant, "four"),
2101            (Role::Tool, "five"),
2102            (Role::User, "six needle six"),
2103            (Role::Assistant, "seven"),
2104            (Role::User, "eight"),
2105        ]);
2106
2107        let found = hit_transcript(&session, "needle", 1, 4_000);
2108
2109        let shown: Vec<(&str, &str, usize)> = found
2110            .blocks
2111            .iter()
2112            .map(|block| {
2113                (
2114                    block.role.as_str(),
2115                    block.text.as_str(),
2116                    block.omitted_before,
2117                )
2118            })
2119            .collect();
2120        assert_eq!(
2121            shown,
2122            vec![
2123                ("user", "zero", 0),
2124                ("assistant", "one needle one", 0),
2125                ("tool", "two", 0),
2126                ("tool", "five", 2),
2127                ("user", "six needle six", 0),
2128                ("assistant", "seven", 0),
2129            ]
2130        );
2131        assert_eq!(found.omitted_after, 1, "the last message is not shown");
2132        assert!(found.blocks[0].hits.is_empty(), "context has no hits");
2133    }
2134
2135    /// A query that only occurs in tool output finds nothing, and a tool
2136    /// message beside a real match still comes back as context. Tool text is
2137    /// machine chatter: anchoring a passage on it opens the preview on command
2138    /// output the reader never wrote, and the preview collapses tool runs, so
2139    /// the match could not be shown even if it were returned.
2140    #[test]
2141    fn transcript_hits_never_anchor_on_tool_output() {
2142        let session = indexed(vec![
2143            (Role::User, "make it build"),
2144            (Role::Tool, "cargo build --needle"),
2145            (Role::Assistant, "it builds"),
2146        ]);
2147
2148        let only_in_a_tool = hit_transcript(&session, "needle", 1, 4_000);
2149        assert!(
2150            only_in_a_tool.blocks.is_empty(),
2151            "tool output must not anchor a passage, got {:?}",
2152            only_in_a_tool.blocks
2153        );
2154
2155        let beside_a_match = hit_transcript(&session, "builds", 1, 4_000);
2156        let shown: Vec<(&str, bool)> = beside_a_match
2157            .blocks
2158            .iter()
2159            .map(|block| (block.role.as_str(), !block.hits.is_empty()))
2160            .collect();
2161        assert_eq!(
2162            shown,
2163            vec![("tool", false), ("assistant", true)],
2164            "a tool message is still context around a real match"
2165        );
2166    }
2167
2168    /// A long message is cut down to the caller's budget around its first hit,
2169    /// not from the start, so the match is always in what comes back.
2170    #[test]
2171    fn transcript_hits_window_keeps_the_first_hit() {
2172        let filler = "x".repeat(4_000);
2173        let session = indexed(vec![(Role::User, &format!("{filler} needle {filler}"))]);
2174
2175        let found = hit_transcript(&session, "needle", 0, 100);
2176
2177        let block = &found.blocks[0];
2178        assert!(block.truncated);
2179        assert_eq!(block.text.chars().count(), 100);
2180        assert_eq!(block.hits.len(), 1, "the windowed text keeps its hit");
2181        let (start, end) = block.hits[0];
2182        assert_eq!(&block.text[start..end], "needle");
2183        assert!(
2184            start >= 20,
2185            "the window keeps lead-in before the hit, got {start}"
2186        );
2187    }
2188
2189    /// The snapshot a restore hands to compaction has to satisfy the same
2190    /// validator a real checkpoint does, and has to carry every message in
2191    /// order.
2192    #[test]
2193    fn a_restored_snapshot_is_a_valid_transcript_of_the_indexed_session() {
2194        let snapshot = snapshot_of(&indexed(vec![
2195            (Role::User, "make the tests green"),
2196            (Role::Tool, "Read src/lib.rs"),
2197            (Role::Assistant, "they are green now"),
2198            (Role::User, "  "),
2199        ]))
2200        .unwrap();
2201
2202        snapshot.validate().expect("the snapshot is well formed");
2203        assert_eq!(snapshot.event_frontier, 3);
2204        assert_eq!(
2205            snapshot.session.session_title.as_deref(),
2206            Some("the archived session")
2207        );
2208        assert!(snapshot.session.last_activity_at_ms.is_some());
2209        let bodies = snapshot
2210            .transcript
2211            .iter()
2212            .map(|item| match &item.body {
2213                mj_core::archive::CanonicalTranscriptBody::User { content } => (
2214                    "user",
2215                    mj_core::transcript::materialized_content_text(content),
2216                ),
2217                mj_core::archive::CanonicalTranscriptBody::Agent { chunks, .. } => (
2218                    "agent",
2219                    mj_core::transcript::materialized_chunks_text(chunks),
2220                ),
2221                mj_core::archive::CanonicalTranscriptBody::Tool { call, .. } => (
2222                    "tool",
2223                    call["title"].as_str().unwrap_or_default().to_owned(),
2224                ),
2225                _ => ("other", String::new()),
2226            })
2227            .collect::<Vec<_>>();
2228        assert_eq!(
2229            bodies,
2230            vec![
2231                ("user", "make the tests green".to_owned()),
2232                ("tool", "Read src/lib.rs".to_owned()),
2233                ("agent", "they are green now".to_owned()),
2234            ],
2235            "the blank message is dropped and every other one keeps its role"
2236        );
2237    }
2238
2239    /// Compaction attaches assistant and tool items to the open turn, so an
2240    /// index that starts mid-conversation must not produce a snapshot whose
2241    /// first item has no turn to join.
2242    #[test]
2243    fn messages_before_the_first_prompt_are_dropped() {
2244        let snapshot = snapshot_of(&indexed(vec![
2245            (Role::Assistant, "still working"),
2246            (Role::User, "carry on"),
2247        ]))
2248        .unwrap();
2249        assert_eq!(snapshot.transcript.len(), 1);
2250        assert_eq!(snapshot.transcript[0].position, 1);
2251        snapshot.validate().unwrap();
2252
2253        let error = snapshot_of(&indexed(vec![(Role::Assistant, "nobody asked")])).unwrap_err();
2254        assert!(
2255            error.to_string().contains("no prompt"),
2256            "a session with no prompt cannot be restored: {error}"
2257        );
2258    }
2259
2260    fn record(
2261        session_id: &str,
2262        state: mj_core::state::SessionState,
2263        updated_at: &str,
2264    ) -> SessionRecord {
2265        SessionRecord {
2266            id: session_id.into(),
2267            state,
2268            updated_at: updated_at.into(),
2269            ..record_template()
2270        }
2271    }
2272
2273    fn child(child_session_id: &str, parent_session_id: &str) -> mj_core::subagent::SubagentRecord {
2274        mj_core::subagent::SubagentRecord {
2275            child_session_id: child_session_id.into(),
2276            parent_session_id: parent_session_id.into(),
2277            task_name: "task".into(),
2278            profile_id: "codex".into(),
2279            model: None,
2280            effort: None,
2281            working_directory: PathBuf::new(),
2282            initial_prompt: "do the thing".into(),
2283            request_key: "key".into(),
2284            created_at: "2026-09-01T00:00:00Z".into(),
2285            noticed_turn: None,
2286        }
2287    }
2288
2289    fn ready(
2290        sessions: Vec<SessionRecord>,
2291        children: Vec<mj_core::subagent::SubagentRecord>,
2292    ) -> Vec<String> {
2293        let now = parse_time("2026-09-10T00:00:00Z").unwrap();
2294        sessions_ready_to_archive(
2295            &sessions
2296                .into_iter()
2297                .map(|record| (record.id.clone(), record))
2298                .collect(),
2299            &children
2300                .into_iter()
2301                .map(|child| (child.child_session_id.clone(), child))
2302                .collect(),
2303            now,
2304            3,
2305        )
2306    }
2307
2308    /// A session whose checkpoint archive and attachments sit under `root`.
2309    fn sized_session(
2310        root: &Path,
2311        session_id: &str,
2312        updated_at: &str,
2313        checkpoint_bytes: usize,
2314        attachment_bytes: &[usize],
2315    ) -> SessionRecord {
2316        let archive_path = root.join(format!("{session_id}.hel.zip"));
2317        std::fs::write(&archive_path, vec![b'c'; checkpoint_bytes]).unwrap();
2318        if !attachment_bytes.is_empty() {
2319            let attachments = root
2320                .join(session_id)
2321                .join(mj_core::attachment::ATTACHMENT_DIR);
2322            std::fs::create_dir_all(&attachments).unwrap();
2323            for (index, size) in attachment_bytes.iter().enumerate() {
2324                std::fs::write(attachments.join(format!("{index}.png")), vec![b'a'; *size])
2325                    .unwrap();
2326            }
2327        }
2328        SessionRecord {
2329            checkpoint: Some(mj_core::state::CheckpointMetadata {
2330                archive_path,
2331                sha256: "0".repeat(64),
2332                created_at: updated_at.into(),
2333                event_frontier: 1,
2334            }),
2335            ..record(
2336                session_id,
2337                mj_core::state::SessionState::Stopped,
2338                updated_at,
2339            )
2340        }
2341    }
2342
2343    #[test]
2344    fn the_space_preview_sizes_every_session_and_only_the_aged_ones_as_reclaimable() {
2345        let directory = tempfile::tempdir().unwrap();
2346        let root = directory.path();
2347        let sessions: BTreeMap<String, SessionRecord> = [
2348            sized_session(root, "old-stopped", "2026-09-01T00:00:00Z", 1000, &[10, 20]),
2349            sized_session(root, "just-stopped", "2026-09-09T00:00:00Z", 500, &[]),
2350            // A record whose checkpoint file is already gone counts as zero
2351            // rather than failing the whole estimate.
2352            SessionRecord {
2353                checkpoint: Some(mj_core::state::CheckpointMetadata {
2354                    archive_path: root.join("missing.hel.zip"),
2355                    sha256: "0".repeat(64),
2356                    created_at: "2026-09-01T00:00:00Z".into(),
2357                    event_frontier: 1,
2358                }),
2359                ..record(
2360                    "lost-checkpoint",
2361                    mj_core::state::SessionState::Stopped,
2362                    "2026-09-01T00:00:00Z",
2363                )
2364            },
2365        ]
2366        .into_iter()
2367        .map(|record| (record.id.clone(), record))
2368        .collect();
2369        let now = parse_time("2026-09-10T00:00:00Z").unwrap();
2370
2371        let all = archive_space_over(root, &sessions, &BTreeMap::new(), now, None);
2372        assert_eq!(all.sessions, 3);
2373        assert_eq!(all.bytes, 1530);
2374        assert_eq!(all.reclaimable_sessions, 0);
2375        assert_eq!(all.reclaimable_bytes, 0);
2376
2377        let aged = archive_space_over(root, &sessions, &BTreeMap::new(), now, Some(3));
2378        assert_eq!(aged.bytes, 1530);
2379        assert_eq!(
2380            (aged.reclaimable_sessions, aged.reclaimable_bytes),
2381            (2, 1030),
2382            "only the sessions the job would archive count, attachments included"
2383        );
2384    }
2385
2386    #[test]
2387    fn only_stopped_sessions_past_the_cut_off_are_archived() {
2388        use mj_core::state::SessionState;
2389        let selected = ready(
2390            vec![
2391                record("old-stopped", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2392                record(
2393                    "just-stopped",
2394                    SessionState::Stopped,
2395                    "2026-09-09T00:00:00Z",
2396                ),
2397                record("old-running", SessionState::Running, "2026-09-01T00:00:00Z"),
2398                record("old-error", SessionState::Error, "2026-09-01T00:00:00Z"),
2399                record("unparsable", SessionState::Stopped, "not a time"),
2400                // Exactly the cut-off counts as old enough.
2401                record("at-the-edge", SessionState::Stopped, "2026-09-07T00:00:00Z"),
2402            ],
2403            Vec::new(),
2404        );
2405        assert_eq!(selected, vec!["at-the-edge", "old-stopped"]);
2406    }
2407
2408    #[test]
2409    fn a_child_the_pass_is_not_archiving_holds_its_parent_back() {
2410        use mj_core::state::SessionState;
2411        let selected = ready(
2412            vec![
2413                record("parent", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2414                record(
2415                    "running-child",
2416                    SessionState::Running,
2417                    "2026-09-01T00:00:00Z",
2418                ),
2419            ],
2420            vec![child("running-child", "parent")],
2421        );
2422        assert!(selected.is_empty(), "the parent must wait: {selected:?}");
2423
2424        let selected = ready(
2425            vec![
2426                record("parent", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2427                record("young-child", SessionState::Stopped, "2026-09-09T00:00:00Z"),
2428            ],
2429            vec![child("young-child", "parent")],
2430        );
2431        assert!(selected.is_empty(), "the parent must wait: {selected:?}");
2432
2433        // A child whose record is already gone holds nothing open.
2434        let selected = ready(
2435            vec![record(
2436                "parent",
2437                SessionState::Stopped,
2438                "2026-09-01T00:00:00Z",
2439            )],
2440            vec![child("departed-child", "parent")],
2441        );
2442        assert_eq!(selected, vec!["parent"]);
2443    }
2444
2445    #[test]
2446    fn children_are_archived_before_their_parents() {
2447        use mj_core::state::SessionState;
2448        let selected = ready(
2449            vec![
2450                record("parent", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2451                record("child", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2452                record("grandchild", SessionState::Stopped, "2026-09-01T00:00:00Z"),
2453            ],
2454            vec![child("child", "parent"), child("grandchild", "child")],
2455        );
2456        assert_eq!(selected, vec!["grandchild", "child", "parent"]);
2457    }
2458
2459    #[test]
2460    fn native_adapters_cover_every_enabled_profile_home() {
2461        use mj_core::config::{Config, HarnessKind, HarnessProfile};
2462
2463        fn profile(kind: HarnessKind, home: &str, enabled: bool) -> HarnessProfile {
2464            HarnessProfile {
2465                enabled,
2466                kind,
2467                home: PathBuf::from(home),
2468                environment: BTreeMap::new(),
2469                context_window_bytes: None,
2470                guardian_review_model: None,
2471            }
2472        }
2473
2474        let mut config = Config::default();
2475        for (id, built) in [
2476            (
2477                "codex",
2478                profile(HarnessKind::Codex, "/home/dev/.codex3", true),
2479            ),
2480            (
2481                "codex-ds",
2482                profile(HarnessKind::Codex, "/home/dev/.codex-ds", true),
2483            ),
2484            // A second profile on one home must not add a second adapter.
2485            (
2486                "codex-alt",
2487                profile(HarnessKind::Codex, "/home/dev/.codex3", true),
2488            ),
2489            (
2490                "codex-off",
2491                profile(HarnessKind::Codex, "/home/dev/.codex-off", false),
2492            ),
2493            (
2494                "claude",
2495                profile(HarnessKind::Claude, "/home/dev/.claude4", true),
2496            ),
2497            ("kimi", profile(HarnessKind::Kimi, "/home/dev/.kimi", true)),
2498            ("grok", profile(HarnessKind::Grok, "/home/dev/.grok", true)),
2499            ("muse", profile(HarnessKind::Muse, "/home/dev/muse", true)),
2500            (
2501                "muse-off",
2502                profile(HarnessKind::Muse, "/home/dev/muse-off", false),
2503            ),
2504        ] {
2505            config.profiles.insert(id.into(), built);
2506        }
2507
2508        let adapters = native_adapters(&config);
2509        let roots: Vec<(&str, Option<PathBuf>)> = adapters
2510            .iter()
2511            .map(|adapter| (adapter.name(), adapter.root()))
2512            .collect();
2513
2514        let codex: Vec<&Option<PathBuf>> = roots
2515            .iter()
2516            .filter(|(name, _)| *name == "codex")
2517            .map(|(_, root)| root)
2518            .collect();
2519        assert_eq!(
2520            codex,
2521            vec![
2522                &Some(PathBuf::from("/home/dev/.codex3/sessions")),
2523                &Some(PathBuf::from("/home/dev/.codex-ds/sessions")),
2524            ],
2525            "one adapter per enabled Codex home, deduplicated: {roots:?}"
2526        );
2527
2528        let claude: Vec<&Option<PathBuf>> = roots
2529            .iter()
2530            .filter(|(name, _)| *name == "claude-code")
2531            .map(|(_, root)| root)
2532            .collect();
2533        assert_eq!(
2534            claude,
2535            vec![&Some(PathBuf::from("/home/dev/.claude4/projects"))],
2536            "one adapter for the enabled Claude home: {roots:?}"
2537        );
2538
2539        for (_, root) in &roots {
2540            let Some(root) = root else { continue };
2541            let text = root.to_string_lossy();
2542            assert!(
2543                !text.contains(".codex-off"),
2544                "a disabled profile must not be indexed: {roots:?}"
2545            );
2546            assert!(
2547                !text.ends_with("/.codex/sessions") && !text.ends_with("/.claude/projects"),
2548                "the stock homes are not indexed unless a profile names them: {roots:?}"
2549            );
2550        }
2551
2552        // SessionWiki has no adapter for these three, so Mjolnir supplies one
2553        // per enabled profile home under its own tool name.
2554        for (name, root) in [
2555            ("kimi-code", PathBuf::from("/home/dev/.kimi/sessions")),
2556            ("grok-build", PathBuf::from("/home/dev/.grok/sessions")),
2557            (
2558                "muse",
2559                mj_checkpoint::native::muse_sessions_root(Path::new("/home/dev/muse")).unwrap(),
2560            ),
2561        ] {
2562            let found: Vec<&Option<PathBuf>> = roots
2563                .iter()
2564                .filter(|(found, _)| *found == name)
2565                .map(|(_, root)| root)
2566                .collect();
2567            assert_eq!(found, vec![&Some(root)], "one {name} adapter: {roots:?}");
2568        }
2569
2570        for (_, root) in &roots {
2571            let Some(root) = root else { continue };
2572            assert!(
2573                !root.to_string_lossy().contains("muse-off"),
2574                "a disabled profile must not be indexed: {roots:?}"
2575            );
2576        }
2577
2578        assert!(
2579            roots.iter().any(|(name, _)| *name == "gemini"),
2580            "the other built-in adapters are kept: {roots:?}"
2581        );
2582    }
2583
2584    /// A Mjolnir row carries the target, profile and harness the sync stored
2585    /// in the index; a row from another tool carries none, because only
2586    /// Mjolnir writes those tags.
2587    #[test]
2588    fn query_rows_returns_the_indexed_target_profile_and_harness() {
2589        let _held = tags::testing::lock();
2590        let (_directory, connection) = tags::testing::isolated_index();
2591        tags::testing::index_row(&connection, "mj-session", TOOL);
2592        tags::testing::index_row(&connection, "codex-session", "codex");
2593        tags::write(
2594            &connection,
2595            "mj-session",
2596            &tags::MjTags {
2597                target: Some("Prod-Box".into()),
2598                profile: Some("codex-Main".into()),
2599                harness: Some("codex".into()),
2600            },
2601        )
2602        .expect("write the session metadata");
2603
2604        let rows = query_rows("", 10, &BTreeSet::new()).expect("query the index");
2605        let mjolnir = rows
2606            .iter()
2607            .find(|row| row.id == "mj-session")
2608            .expect("the Mjolnir row is returned");
2609        assert_eq!(mjolnir.target.as_deref(), Some("Prod-Box"));
2610        assert_eq!(mjolnir.profile.as_deref(), Some("codex-Main"));
2611        assert_eq!(mjolnir.harness.as_deref(), Some("codex"));
2612
2613        let codex = rows
2614            .iter()
2615            .find(|row| row.id == "codex-session")
2616            .expect("the Codex row is returned");
2617        assert_eq!(codex.target, None);
2618        assert_eq!(codex.profile, None);
2619        assert_eq!(codex.harness, None);
2620    }
2621}