1mod 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
39const TOOL: &str = "mjolnir";
43
44struct ArchiveFile {
46 path: PathBuf,
47 frontier: u64,
48 token: i64,
50}
51
52#[derive(Default)]
56struct Sessions {
57 records: BTreeMap<String, SessionRecord>,
58 subagent_ids: BTreeSet<String>,
59 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
73fn 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
98pub struct MjolnirAdapter {
100 sessions_dir: PathBuf,
101 sessions: std::sync::Mutex<Sessions>,
102 reload: bool,
104}
105
106impl MjolnirAdapter {
107 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 pub fn reloading(state: &State) -> Self {
126 Self {
127 reload: true,
128 ..Self::from_state(state)
129 }
130 }
131
132 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 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 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 fn key_for(&self, session_id: &str) -> String {
229 format!("{}/{session_id}", self.sessions_dir.display())
230 }
231
232 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
292fn 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
308fn 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
330fn 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 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 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 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 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
475struct 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
514pub struct WikiIndexer {
521 inner: Arc<Indexer>,
522}
523
524#[derive(Default)]
525struct Indexer {
526 running: tokio::sync::Mutex<()>,
528 notify: tokio::sync::Notify,
529 requested: AtomicBool,
531 full_requested: AtomicBool,
533 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 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 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 pub async fn sync_now(&self, full: bool) -> Result<()> {
568 self.inner.sync(full).await
569 }
570
571 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 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 break;
604 }
605 }
606 }
607 }
608
609 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 .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
651fn 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 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 record_first_build();
676 }
677 Ok(true)
678}
679
680fn 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
711fn native_adapters(config: &mj_core::config::Config) -> Vec<Box<dyn Adapter>> {
728 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 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
759fn 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
786fn 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 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
832fn 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
849fn 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
856pub 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
871pub const MAX_WIKI_LIMIT: usize = 200;
877pub const DEFAULT_WIKI_LIMIT: usize = 50;
879const MIN_FULLTEXT_QUERY: usize = 3;
882pub const SYNC_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
884
885pub fn sync_is_stale(last_success: Option<Instant>) -> bool {
887 last_success.is_none_or(|at| at.elapsed() >= SYNC_STALE_AFTER)
888}
889
890pub 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 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 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
943fn 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
966const NAME_SCAN_LIMIT: usize = 2_000;
970
971fn 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
988pub 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
1004pub 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
1034fn 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
1083pub struct ArchivedSession {
1087 pub title: String,
1088 pub project_directory: Option<PathBuf>,
1091 pub snapshot: mj_core::archive::CanonicalSessionSnapshot,
1092}
1093
1094pub 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
1113pub 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 .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
1159fn 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 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
1182pub use mj_core::state::ArchiveSpacePreview;
1188
1189pub 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
1212fn 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
1245fn 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
1262pub fn indexed_with_messages(session_ids: &[String]) -> Result<BTreeSet<String>> {
1269 if !index_is_writable() {
1270 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
1295fn 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 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 target: None,
1333 profile: None,
1334 harness: None,
1335 }
1336}
1337
1338fn 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
1359fn 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
1468pub enum WikiContinuation {
1469 Resume { session_id: String },
1471 Restore { wiki_id: String },
1474 Import {
1476 harness: HarnessKind,
1477 native_session_id: String,
1478 },
1479}
1480
1481pub 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 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
1519pub 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 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 #[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 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 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 (
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 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 #[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}