toolpath-claude 0.13.3

Derive Toolpath provenance documents from Claude conversation logs
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Session chain resolution for Claude Code's file rotation.
//!
//! When Claude Code rotates to a new JSONL file (plan-mode exit, context
//! overflow), the new file's first real entry carries the **old** session
//! ID — a "bridge entry" linking the two files. This module detects those
//! links and resolves full chains so callers can treat a multi-file
//! conversation as a single logical session.

use crate::error::Result;
use crate::paths::PathResolver;
use crate::reader::ConversationReader;
use crate::types::ConversationEntry;
use std::collections::{HashMap, HashSet};

/// Resolve a chain using a pre-built succession map.
///
/// Walks backwards from `session_id` to the head, then forwards to the
/// tail. Returns the chain in chronological order (oldest first).
pub(crate) fn resolve_chain_with_map(
    succession: &HashMap<String, String>,
    session_id: &str,
) -> Vec<String> {
    // Walk backwards to find the chain head (the segment with no predecessor).
    let reverse: HashMap<&str, &str> = succession
        .iter()
        .map(|(pred, succ)| (succ.as_str(), pred.as_str()))
        .collect();

    let mut visited = HashSet::new();
    let mut head = session_id;
    visited.insert(head);
    while let Some(&pred) = reverse.get(head) {
        if !visited.insert(pred) {
            break; // cycle detected
        }
        head = pred;
    }

    // Walk forward from head collecting the chain.
    let mut seen = HashSet::new();
    let mut chain = vec![head.to_string()];
    seen.insert(head);
    let mut current = head;
    while let Some(next) = succession.get(current) {
        if !seen.insert(next.as_str()) {
            break; // cycle detected
        }
        chain.push(next.clone());
        current = next;
    }

    chain
}

/// Cached index of session succession relationships.
///
/// Incrementally built: once a file has been checked and found not to be
/// a successor, it's never re-checked (`non_successors` is an immutable
/// property of a file's first entry).
#[derive(Debug, Clone)]
pub(crate) struct ChainIndex {
    /// predecessor session_id → successor file stem
    succession: HashMap<String, String>,
    /// successor file stem → predecessor session_id
    reverse: HashMap<String, String>,
    /// File stems confirmed not to be successors (immutable property)
    non_successors: HashSet<String>,
    /// All file stems we've ever checked
    known_files: HashSet<String>,
}

impl ChainIndex {
    pub(crate) fn new() -> Self {
        Self {
            succession: HashMap::new(),
            reverse: HashMap::new(),
            non_successors: HashSet::new(),
            known_files: HashSet::new(),
        }
    }

    /// Scan for new files and classify them. Files already in
    /// `known_files` are skipped entirely.
    pub(crate) fn refresh(&mut self, resolver: &PathResolver, project_path: &str) -> Result<()> {
        let sessions = resolver.list_conversations(project_path)?;

        for file_stem in &sessions {
            if self.known_files.contains(file_stem.as_str()) {
                continue;
            }
            self.known_files.insert(file_stem.clone());

            // Rotation artifacts (`<uuid>.orphaned-<ts>-<hash>`) open with a
            // foreign-looking `sessionId` — their entries' own uuid, which the
            // mangled stem no longer equals — so the old classifier chained
            // them in as successors, whereupon every entry of the segment read
            // as a bridge entry and the whole segment (turns, usage) silently
            // vanished from the merged conversation. A session stem never
            // contains a dot; anything dotted is classified standalone here
            // and excluded from chain_heads() below.
            if file_stem.contains('.') {
                self.non_successors.insert(file_stem.clone());
                continue;
            }

            let path = resolver.conversation_file(project_path, file_stem)?;
            if let Some(first_sid) = ConversationReader::read_first_session_id(&path) {
                if first_sid != *file_stem {
                    // This file is a successor of first_sid
                    self.succession.insert(first_sid.clone(), file_stem.clone());
                    self.reverse.insert(file_stem.clone(), first_sid);
                } else {
                    self.non_successors.insert(file_stem.clone());
                }
            } else {
                self.non_successors.insert(file_stem.clone());
            }
        }

        Ok(())
    }

    /// Resolve the full chain containing `session_id` (oldest first).
    pub(crate) fn resolve_chain(&self, session_id: &str) -> Vec<String> {
        resolve_chain_with_map(&self.succession, session_id)
    }

    /// Return the chain head (earliest segment) for `session_id`.
    #[allow(dead_code)]
    pub(crate) fn head_for(&self, session_id: &str) -> String {
        let chain = self.resolve_chain(session_id);
        chain
            .into_iter()
            .next()
            .unwrap_or_else(|| session_id.to_string())
    }

    /// Immediate successor of `session_id`, if any.
    #[cfg(any(feature = "watcher", test))]
    pub(crate) fn successor_of(&self, session_id: &str) -> Option<&str> {
        self.succession.get(session_id).map(|s| s.as_str())
    }

    /// All chain heads — file stems that are not successors of another.
    ///
    /// Dotted stems (`.orphaned-*` rotation artifacts) are excluded even
    /// though they stand outside every chain: a head becomes a derived
    /// document whose id truncates the stem to its first 8 characters,
    /// which for an orphan equals its parent session's prefix — the two
    /// documents would overwrite each other in the cache. Until ids can
    /// carry the full stem, orphans are neither chained nor listed.
    pub(crate) fn chain_heads(&self) -> Vec<String> {
        self.known_files
            .iter()
            .filter(|stem| !self.reverse.contains_key(stem.as_str()) && !stem.contains('.'))
            .cloned()
            .collect()
    }

    /// Whether `session_id` is a successor file (not a chain head).
    #[allow(dead_code)]
    pub(crate) fn is_successor(&self, session_id: &str) -> bool {
        self.reverse.contains_key(session_id)
    }
}

/// Test whether an entry is a bridge entry (its `session_id` differs
/// from the owning conversation's session_id).
pub(crate) fn is_bridge_entry(entry: &ConversationEntry, owner_session_id: &str) -> bool {
    entry
        .session_id
        .as_ref()
        .is_some_and(|sid| !sid.is_empty() && sid != owner_session_id)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn setup_chain_env() -> (TempDir, PathResolver) {
        let temp = TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        let project_dir = claude_dir.join("projects/-test-project");
        fs::create_dir_all(&project_dir).unwrap();

        let resolver = PathResolver::new().with_claude_dir(&claude_dir);
        (temp, resolver)
    }

    fn write_session(resolver: &PathResolver, session_id: &str, entries: &[&str]) {
        let path = resolver
            .conversation_file("/test/project", session_id)
            .unwrap();
        fs::write(&path, entries.join("\n")).unwrap();
    }

    // ── ChainIndex tests ─────────────────────────────────────────────

    #[test]
    fn test_chain_index_basic_build() {
        let (_temp, resolver) = setup_chain_env();

        write_session(
            &resolver,
            "session-a",
            &[
                r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Hello"}}"#,
            ],
        );

        write_session(
            &resolver,
            "session-b",
            &[
                r#"{"type":"user","uuid":"u2","timestamp":"2024-01-01T01:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Bridge"}}"#,
                r#"{"type":"user","uuid":"u3","timestamp":"2024-01-01T01:00:01Z","sessionId":"session-b","message":{"role":"user","content":"New"}}"#,
            ],
        );

        let mut index = ChainIndex::new();
        index.refresh(&resolver, "/test/project").unwrap();

        assert_eq!(index.successor_of("session-a"), Some("session-b"));
        assert!(index.successor_of("session-b").is_none());
        assert!(index.is_successor("session-b"));
        assert!(!index.is_successor("session-a"));
        assert_eq!(index.head_for("session-b"), "session-a");
        assert_eq!(index.head_for("session-a"), "session-a");
    }

    #[test]
    fn test_chain_index_incremental_refresh() {
        let (_temp, resolver) = setup_chain_env();

        write_session(
            &resolver,
            "session-a",
            &[
                r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Hello"}}"#,
            ],
        );

        let mut index = ChainIndex::new();
        index.refresh(&resolver, "/test/project").unwrap();
        assert_eq!(index.chain_heads().len(), 1);
        assert!(index.chain_heads().contains(&"session-a".to_string()));

        // Add a successor file after initial build
        write_session(
            &resolver,
            "session-b",
            &[
                r#"{"type":"user","uuid":"u2","timestamp":"2024-01-01T01:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Bridge"}}"#,
            ],
        );

        index.refresh(&resolver, "/test/project").unwrap();
        assert_eq!(index.successor_of("session-a"), Some("session-b"));

        let heads = index.chain_heads();
        assert_eq!(heads.len(), 1);
        assert!(heads.contains(&"session-a".to_string()));
    }

    #[test]
    fn test_chain_index_chain_heads() {
        let (_temp, resolver) = setup_chain_env();

        // Two independent conversations
        write_session(
            &resolver,
            "session-x",
            &[
                r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-x","message":{"role":"user","content":"Hello"}}"#,
            ],
        );

        write_session(
            &resolver,
            "session-y",
            &[
                r#"{"type":"user","uuid":"u2","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-y","message":{"role":"user","content":"World"}}"#,
            ],
        );

        // Chain: session-a → session-b
        write_session(
            &resolver,
            "session-a",
            &[
                r#"{"type":"user","uuid":"u3","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Start"}}"#,
            ],
        );

        write_session(
            &resolver,
            "session-b",
            &[
                r#"{"type":"user","uuid":"u4","timestamp":"2024-01-01T01:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Bridge"}}"#,
            ],
        );

        let mut index = ChainIndex::new();
        index.refresh(&resolver, "/test/project").unwrap();

        let mut heads = index.chain_heads();
        heads.sort();
        // session-b is a successor, so heads are: session-a, session-x, session-y
        assert_eq!(heads.len(), 3);
        assert!(heads.contains(&"session-a".to_string()));
        assert!(heads.contains(&"session-x".to_string()));
        assert!(heads.contains(&"session-y".to_string()));
        assert!(!heads.contains(&"session-b".to_string()));
    }

    #[test]
    fn test_chain_index_resolve_chain_three_segments() {
        let (_temp, resolver) = setup_chain_env();

        write_session(
            &resolver,
            "session-a",
            &[
                r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Start"}}"#,
            ],
        );

        write_session(
            &resolver,
            "session-b",
            &[
                r#"{"type":"user","uuid":"u2","timestamp":"2024-01-01T01:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Bridge AB"}}"#,
            ],
        );

        write_session(
            &resolver,
            "session-c",
            &[
                r#"{"type":"user","uuid":"u3","timestamp":"2024-01-01T02:00:00Z","sessionId":"session-b","message":{"role":"user","content":"Bridge BC"}}"#,
            ],
        );

        let mut index = ChainIndex::new();
        index.refresh(&resolver, "/test/project").unwrap();

        assert_eq!(
            index.resolve_chain("session-a"),
            vec!["session-a", "session-b", "session-c"]
        );
        assert_eq!(
            index.resolve_chain("session-b"),
            vec!["session-a", "session-b", "session-c"]
        );
        assert_eq!(
            index.resolve_chain("session-c"),
            vec!["session-a", "session-b", "session-c"]
        );
    }

    // ── resolve_chain_with_map tests ─────────────────────────────────

    #[test]
    fn test_resolve_chain_with_map_cycle() {
        // Corrupt data: A→B and B→A would loop forever without cycle detection
        let mut succession = HashMap::new();
        succession.insert("session-a".to_string(), "session-b".to_string());
        succession.insert("session-b".to_string(), "session-a".to_string());

        let chain = resolve_chain_with_map(&succession, "session-a");
        // Should terminate and contain at most the two nodes (no infinite loop)
        assert!(chain.len() <= 2);
        assert!(chain.contains(&"session-a".to_string()));
    }

    #[test]
    fn test_resolve_chain_with_map_self_loop() {
        // Degenerate: A→A
        let mut succession = HashMap::new();
        succession.insert("session-a".to_string(), "session-a".to_string());

        let chain = resolve_chain_with_map(&succession, "session-a");
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0], "session-a");
    }

    // ── is_bridge_entry tests ────────────────────────────────────────

    #[test]
    fn test_is_bridge_entry() {
        let entry: ConversationEntry = serde_json::from_str(
            r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Hi"}}"#,
        )
        .unwrap();

        // Entry with session_id "session-a" in a file owned by "session-b" is a bridge
        assert!(is_bridge_entry(&entry, "session-b"));

        // Entry with matching session_id is not a bridge
        assert!(!is_bridge_entry(&entry, "session-a"));
    }

    #[test]
    fn test_orphaned_stem_is_not_a_successor() {
        let (_temp, resolver) = setup_chain_env();

        write_session(
            &resolver,
            "session-a",
            &[
                r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Hello"}}"#,
            ],
        );

        // A rotation artifact: mangled stem, every entry carrying the
        // original session's id. Must never be chained onto session-a.
        write_session(
            &resolver,
            "session-a.orphaned-1787626221622-ac84712d",
            &[
                r#"{"type":"user","uuid":"u2","timestamp":"2024-01-01T02:00:00Z","sessionId":"session-a","message":{"role":"user","content":"Orphaned"}}"#,
            ],
        );

        let mut index = ChainIndex::new();
        index.refresh(&resolver, "/test/project").unwrap();

        assert!(index.successor_of("session-a").is_none());
        assert!(!index.is_successor("session-a.orphaned-1787626221622-ac84712d"));

        // And it is not a listable head either: its derived id would
        // truncate to the parent session's prefix and collide in the cache.
        let heads = index.chain_heads();
        assert!(heads.contains(&"session-a".to_string()));
        assert!(!heads.iter().any(|h| h.contains(".orphaned-")));
    }

    #[test]
    fn test_is_bridge_entry_no_session_id() {
        let entry: ConversationEntry = serde_json::from_str(
            r#"{"type":"user","uuid":"u1","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"Hi"}}"#,
        )
        .unwrap();

        // Entry without session_id is never a bridge
        assert!(!is_bridge_entry(&entry, "session-b"));
    }
}