path-cli 0.16.1

CLI for deriving, querying, and visualizing Toolpath provenance (binary: path)
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
//! Per-provider artifact sources. [`ArtifactSource`] is the seam
//! between the sync engine and the providers: everything the engine
//! needs from one provider — enumerate its artifacts with stat-level
//! fingerprints, stat one artifact directly, derive one into a
//! document, peek at where one lives, compare directories in its key
//! space — sits behind the trait, one impl per provider. The engine
//! never matches on [`ArtifactType`]; provider details changing means
//! editing that provider's impl here, nothing else.

use anyhow::{Result, anyhow};
use chrono::{DateTime, Utc};

use crate::artifact::{ArtifactRef, ArtifactType, claude_chain_stamp, stat_stamp};
use crate::derive::{self, DerivedDoc};
use crate::harness::{
    HarnessBundle, is_not_found_claude, is_not_found_codex, is_not_found_cursor,
    is_not_found_gemini, is_not_found_opencode, is_not_found_pi,
};

/// A source's stat-level fingerprint for one artifact: mtime (file
/// providers) or updated-at (DB providers), plus file size — each
/// `None` when unavailable.
pub(crate) type Stamp = (Option<DateTime<Utc>>, Option<u64>);

/// One provider, as the sync engine sees it.
pub(crate) trait ArtifactSource {
    /// Enumerate this provider's artifacts with stat-level
    /// fingerprints. Never reads session bodies. Listing errors warn
    /// and skip so one broken provider can't block a run.
    fn enumerate(&self) -> Vec<ArtifactRef>;

    /// Stat-level fingerprint for a single artifact, resolved
    /// directly — the same stat targets as [`Self::enumerate`], so the
    /// result compares against manifest records. `project` is required
    /// by the path-keyed providers (claude/gemini/pi).
    fn stamp(&self, project: Option<&str>, id: &str) -> Option<Stamp>;

    /// Derive one enumerated artifact into a cacheable document,
    /// through the same manager it was enumerated from, so listing and
    /// derivation always agree on provider roots.
    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc>;
}

/// The source for `t`'s artifacts, borrowing its manager from
/// `bundle`. `None` when the provider isn't in the bundle — and for
/// git, which is recorded by `p import` but never discovered: there is
/// no machine-wide registry of repos to enumerate.
pub(crate) fn source_for<'a>(
    bundle: &'a HarnessBundle,
    t: ArtifactType,
) -> Option<Box<dyn ArtifactSource + 'a>> {
    match t {
        ArtifactType::Claude => Some(Box::new(ClaudeSource(bundle.claude.as_ref()?))),
        ArtifactType::Gemini => Some(Box::new(GeminiSource(bundle.gemini.as_ref()?))),
        ArtifactType::Codex => Some(Box::new(CodexSource(bundle.codex.as_ref()?))),
        ArtifactType::Opencode => Some(Box::new(OpencodeSource(bundle.opencode.as_ref()?))),
        ArtifactType::Cursor => Some(Box::new(CursorSource(bundle.cursor.as_ref()?))),
        ArtifactType::Pi => Some(Box::new(PiSource(bundle.pi.as_ref()?))),
        ArtifactType::Copilot => Some(Box::new(CopilotSource(bundle.copilot.as_ref()?))),
        ArtifactType::Git => None,
    }
}

/// The project path a path-keyed artifact was enumerated under.
fn require_path(artifact: &ArtifactRef) -> Result<&str> {
    artifact
        .path
        .as_deref()
        .ok_or_else(|| anyhow!("artifact {} has no path", artifact.id))
}

// ── claude ─────────────────────────────────────────────────────────

struct ClaudeSource<'a>(&'a toolpath_claude::ClaudeConvo);

impl ArtifactSource for ClaudeSource<'_> {
    /// Chain heads via `list_conversations` (bounded first-lines peek
    /// per file, no full parse). The head is the chain's *oldest*
    /// segment and its id is rotation-stable; the fingerprint covers
    /// the whole chain (see `claude_chain_stamp`) because appends land
    /// in the newest segment, not the head file.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let projects = match self.0.list_projects() {
            Ok(ps) => ps,
            Err(e) if is_not_found_claude(&e) => return out,
            Err(e) => {
                eprintln!("warning: claude enumeration failed: {e}");
                return out;
            }
        };
        for project in projects {
            let heads = match self.0.list_conversations(&project) {
                Ok(h) => h,
                Err(e) => {
                    eprintln!("warning: claude project {project} failed: {e}");
                    continue;
                }
            };
            for head in heads {
                let (modified, size) = claude_chain_stamp(self.0, &project, &head);
                out.push(ArtifactRef {
                    artifact_type: ArtifactType::Claude,
                    id: head,
                    path: Some(project.clone()),
                    modified,
                    size,
                });
            }
        }
        out
    }

    fn stamp(&self, project: Option<&str>, id: &str) -> Option<Stamp> {
        Some(claude_chain_stamp(self.0, project?, id))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_claude_session_with(self.0, require_path(artifact)?, &artifact.id)
    }
}

// ── gemini ─────────────────────────────────────────────────────────

struct GeminiSource<'a>(&'a toolpath_gemini::GeminiConvo);

impl ArtifactSource for GeminiSource<'_> {
    /// Session entries via a bounded identity peek (`toolpath-gemini`
    /// reads at most the first 4 KiB of a main file); the fingerprint
    /// stats the main file (or the orphan sub-agent directory).
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let projects = match self.0.list_projects() {
            Ok(ps) => ps,
            Err(e) if is_not_found_gemini(&e) => return out,
            Err(e) => {
                eprintln!("warning: gemini enumeration failed: {e}");
                return out;
            }
        };
        for project in projects {
            let entries = match self.0.resolver().list_session_entries(&project) {
                Ok(entries) => entries,
                Err(e) => {
                    eprintln!("warning: gemini project {project} failed: {e}");
                    continue;
                }
            };
            for entry in entries {
                let (modified, size) = stat_stamp(&entry.path);
                out.push(ArtifactRef {
                    artifact_type: ArtifactType::Gemini,
                    id: entry.session_uuid.unwrap_or(entry.id),
                    path: Some(project.clone()),
                    modified,
                    size,
                });
            }
        }
        out
    }

    fn stamp(&self, project: Option<&str>, id: &str) -> Option<Stamp> {
        let entries = self.0.resolver().list_session_entries(project?).ok()?;
        let entry = entries
            .into_iter()
            .find(|e| e.id == id || e.session_uuid.as_deref() == Some(id))?;
        Some(stat_stamp(&entry.path))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_gemini_session_with(self.0, require_path(artifact)?, &artifact.id)
    }
}

// ── codex ──────────────────────────────────────────────────────────

struct CodexSource<'a>(&'a toolpath_codex::CodexConvo);

impl ArtifactSource for CodexSource<'_> {
    /// Rollout files, stat-only. The artifact id is the trailing UUID of
    /// the filename stem (`rollout-<timestamp>-<uuid>`); `read_session`
    /// accepts either the UUID or the full stem, so the fallback is safe.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let files = match self.0.io().list_rollout_files() {
            Ok(f) => f,
            Err(e) if is_not_found_codex(&e) => return out,
            Err(e) => {
                eprintln!("warning: codex enumeration failed: {e}");
                return out;
            }
        };
        for file in files {
            let Some(stem) = file.file_stem().and_then(|s| s.to_str()) else {
                continue;
            };
            let id = toolpath_codex::session_id_from_stem(stem).to_string();
            let (modified, size) = stat_stamp(&file);
            out.push(ArtifactRef {
                artifact_type: ArtifactType::Codex,
                id,
                path: None,
                modified,
                size,
            });
        }
        out
    }

    fn stamp(&self, _project: Option<&str>, id: &str) -> Option<Stamp> {
        let file = self.0.resolver().find_rollout_file(id).ok()?;
        Some(stat_stamp(&file))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_codex_session_with(self.0, &artifact.id)
    }
}

// ── opencode ───────────────────────────────────────────────────────

struct OpencodeSource<'a>(&'a toolpath_opencode::OpencodeConvo);

impl ArtifactSource for OpencodeSource<'_> {
    /// One header-only `SELECT` — `time_updated` is the fingerprint; no
    /// message bodies are loaded.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let sessions = match self.0.io().list_sessions(None) {
            Ok(s) => s,
            Err(e) if is_not_found_opencode(&e) => return out,
            Err(e) => {
                eprintln!("warning: opencode enumeration failed: {e}");
                return out;
            }
        };
        for s in sessions {
            out.push(ArtifactRef {
                artifact_type: ArtifactType::Opencode,
                modified: s.last_activity(),
                path: Some(s.directory.to_string_lossy().into_owned()),
                id: s.id,
                size: None,
            });
        }
        out
    }

    fn stamp(&self, _project: Option<&str>, id: &str) -> Option<Stamp> {
        let sessions = self.0.io().list_sessions(None).ok()?;
        let session = sessions.into_iter().find(|s| s.id == id)?;
        Some((session.last_activity(), None))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_opencode_session_with(self.0, &artifact.id, false)
    }
}

// ── cursor ─────────────────────────────────────────────────────────

struct CursorSource<'a>(&'a toolpath_cursor::CursorConvo);

impl ArtifactSource for CursorSource<'_> {
    /// Composer headers (one `SELECT` plus a per-composer bubble-count
    /// check) — `lastUpdatedAt` is the fingerprint. Bubble-less drafts
    /// are skipped; unlike `share`, composers without a workspace are
    /// included, since sync doesn't need to rank them by project.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let listings = match self.0.io().list_composers() {
            Ok(l) => l,
            Err(e) if is_not_found_cursor(&e) => return out,
            Err(e) => {
                eprintln!("warning: cursor enumeration failed: {e}");
                return out;
            }
        };
        for l in listings.into_iter().filter(|l| l.has_bubbles) {
            out.push(ArtifactRef {
                artifact_type: ArtifactType::Cursor,
                modified: l.head.last_updated_at_utc(),
                path: l
                    .head
                    .workspace_path()
                    .map(|p| p.to_string_lossy().into_owned()),
                id: l.head.composer_id,
                size: None,
            });
        }
        out
    }

    fn stamp(&self, _project: Option<&str>, id: &str) -> Option<Stamp> {
        let headers = self.0.io().read_composer_headers().ok()?;
        let composer = headers
            .all_composers
            .into_iter()
            .find(|c| c.composer_id == id)?;
        Some((composer.last_updated_at_utc(), None))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_cursor_session_with(self.0, &artifact.id)
    }
}

// ── pi ─────────────────────────────────────────────────────────────

struct PiSource<'a>(&'a toolpath_pi::PiConvo);

impl ArtifactSource for PiSource<'_> {
    /// Session files stat-only; the id comes from a one-line header
    /// peek, falling back to the filename stem's `<timestamp>_<id>`
    /// shape — the same resolution `read_session` accepts.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let projects = match self.0.list_projects() {
            Ok(ps) => ps,
            Err(e) if is_not_found_pi(&e) => return out,
            Err(e) => {
                eprintln!("warning: pi enumeration failed: {e}");
                return out;
            }
        };
        for project in projects {
            let files = match toolpath_pi::reader::list_session_files(self.0.resolver(), &project) {
                Ok(f) => f,
                Err(e) => {
                    eprintln!("warning: pi project {project} failed: {e}");
                    continue;
                }
            };
            for file in files {
                let header_id = toolpath_pi::reader::peek_header(&file)
                    .ok()
                    .map(|h| h.id)
                    .filter(|id| !id.is_empty());
                let stem_id = file
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .and_then(|s| s.split_once('_'))
                    .map(|(_, rest)| rest.to_string());
                let Some(id) = header_id.or(stem_id) else {
                    continue;
                };
                let (modified, size) = stat_stamp(&file);
                out.push(ArtifactRef {
                    artifact_type: ArtifactType::Pi,
                    id,
                    path: Some(project.clone()),
                    modified,
                    size,
                });
            }
        }
        out
    }

    fn stamp(&self, project: Option<&str>, id: &str) -> Option<Stamp> {
        let files = toolpath_pi::reader::list_session_files(self.0.resolver(), project?).ok()?;
        let file = files.into_iter().find(|f| {
            toolpath_pi::reader::peek_header(f).is_ok_and(|h| h.id == id)
                || f.file_stem()
                    .and_then(|stem| stem.to_str())
                    .and_then(|stem| stem.split_once('_'))
                    .is_some_and(|(_, rest)| rest == id)
        })?;
        Some(stat_stamp(&file))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_pi_session_with(self.0, require_path(artifact)?, &artifact.id)
    }
}

// ── copilot ────────────────────────────────────────────────────────

struct CopilotSource<'a>(&'a toolpath_copilot::CopilotConvo);

impl ArtifactSource for CopilotSource<'_> {
    /// Session-state directories, stat-only: each session is a
    /// `<id>/events.jsonl` under `session-state/` (or its legacy
    /// sibling); the directory name is the id and the events file is
    /// the fingerprint target.
    fn enumerate(&self) -> Vec<ArtifactRef> {
        let mut out = Vec::new();
        let mut seen = std::collections::HashSet::new();
        let dirs = [
            self.0.resolver().session_state_dir(),
            self.0.resolver().legacy_session_state_dir(),
        ];
        for dir in dirs.into_iter().flatten() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let Some(id) = entry.file_name().to_str().map(String::from) else {
                    continue;
                };
                let events = entry.path().join("events.jsonl");
                if !events.exists() || !seen.insert(id.clone()) {
                    continue;
                }
                let (modified, size) = stat_stamp(&events);
                out.push(ArtifactRef {
                    artifact_type: ArtifactType::Copilot,
                    id,
                    path: None,
                    modified,
                    size,
                });
            }
        }
        out
    }

    fn stamp(&self, _project: Option<&str>, id: &str) -> Option<Stamp> {
        let file = self.0.resolver().events_file(id).ok()?;
        Some(stat_stamp(&file))
    }

    fn derive(&self, artifact: &ArtifactRef) -> Result<DerivedDoc> {
        derive::derive_copilot_session_with(self.0, &artifact.id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn source_for_missing_provider_or_git_is_none() {
        let empty = HarnessBundle::default();
        assert!(source_for(&empty, ArtifactType::Claude).is_none());
        assert!(source_for(&empty, ArtifactType::Git).is_none());

        let with_claude = HarnessBundle {
            claude: Some(toolpath_claude::ClaudeConvo::new()),
            ..Default::default()
        };
        assert!(source_for(&with_claude, ArtifactType::Claude).is_some());
        assert!(
            source_for(&with_claude, ArtifactType::Git).is_none(),
            "git is recorded by `p import`, never enumerated or derived by sync"
        );
    }
}