Repository navigation
Expand file tree
/
Copy pathmod.rs
More file actions
368 lines (346 loc) · 13.7 KB
/
Copy pathmod.rs
File metadata and controls
368 lines (346 loc) · 13.7 KB
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
mod aider;
mod antigravity;
mod claude_code;
mod cline;
mod codex;
mod continue_dev;
mod gajae;
mod gemini;
mod gptme;
mod grok;
pub mod harness;
mod kimi;
mod muse;
mod opencode;
mod prodex;
pub use antigravity::Antigravity;
pub use claude_code::ClaudeCode;
pub(crate) use codex::is_subagent_meta as codex_is_subagent_meta;
#[cfg(test)]
pub(crate) use codex::THREAD_SCANS;
pub use codex::{Codex, CodexHistory};
pub(crate) use gemini::project_root as gemini_project_root;
pub use grok::GrokBuild;
pub use kimi::KimiCode;
pub use muse::Muse;
pub use prodex::thread_url_for_task as prodex_thread_url;
use crate::model::{Session, StoreReport};
use anyhow::Result;
use chrono::{DateTime, Utc};
use std::path::{Path, PathBuf};
/// One supported agent tool. An adapter knows where the tool keeps its
/// session files on disk and how to parse one file into a `Session`.
///
/// Adding support for a new tool means implementing this trait in a new
/// module and registering it in `all()`. PRs for new adapters are the main
/// way this project grows.
/// A store that holds many sessions in one place (e.g. a SQLite database)
/// rather than one file per session. Returned by [`Adapter::store`] when the
/// file-per-session model does not fit; the indexer then enumerates sessions
/// from `keys` (re-parsing only changed ones) instead of `discover`/`parse`.
pub struct Store {
/// `(stable key, change-token)` for every session, cheap to compute without
/// a full parse. The change-token (e.g. the session's updated-time in ms)
/// drives incremental re-indexing; the key identifies the session for
/// [`Adapter::parse_key`]. The key doubles as the session's stored path.
pub keys: Vec<(String, i64)>,
/// The backing files (the database), for `scan` size accounting.
pub files: Vec<PathBuf>,
/// True if a backing store existed but could not be read this run (locked,
/// half-written, permissions). The indexer then skips deletion
/// reconciliation, so a transient read failure cannot archive the whole
/// corpus off an incomplete key set.
pub had_error: bool,
}
/// The result of file discovery. `had_error` means the listing is PARTIAL: a
/// directory that exists could not be read (permissions, transient IO). The
/// indexer still indexes what was found but skips deletion reconciliation, so
/// a partial walk cannot archive live sessions off an incomplete listing - the
/// same guard [`Store::had_error`] gives shared-store adapters. A root that
/// simply does not exist on this machine is normal, not an error.
pub struct Discovered {
pub files: Vec<PathBuf>,
pub had_error: bool,
}
impl From<Vec<PathBuf>> for Discovered {
fn from(files: Vec<PathBuf>) -> Self {
Discovered {
files,
had_error: false,
}
}
}
/// `result.ok()` that records the failure in `had_error` instead of dropping
/// it silently - for walk loops that must report a partial listing.
pub(crate) fn ok_or_flag<T, E>(r: std::result::Result<T, E>, had_error: &mut bool) -> Option<T> {
match r {
Ok(v) => Some(v),
Err(_) => {
*had_error = true;
None
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct UnavailableMetadata {
pub title: bool,
pub project: bool,
pub subagent: bool,
}
impl UnavailableMetadata {
pub fn any(self) -> bool {
self.title || self.project || self.subagent
}
}
pub trait Adapter {
fn name(&self) -> &'static str;
/// Store root, e.g. ~/.claude/projects. May not exist on this machine.
fn root(&self) -> Option<PathBuf>;
/// All session files under the root, with a partial-walk flag the indexer
/// uses to protect deletion reconciliation (see [`Discovered`]).
fn discover(&self) -> Discovered;
/// Parse one session file. Must never panic on malformed input;
/// skip bad lines and return what could be read.
fn parse(&self, path: &Path) -> Result<Session>;
/// A shared store (many sessions in one database) for tools that do not use
/// one file per session. When `Some`, the indexer uses it instead of
/// `discover`/`parse`. Default `None` = ordinary file-per-session adapter.
fn store(&self) -> Option<Store> {
None
}
/// Parse one session out of a shared store by its key (from `store().keys`).
/// Only called for adapters that return a [`Store`].
fn parse_key(&self, _key: &str) -> Result<Session> {
anyhow::bail!("this adapter is not a shared store")
}
/// Fields whose stored values should survive temporarily unavailable metadata.
fn unavailable_metadata(&self, _key: &str) -> UnavailableMetadata {
UnavailableMetadata::default()
}
/// Most recent timestamp relevant to bounded-sync eligibility. Shared metadata
/// freshness may be included for already-indexed keys without backfilling old
/// unindexed conversations. Defaults to real per-key activity.
fn sync_activity_at(&self, key: &str, already_indexed: bool) -> Option<DateTime<Utc>> {
let _ = already_indexed;
self.modified_at(key)
}
/// Actual last activity time for a shared-store key, independent of its
/// opaque change-token. The default bounded-sync hook and
/// `scan` use it for the store's time span. Keep this metadata-only; it
/// must not parse the conversation. `None` preserves the legacy token
/// interpretation for adapters whose tokens already encode timestamps.
fn modified_at(&self, _key: &str) -> Option<chrono::DateTime<chrono::Utc>> {
None
}
/// Limit deletion reconciliation to part of this tool's indexed rows. When
/// `Some(prefix)`, only indexed rows whose key starts with `prefix` are
/// considered for archiving after this adapter runs. Use it when the
/// adapter's store holds only part of a tool's sessions - for example
/// several installations of the same tool sharing one tool name, each
/// listing only its own keys - so that one installation's sync cannot
/// archive another's rows. Default `None` = the adapter speaks for every
/// row of its tool.
fn reconcile_scope(&self) -> Option<String> {
None
}
}
/// Parse a session through an adapter and normalize any structured tool parts.
/// Callers that consume adapter output should use this rather than `parse`
/// directly so indexing and live readers share identical tool summaries.
pub fn parse_session(adapter: &dyn Adapter, path: &Path) -> Result<Session> {
let mut session = adapter.parse(path)?;
crate::tool_summary::fold_tool_parts(&mut session);
Ok(session)
}
/// Parse one key from a shared-store adapter and apply the same normalization
/// as the ordinary file-backed path.
pub fn parse_session_key(adapter: &dyn Adapter, key: &str) -> Result<Session> {
let mut session = adapter.parse_key(key)?;
crate::tool_summary::fold_tool_parts(&mut session);
Ok(session)
}
/// The [`Adapter::reconcile_scope`] for an adapter pinned to `root`: every key
/// under that directory, as a path prefix.
pub(crate) fn root_scope(root: Option<&Path>) -> Option<String> {
let root = root?;
let mut prefix = root.to_string_lossy().into_owned();
if !prefix.ends_with(std::path::MAIN_SEPARATOR) {
prefix.push(std::path::MAIN_SEPARATOR);
}
Some(prefix)
}
pub fn all() -> Vec<Box<dyn Adapter>> {
vec![
Box::new(ClaudeCode::default()),
Box::new(Codex::default()),
Box::new(Codex::archived()),
Box::new(CodexHistory::default()),
Box::new(gemini::Gemini),
Box::new(Antigravity::ide()),
Box::new(Antigravity::cli()),
Box::new(opencode::OpenCode::default()),
Box::new(Muse::default()),
Box::new(KimiCode::default()),
Box::new(cline::Cline),
Box::new(cline::RooCode),
Box::new(cline::KiloCode),
Box::new(gajae::GajaeCode),
Box::new(continue_dev::Continue),
Box::new(gptme::Gptme),
Box::new(aider::Aider::default()),
Box::new(prodex::Prodex),
Box::new(GrokBuild::default()),
]
}
pub fn by_name(name: &str) -> Option<Box<dyn Adapter>> {
all().into_iter().find(|a| a.name() == name)
}
/// Every registered store of one tool. Codex has three: its rollouts, its
/// archived rollouts and its thread history; [`by_name`] returns the first.
pub fn named(name: &str) -> Vec<Box<dyn Adapter>> {
all().into_iter().filter(|a| a.name() == name).collect()
}
/// Filesystem-only summary of a store, used by `scan`. No parsing involved.
pub fn report(adapter: &dyn Adapter) -> Option<StoreReport> {
let root = adapter.root()?;
// Shared store (e.g. SQLite): presence comes from the store itself (the db
// can live outside `root` via OPENCODE_DB), so this is checked before the
// root-exists gate. Size is the backing files, count is the sessions, and
// the time span comes from the per-session change-tokens.
if let Some(store) = adapter.store() {
if store.keys.is_empty() {
return None; // present but no sessions yet - not worth a scan row
}
let bytes = store
.files
.iter()
.filter_map(|f| f.metadata().ok())
.map(|m| m.len())
.sum();
// Prefer explicit activity dates. Legacy stores encode milliseconds
// in their tokens; zero means an unknown date.
let activity_times: Vec<_> = store
.keys
.iter()
.filter_map(|(key, token)| {
adapter.modified_at(key).or_else(|| {
if *token > 0 {
DateTime::from_timestamp_millis(*token)
} else {
None
}
})
})
.collect();
let oldest = activity_times.iter().min().copied();
let newest = activity_times.iter().max().copied();
return Some(StoreReport {
tool: adapter.name(),
root,
files: store.keys.len(),
bytes,
oldest,
newest,
});
}
if !root.exists() {
return None;
}
let files = adapter.discover().files;
let mut bytes: u64 = 0;
let mut oldest: Option<DateTime<Utc>> = None;
let mut newest: Option<DateTime<Utc>> = None;
let mut count = 0usize;
for f in &files {
let Ok(meta) = f.metadata() else { continue };
count += 1;
bytes += meta.len();
if let Ok(modified) = meta.modified() {
let t: DateTime<Utc> = modified.into();
if oldest.is_none_or(|o| t < o) {
oldest = Some(t);
}
if newest.is_none_or(|n| t > n) {
newest = Some(t);
}
}
}
if count == 0 {
return None; // root exists but holds no session files
}
Some(StoreReport {
tool: adapter.name(),
root,
files: count,
bytes,
oldest,
newest,
})
}
/// Shared helper: pick a session title from messages when the tool does not
/// store one. First user message that is not harness boilerplate wins.
pub(crate) fn title_from_messages(messages: &[crate::model::Message]) -> String {
messages
.iter()
.find(|m| {
m.role == crate::model::Role::User
&& !m.text.trim_start().starts_with('<')
&& !m.text.trim().is_empty()
})
.map(|m| redacted_truncate(&m.text, 80))
.unwrap_or_else(|| "(no user prompt)".into())
}
/// Redact the complete logical value before bounding a derived field. The
/// order matters: truncating first can leave a credential prefix too short for
/// the redactor to recognize.
pub(crate) fn redacted_truncate(text: &str, max: usize) -> String {
crate::util::truncate(&crate::redact::redact(text), max)
}
const MAX_TOOL_OUTPUT_BYTES: usize = 8 * 1024;
/// Redact a complete tool result, then cap it without splitting a UTF-8 code
/// point. Redacting before truncation keeps credential detection intact.
pub(crate) fn bounded_redacted_output(text: &str) -> String {
let redacted = crate::redact::redact(text);
let mut end = redacted.len().min(MAX_TOOL_OUTPUT_BYTES);
while !redacted.is_char_boundary(end) {
end -= 1;
}
redacted[..end].to_owned()
}
/// First-line title variant for adapters whose existing format uses a hard
/// character cap without an ellipsis. Redaction happens before line selection
/// so a multi-line credential is considered as one logical value.
pub(crate) fn redacted_first_line(text: &str, max: usize) -> String {
let redacted = crate::redact::redact(text);
redacted
.lines()
.next()
.unwrap_or("")
.chars()
.take(max)
.collect()
}
pub(crate) fn parse_ts(s: &str) -> Option<DateTime<Utc>> {
DateTime::parse_from_rfc3339(s)
.ok()
.map(|t| t.with_timezone(&Utc))
}
/// Path hygiene shared by `touched` and `edits`: trim, and reject the shapes
/// that are not a real edited path (empty, embedded newline, absurdly long).
/// Returns the cleaned path or None to drop it, so the two provenance layers
/// apply IDENTICAL rules and never diverge.
pub(crate) fn clean_path(p: &str) -> Option<String> {
let p = p.trim();
(!p.is_empty() && !p.contains('\n') && p.len() <= 4096).then(|| p.to_string())
}
/// Tidy the list of files a session touched: `clean_path` each, then de-duplicate
/// while preserving first-seen order. A session edits the same file many times;
/// the link cares only that it did.
pub(crate) fn dedup_paths(paths: Vec<String>) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
paths
.into_iter()
.filter_map(|p| clean_path(&p))
.filter(|p| seen.insert(p.clone()))
.collect()
}