brokk-mj-controller 2.35.0

Daemon-side controller, session manager, and web server for Mjolnir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use super::*;

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// What one scanned native session file parsed into, keyed by the file itself.
#[derive(Debug, Clone)]
enum CachedNativeMetadata {
    /// `claude_native_metadata`, including its "filtered out" verdict.
    Claude(Option<(String, PathBuf, String)>),
    /// `codex_session_metadata`, including its "not interactive" verdict.
    Codex(Option<CodexSessionMetadata>),
    IndexEligible(bool),
}

#[derive(Debug)]
struct CachedNativeEntry {
    modified_at: SystemTime,
    size_bytes: u64,
    metadata: CachedNativeMetadata,
}

#[derive(Debug, Default)]
struct NativeScanCacheInner {
    entries: HashMap<PathBuf, CachedNativeEntry>,
    parsed_files: u64,
}

/// Remembers what each native session file parsed into, keyed by its path,
/// modified time and size. The parsers are pure functions of a file's content,
/// so an unchanged file never has to be opened again. One cache lives for the
/// process, so reopening the resume dialog reparses only what changed.
#[derive(Debug, Clone, Default)]
pub struct NativeScanCache {
    inner: Arc<Mutex<NativeScanCacheInner>>,
}

impl NativeScanCache {
    pub fn new() -> Self {
        Self::default()
    }

    /// The cache shared by index discovery and Mjolnir's SessionWiki reads.
    pub(crate) fn shared() -> Self {
        static CACHE: std::sync::OnceLock<NativeScanCache> = std::sync::OnceLock::new();
        CACHE.get_or_init(Self::new).clone()
    }

    /// How many files this cache has actually parsed, for tests and diagnostics.
    pub fn parsed_files(&self) -> u64 {
        self.lock().parsed_files
    }

    /// Index discovery excludes identified children, preserving parents even
    /// when their entrypoint or missing working directory prevents importing.
    pub(crate) fn index_eligible(&self, kind: HarnessKind, path: &Path) -> Result<bool> {
        if kind == HarnessKind::Claude
            && path
                .components()
                .any(|component| component.as_os_str() == "subagents")
        {
            return Ok(false);
        }
        let metadata = fs::metadata(path)?;
        let modified_at = metadata.modified()?;
        let size_bytes = metadata.len();
        if let Some(CachedNativeMetadata::IndexEligible(eligible)) =
            self.cached(path, modified_at, size_bytes)
        {
            return Ok(eligible);
        }
        let eligible = match kind {
            HarnessKind::Codex => !codex::codex_session_summary(path)?.subagent,
            HarnessKind::Claude => !claude::claude_native_summary(path)?.subagent,
            other => bail!("{other:?} has its own top-level source enumeration"),
        };
        self.store(
            path,
            modified_at,
            size_bytes,
            CachedNativeMetadata::IndexEligible(eligible),
        );
        Ok(eligible)
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, NativeScanCacheInner> {
        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn cached(
        &self,
        path: &Path,
        modified_at: SystemTime,
        size_bytes: u64,
    ) -> Option<CachedNativeMetadata> {
        let inner = self.lock();
        let entry = inner.entries.get(path)?;
        (entry.modified_at == modified_at && entry.size_bytes == size_bytes)
            .then(|| entry.metadata.clone())
    }

    fn store(
        &self,
        path: &Path,
        modified_at: SystemTime,
        size_bytes: u64,
        metadata: CachedNativeMetadata,
    ) {
        let mut inner = self.lock();
        inner.parsed_files = inner.parsed_files.saturating_add(1);
        inner.entries.insert(
            path.to_owned(),
            CachedNativeEntry {
                modified_at,
                size_bytes,
                metadata,
            },
        );
    }

    /// Claude metadata for one transcript, parsing only on a cache miss.
    /// Errors are returned to the caller and never cached.
    pub(super) fn claude_metadata(
        &self,
        path: &Path,
        modified_at: SystemTime,
        size_bytes: u64,
        parse: impl FnOnce() -> Result<Option<(String, PathBuf, String)>>,
    ) -> Result<Option<(String, PathBuf, String)>> {
        if let Some(CachedNativeMetadata::Claude(metadata)) =
            self.cached(path, modified_at, size_bytes)
        {
            return Ok(metadata);
        }
        let metadata = parse()?;
        self.store(
            path,
            modified_at,
            size_bytes,
            CachedNativeMetadata::Claude(metadata.clone()),
        );
        Ok(metadata)
    }

    /// Codex metadata for one rollout, parsing only on a cache miss.
    pub(super) fn codex_metadata(
        &self,
        path: &Path,
        modified_at: SystemTime,
        size_bytes: u64,
        parse: impl FnOnce() -> Result<Option<CodexSessionMetadata>>,
    ) -> Result<Option<CodexSessionMetadata>> {
        if let Some(CachedNativeMetadata::Codex(metadata)) =
            self.cached(path, modified_at, size_bytes)
        {
            return Ok(metadata);
        }
        let metadata = parse()?;
        self.store(
            path,
            modified_at,
            size_bytes,
            CachedNativeMetadata::Codex(metadata.clone()),
        );
        Ok(metadata)
    }
}

/// One native session located on disk, normalized across harnesses: the id
/// `session/load` takes and the file or directory its transcript is read from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocatedNativeSession {
    pub native_session_id: String,
    pub source_path: PathBuf,
}

/// One native session as a picker lists it, normalized across harnesses.
#[derive(Debug, Clone)]
pub struct NativeSessionListing {
    pub native_session_id: String,
    pub title: String,
    pub modified_at: SystemTime,
    pub git_branch: String,
    pub size_bytes: u64,
    pub cwd: PathBuf,
    /// Why this session cannot be imported, when it cannot be.
    pub unavailable_reason: Option<&'static str>,
    /// Archived inside the harness itself. Only Codex reports this today.
    pub natively_archived: bool,
}

/// Locate one native session for any harness.
pub fn locate_native_session(
    harness: HarnessKind,
    home: &Path,
    selection: &ClaudeSessionSelection,
) -> Result<LocatedNativeSession> {
    let (native_session_id, source_path) = match harness {
        HarnessKind::Muse => {
            return muse::locate(&mj_checkpoint::native::muse_sessions_root(home)?, selection);
        }
        HarnessKind::Codex => {
            let located = locate_codex_session(home, selection)?;
            (located.native_session_id, located.jsonl_path)
        }
        HarnessKind::Claude => {
            let located = locate_claude_session(home, selection)?;
            (located.native_session_id, located.jsonl_path)
        }
        HarnessKind::Kimi => {
            let located = locate_kimi_session(home, selection)?;
            (located.native_session_id, located.session_path)
        }
        HarnessKind::Grok => {
            let located = locate_grok_session(home, selection)?;
            (located.native_session_id, located.session_path)
        }
        HarnessKind::OpenCode => bail!(
            "OpenCode keeps its sessions in a SQLite database; Mjolnir cannot import them yet"
        ),
    };
    Ok(LocatedNativeSession {
        native_session_id,
        source_path,
    })
}

/// The id [`locate_native_session`] takes, read back from the path that
/// locator produced. `None` when the path has no readable name.
///
/// The inverse of the locators above, so every caller that has only a
/// transcript path — the SessionWiki index stores one per row — names the
/// session the same way `mj import` does. Each harness keeps its id in a
/// different part of the path: Claude Code names the file after the session,
/// Codex appends the thread UUID to a `rollout-` prefix, Kimi and Grok name
/// the session's own directory, and Muse names the directory above
/// `session.jsonl`.
pub fn native_session_id_from_path(harness: HarnessKind, path: &Path) -> Option<String> {
    match harness {
        HarnessKind::Claude => path.file_stem()?.to_str().map(str::to_owned),
        HarnessKind::Codex => codex_rollout_id_from_path(path).map(str::to_owned),
        HarnessKind::Kimi | HarnessKind::Grok => path.file_name()?.to_str().map(str::to_owned),
        HarnessKind::Muse => path.parent()?.file_name()?.to_str().map(str::to_owned),
        // OpenCode sessions live in SQLite rows, not files, so no transcript
        // path carries their id.
        HarnessKind::OpenCode => None,
    }
}

/// Where one native session's transcript lives and when it last changed.
///
/// Cheaper than [`NativeSessionListing`]: no git branch and no directory size,
/// because the search index only needs a stable key and a change token.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeSessionSource {
    pub native_session_id: String,
    pub source_path: PathBuf,
    /// The newest modification time of the session's own transcript files, not
    /// of the directory that holds them.
    pub modified_at: SystemTime,
}

/// List the sessions of one harness home for indexing.
///
/// Only the harnesses whose sessions Mjolnir itself has to enumerate are
/// supported; Codex and Claude Code keep one file per session, which their
/// own readers walk directly.
pub fn list_native_session_sources(
    harness: HarnessKind,
    home: &Path,
) -> Result<Vec<NativeSessionSource>> {
    let sources = match harness {
        HarnessKind::Kimi => kimi_indexed_candidates(home, &home.join("sessions"))?
            .into_iter()
            .map(|candidate| NativeSessionSource {
                native_session_id: candidate.native_session_id,
                source_path: candidate.session_path,
                modified_at: candidate.modified_at,
            })
            .collect(),
        HarnessKind::Grok => grok::grok_candidates(&home.join("sessions"))?
            .into_iter()
            .map(|candidate| NativeSessionSource {
                native_session_id: candidate.native_session_id,
                source_path: candidate.session_path,
                modified_at: candidate.modified_at,
            })
            .collect(),
        HarnessKind::Muse => muse::list_sources(&mj_checkpoint::native::muse_sessions_root(home)?)?,
        HarnessKind::OpenCode => bail!(
            "OpenCode keeps its sessions in a SQLite database; Mjolnir cannot enumerate them yet"
        ),
        other => bail!("{other:?} keeps one session per file; there is nothing to enumerate"),
    };
    Ok(sources)
}

/// The title the harness itself records for one session, read from that
/// session's own metadata file. `None` when the harness records none, which
/// leaves the caller to derive a title from the conversation.
pub fn native_session_title(harness: HarnessKind, source_path: &Path) -> Option<String> {
    match harness {
        HarnessKind::Kimi => {
            kimi_state_listing_metadata(source_path, Path::new("")).map(|(title, _, _)| title)
        }
        HarnessKind::Grok => grok::grok_listing_metadata(source_path).0,
        _ => None,
    }
}

/// Project one native session into the canonical transcript, for any harness.
pub fn read_native_transcript(
    harness: HarnessKind,
    source_path: &Path,
) -> Result<ClaudeTranscript> {
    match harness {
        HarnessKind::Muse => muse::read_transcript(source_path),
        HarnessKind::Codex => read_codex_transcript(source_path),
        HarnessKind::Claude => read_claude_transcript(source_path),
        HarnessKind::Kimi => read_kimi_transcript(source_path),
        HarnessKind::Grok => read_grok_transcript(source_path),
        HarnessKind::OpenCode => bail!(
            "OpenCode keeps its sessions in a SQLite database; Mjolnir cannot import them yet"
        ),
    }
}

/// Scan a harness home newest first, reporting after every candidate.
pub fn scan_native_sessions(
    harness: HarnessKind,
    home: &Path,
    cache: &NativeScanCache,
    mut report: impl FnMut(SessionScanProgress<NativeSessionListing>),
) -> Result<()> {
    let mut forward = |scanned, total, session| {
        report(SessionScanProgress {
            scanned,
            total,
            session,
        });
    };
    match harness {
        HarnessKind::Muse => muse::scan(
            &mj_checkpoint::native::muse_sessions_root(home)?,
            |progress| {
                forward(progress.scanned, progress.total, progress.session);
            },
        ),
        HarnessKind::Codex => scan_codex_sessions(home, cache, |progress| {
            let session = progress.session.map(|session| NativeSessionListing {
                unavailable_reason: session.history_mode.import_issue(),
                native_session_id: session.native_session_id,
                title: session.title,
                modified_at: session.modified_at,
                git_branch: session.git_branch,
                size_bytes: session.size_bytes,
                cwd: session.cwd,
                natively_archived: session.natively_archived,
            });
            forward(progress.scanned, progress.total, session);
        }),
        HarnessKind::Claude => scan_claude_sessions(home, cache, |progress| {
            let session = progress.session.map(|session| NativeSessionListing {
                native_session_id: session.native_session_id,
                title: session.title,
                modified_at: session.modified_at,
                git_branch: session.git_branch,
                size_bytes: session.size_bytes,
                cwd: session.cwd,
                unavailable_reason: None,
                natively_archived: false,
            });
            forward(progress.scanned, progress.total, session);
        }),
        HarnessKind::Kimi => scan_kimi_sessions(home, |progress| {
            let session = progress.session.map(|session| NativeSessionListing {
                native_session_id: session.native_session_id,
                title: session.title,
                modified_at: session.modified_at,
                git_branch: session.git_branch,
                size_bytes: session.size_bytes,
                cwd: session.cwd,
                unavailable_reason: None,
                natively_archived: false,
            });
            forward(progress.scanned, progress.total, session);
        }),
        HarnessKind::Grok => scan_grok_sessions(home, |progress| {
            let session = progress.session.map(|session| NativeSessionListing {
                native_session_id: session.native_session_id,
                title: session.title,
                modified_at: session.modified_at,
                git_branch: session.git_branch,
                size_bytes: session.size_bytes,
                cwd: session.cwd,
                unavailable_reason: None,
                natively_archived: false,
            });
            forward(progress.scanned, progress.total, session);
        }),
        HarnessKind::OpenCode => bail!(
            "OpenCode keeps its sessions in a SQLite database; Mjolnir cannot enumerate them yet"
        ),
    }
}