-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathdelete.rs
More file actions
702 lines (601 loc) · 25.6 KB
/
Copy pathdelete.rs
File metadata and controls
702 lines (601 loc) · 25.6 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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::fs;
use std::io;
use std::path::Path;
use walkdir::WalkDir;
use crate::config;
use crate::model::{Agent, Session};
/// Delete a session's data files. Returns Ok(()) on success.
/// Only removes session data, NOT the project directory.
pub fn delete_session(session: &Session) -> Result<(), io::Error> {
// Defense in depth: never accept a session_id that could escape the intended
// directory via path traversal. Agent scanners should already sanitize IDs.
debug_assert!(
!session.session_id.contains('/') && !session.session_id.contains(".."),
"session_id must not contain path separators or parent traversal",
);
match session.agent {
Agent::ClaudeCode => delete_claude_session(session),
Agent::Codex => delete_codex_session(session),
Agent::OpenCode => delete_opencode_session(session),
Agent::Pi => delete_pi_session(session),
Agent::OhMyPi => delete_oh_my_pi_session(session),
Agent::Kiro => delete_kiro_session(session),
Agent::CursorAgent => delete_cursor_agent_session(session),
Agent::Gemini => delete_gemini_session(session),
Agent::Hermes => delete_hermes_session(session),
Agent::Yolop => delete_yolop_session(session),
}
}
fn delete_yolop_session(session: &Session) -> Result<(), io::Error> {
let sessions_dir = config::yolop_sessions_dir().map_err(io::Error::other)?;
delete_yolop_session_from(&sessions_dir, &session.session_id)
}
fn delete_yolop_session_from(sessions_dir: &Path, session_id: &str) -> Result<(), io::Error> {
let session_dir = sessions_dir.join(session_id);
if session_dir.is_dir() {
fs::remove_dir_all(session_dir)?;
}
let legacy_log = sessions_dir.join(format!("{session_id}.jsonl"));
if legacy_log.is_file() {
fs::remove_file(legacy_log)?;
}
Ok(())
}
// ---------------------------------------------------------------------------
// Shared JSONL helpers
// ---------------------------------------------------------------------------
/// Rewrite a JSONL file, excluding all lines where `json_key` matches `value`.
fn rewrite_jsonl_excluding(path: &Path, json_key: &str, value: &str) -> Result<(), io::Error> {
let content = fs::read_to_string(path)?;
let mut kept_lines: Vec<&str> = Vec::new();
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if line_has_field_value(trimmed, json_key, value) {
continue;
}
kept_lines.push(line);
}
let new_content = if kept_lines.is_empty() {
String::new()
} else {
let mut out = kept_lines.join("\n");
out.push('\n');
out
};
fs::write(path, new_content)
}
/// Check if a JSON line contains `"key": "value"`.
fn line_has_field_value(line: &str, key: &str, value: &str) -> bool {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(line)
&& let Some(v) = parsed.get(key).and_then(|v| v.as_str())
{
return v == value;
}
false
}
// ---------------------------------------------------------------------------
// Claude Code
// ---------------------------------------------------------------------------
/// Claude sessions are stored as lines in `~/.claude/history.jsonl`.
/// We rewrite the file excluding all lines whose `sessionId` matches.
/// We also remove any project-specific session data under
/// `~/.claude/projects/<project>/sessions/<sessionId>/`.
fn delete_claude_session(session: &Session) -> Result<(), io::Error> {
let claude_dir = config::claude_dir().map_err(io::Error::other)?;
let history_path = claude_dir.join("history.jsonl");
if history_path.exists() {
rewrite_jsonl_excluding(&history_path, "sessionId", &session.session_id)?;
}
let projects_dir = claude_dir.join("projects");
if projects_dir.exists() {
remove_dirs_matching_name(&projects_dir, &session.session_id)?;
}
Ok(())
}
/// Walk a directory tree and remove any subdirectory whose name matches the target.
fn remove_dirs_matching_name(base: &Path, name: &str) -> Result<(), io::Error> {
if !base.is_dir() {
return Ok(());
}
for entry in WalkDir::new(base).into_iter().flatten() {
let path = entry.path();
if path.is_dir() && path.file_name().and_then(|n| n.to_str()) == Some(name) {
fs::remove_dir_all(path)?;
}
}
Ok(())
}
/// Walk a directory tree and remove any regular file whose name (including
/// extension) matches the target.
fn remove_files_matching_name(base: &Path, name: &str) -> Result<(), io::Error> {
if !base.is_dir() {
return Ok(());
}
for entry in WalkDir::new(base).into_iter().flatten() {
let path = entry.path();
if path.is_file() && path.file_name().and_then(|n| n.to_str()) == Some(name) {
fs::remove_file(path)?;
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Codex
// ---------------------------------------------------------------------------
/// Codex session data lives in three places (any combination may be present
/// depending on Codex CLI version):
/// * `state_*.sqlite` `threads` row (primary source for current Codex CLI),
/// * `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` rollout file,
/// * `~/.codex/history.jsonl` per-prompt summary entries.
///
/// We delete from all three so the session does not reappear after the next
/// `agf` scan via the SQLite path.
fn delete_codex_session(session: &Session) -> Result<(), io::Error> {
let codex_dir = config::codex_dir().map_err(io::Error::other)?;
// 1. Delete the SQLite row(s). Codex may have multiple `state_*.sqlite`
// files (e.g. across CLI upgrades); remove the row from every one
// that contains it so the session cannot be revived from a stale db.
delete_codex_sqlite_rows(&codex_dir, &session.session_id)?;
// 2. Find and delete the session rollout file
let sessions_dir = codex_dir.join("sessions");
if sessions_dir.exists() {
delete_codex_session_file(&sessions_dir, &session.session_id)?;
}
// 3. Rewrite history.jsonl excluding lines with matching session_id
let history_path = codex_dir.join("history.jsonl");
if history_path.exists() {
rewrite_jsonl_excluding(&history_path, "session_id", &session.session_id)?;
}
Ok(())
}
/// Remove the `threads` row matching `session_id` from every
/// `state_*.sqlite` in `codex_dir`. Missing tables / open errors on a single
/// file are swallowed so one corrupt or older-schema db cannot block the
/// delete on the others.
fn delete_codex_sqlite_rows(codex_dir: &Path, session_id: &str) -> Result<(), io::Error> {
let Ok(entries) = fs::read_dir(codex_dir) else {
return Ok(());
};
for entry in entries.flatten() {
let path = entry.path();
let is_state_db = path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("state_") && n.ends_with(".sqlite"));
if !is_state_db {
continue;
}
let Ok(conn) = rusqlite::Connection::open(&path) else {
continue;
};
// `threads` is the only table the Codex scanner reads from. Older
// Codex CLI versions may not have this table — ignore the error.
let _ = conn.execute("DELETE FROM threads WHERE id = ?1", [session_id]);
}
Ok(())
}
/// Find and delete the Codex rollout JSONL file matching the given session ID.
fn delete_codex_session_file(sessions_dir: &Path, session_id: &str) -> Result<(), io::Error> {
for entry in WalkDir::new(sessions_dir).into_iter().flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
continue;
}
let Ok(content) = fs::read_to_string(path) else {
continue;
};
let first_line = match content.lines().next() {
Some(line) if !line.trim().is_empty() => line.trim(),
_ => continue,
};
if let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) {
let payload_id = value
.get("payload")
.and_then(|p| p.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("");
if payload_id == session_id {
fs::remove_file(path)?;
return Ok(());
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// OpenCode
// ---------------------------------------------------------------------------
/// OpenCode sessions are stored in a SQLite database at
/// `~/.local/share/opencode/opencode.db`.
fn delete_opencode_session(session: &Session) -> Result<(), io::Error> {
let opencode_dir = config::opencode_data_dir().map_err(io::Error::other)?;
let db_path = opencode_dir.join("opencode.db");
if !db_path.exists() {
return Ok(());
}
let conn = rusqlite::Connection::open(&db_path)
.map_err(|e| io::Error::other(format!("SQLite open error: {e}")))?;
conn.execute("DELETE FROM session WHERE id = ?1", [&session.session_id])
.map_err(|e| io::Error::other(format!("SQLite delete error: {e}")))?;
// Also remove JSON storage mirror if it exists
let session_storage = opencode_dir.join("storage/session");
if session_storage.exists() {
for entry in WalkDir::new(&session_storage).into_iter().flatten() {
let path = entry.path();
if path.is_file()
&& path.file_stem().and_then(|n| n.to_str()) == Some(&session.session_id)
{
let _ = fs::remove_file(path);
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Pi
// ---------------------------------------------------------------------------
/// Pi sessions are stored as JSONL files under
/// `~/.pi/agent/sessions/<encoded-cwd>/<timestamp>_<sessionId>.jsonl`.
fn delete_pi_session(session: &Session) -> Result<(), io::Error> {
let sessions_dir = config::pi_sessions_dir().map_err(io::Error::other)?;
delete_pi_style_session(session, &sessions_dir)
}
/// Oh My Pi uses the same JSONL session format as pi under
/// `~/.omp/agent/sessions/<encoded-cwd>/<timestamp>_<sessionId>.jsonl`.
fn delete_oh_my_pi_session(session: &Session) -> Result<(), io::Error> {
let sessions_dir = config::oh_my_pi_sessions_dir().map_err(io::Error::other)?;
delete_pi_style_session(session, &sessions_dir)
}
fn delete_pi_style_session(session: &Session, sessions_dir: &Path) -> Result<(), io::Error> {
if !sessions_dir.exists() {
return Ok(());
}
for entry in WalkDir::new(sessions_dir).into_iter().flatten() {
let path = entry.path();
if !path.is_file() || path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
continue;
}
let Ok(content) = fs::read_to_string(path) else {
continue;
};
let matches = content
.lines()
.filter(|line| !line.trim().is_empty())
.any(|line| {
serde_json::from_str::<serde_json::Value>(line)
.ok()
.is_some_and(|value| {
value.get("type").and_then(|v| v.as_str()) == Some("session")
&& value.get("id").and_then(|v| v.as_str()) == Some(&session.session_id)
})
});
if matches {
fs::remove_file(path)?;
return Ok(());
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Kiro
// ---------------------------------------------------------------------------
/// Kiro sessions are stored in a SQLite database at
/// `~/Library/Application Support/kiro-cli/data.sqlite3` (macOS) or
/// `~/.local/share/kiro-cli/data.sqlite3` (Linux).
fn delete_kiro_session(session: &Session) -> Result<(), io::Error> {
let data_dir = config::kiro_data_dir().map_err(io::Error::other)?;
let db_path = data_dir.join("data.sqlite3");
if !db_path.exists() {
return Ok(());
}
let conn = rusqlite::Connection::open(&db_path)
.map_err(|e| io::Error::other(format!("SQLite open error: {e}")))?;
conn.execute(
"DELETE FROM conversations_v2 WHERE conversation_id = ?1",
[&session.session_id],
)
.map_err(|e| io::Error::other(format!("SQLite delete error: {e}")))?;
Ok(())
}
// ---------------------------------------------------------------------------
// Cursor Agent
// ---------------------------------------------------------------------------
/// Cursor Agent sessions are stored across two layouts:
/// - Current (Composer 2+) JSONL: directory at
/// `~/.cursor/projects/*/agent-transcripts/<session_id>/` containing
/// `<session_id>.jsonl`, plus chat metadata under
/// `~/.cursor/chats/<workspace-hash>/<session_id>/store.db`.
/// - Legacy: file at `~/.cursor/projects/*/agent-transcripts/<session_id>.txt`
/// with no `chats/` counterpart.
///
/// Both shapes are still surfaced by the scanner (see `scan_from`), so delete
/// must remove the directory AND the file form — otherwise legacy sessions
/// silently no-op (`remove_dirs_matching_name` filters on `is_dir()`) and the
/// next scan resurrects the orphan.
fn delete_cursor_agent_session(session: &Session) -> Result<(), io::Error> {
let cursor_dir = config::cursor_dir().map_err(io::Error::other)?;
// 1. Chat metadata: ~/.cursor/chats/*/<session_id>/
let chats_dir = cursor_dir.join("chats");
if chats_dir.exists() {
remove_dirs_matching_name(&chats_dir, &session.session_id)?;
}
// 2. Transcript: directory form (JSONL) and file form (legacy .txt).
let projects_dir = cursor_dir.join("projects");
if projects_dir.exists() {
remove_dirs_matching_name(&projects_dir, &session.session_id)?;
let legacy_txt = format!("{}.txt", session.session_id);
remove_files_matching_name(&projects_dir, &legacy_txt)?;
}
Ok(())
}
// ---------------------------------------------------------------------------
// Gemini
// ---------------------------------------------------------------------------
/// Gemini sessions are stored as JSON files under
/// `~/.gemini/tmp/<project-name-or-hash>/chats/session-<date>-<short-id>.json`.
fn delete_gemini_session(session: &Session) -> Result<(), io::Error> {
let gemini_dir = config::gemini_dir().map_err(io::Error::other)?;
let tmp_dir = gemini_dir.join("tmp");
if !tmp_dir.exists() {
return Ok(());
}
for project_entry in fs::read_dir(&tmp_dir)?.flatten() {
let chats_dir = project_entry.path().join("chats");
if !chats_dir.is_dir() {
continue;
}
for chat_entry in fs::read_dir(&chats_dir)?.flatten() {
let path = chat_entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Ok(content) = fs::read_to_string(&path) else {
continue;
};
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
&& json
.get("sessionId")
.and_then(|v| v.as_str())
.is_some_and(|id| id == session.session_id)
{
fs::remove_file(&path)?;
return Ok(());
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Hermes
// ---------------------------------------------------------------------------
/// Hermes Agent sessions are stored in a SQLite database at
/// `~/.hermes/state.db`. Messages are in a separate `messages` table
/// with a foreign key to `sessions.id`. The four DELETEs are wrapped in
/// a single transaction so a mid-cascade failure can't leave the DB in
/// an inconsistent state (e.g. orphan messages whose sessions row is
/// gone, which would surface as ghost rows on the next scan).
fn delete_hermes_session(session: &Session) -> Result<(), io::Error> {
let hermes_dir = config::hermes_dir().map_err(io::Error::other)?;
let db_path = hermes_dir.join("state.db");
if !db_path.exists() {
return Ok(());
}
let mut conn = rusqlite::Connection::open(&db_path)
.map_err(|e| io::Error::other(format!("SQLite open error: {e}")))?;
let tx = conn
.transaction()
.map_err(|e| io::Error::other(format!("SQLite begin tx error: {e}")))?;
// Delete messages first (foreign key constraint).
tx.execute(
"DELETE FROM messages WHERE session_id = ?1",
[&session.session_id],
)
.map_err(|e| io::Error::other(format!("SQLite delete messages error: {e}")))?;
// Delete child sessions' messages and then the child sessions themselves.
tx.execute(
"DELETE FROM messages WHERE session_id IN \
(SELECT id FROM sessions WHERE parent_session_id = ?1)",
[&session.session_id],
)
.map_err(|e| io::Error::other(format!("SQLite delete child messages error: {e}")))?;
tx.execute(
"DELETE FROM sessions WHERE parent_session_id = ?1",
[&session.session_id],
)
.map_err(|e| io::Error::other(format!("SQLite delete child sessions error: {e}")))?;
// Delete the parent session.
tx.execute("DELETE FROM sessions WHERE id = ?1", [&session.session_id])
.map_err(|e| io::Error::other(format!("SQLite delete session error: {e}")))?;
tx.commit()
.map_err(|e| io::Error::other(format!("SQLite commit error: {e}")))?;
// Also remove any on-disk session JSON dumps. These are best-effort:
// a failure here doesn't undo the DB delete (which is the source of
// truth for the listing), so we swallow the error.
let sessions_dir = hermes_dir.join("sessions");
if sessions_dir.exists() {
let prefix = format!("session_{}", session.session_id);
if let Ok(entries) = fs::read_dir(&sessions_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str()
&& name.starts_with(&prefix)
&& name.ends_with(".json")
{
let _ = fs::remove_file(entry.path());
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn make_codex_dir(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(name);
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
/// Create a minimal `state_*.sqlite` mirroring the Codex schema fields
/// the scanner reads, then seed two `threads` rows.
fn seed_state_db(path: &Path, ids: &[&str]) {
let conn = rusqlite::Connection::open(path).unwrap();
conn.execute_batch(
"CREATE TABLE threads (
id TEXT PRIMARY KEY,
cwd TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
git_branch TEXT,
first_user_message TEXT NOT NULL DEFAULT ''
);",
)
.unwrap();
for id in ids {
conn.execute("INSERT INTO threads (id, cwd) VALUES (?1, '/tmp/x')", [id])
.unwrap();
}
}
fn count_thread(path: &Path, id: &str) -> i64 {
let conn = rusqlite::Connection::open(path).unwrap();
conn.query_row("SELECT COUNT(*) FROM threads WHERE id = ?1", [id], |row| {
row.get(0)
})
.unwrap()
}
#[test]
fn delete_codex_sqlite_rows_removes_target_only() {
let dir = make_codex_dir("agf-test-codex-delete-target");
let db = dir.join("state_5.sqlite");
seed_state_db(&db, &["target-id", "keep-id"]);
delete_codex_sqlite_rows(&dir, "target-id").unwrap();
assert_eq!(count_thread(&db, "target-id"), 0);
assert_eq!(count_thread(&db, "keep-id"), 1);
}
#[test]
fn delete_codex_sqlite_rows_walks_every_state_db() {
let dir = make_codex_dir("agf-test-codex-delete-multi");
let db4 = dir.join("state_4.sqlite");
let db5 = dir.join("state_5.sqlite");
seed_state_db(&db4, &["dup-id"]);
seed_state_db(&db5, &["dup-id"]);
delete_codex_sqlite_rows(&dir, "dup-id").unwrap();
assert_eq!(count_thread(&db4, "dup-id"), 0);
assert_eq!(count_thread(&db5, "dup-id"), 0);
}
#[test]
fn delete_codex_sqlite_rows_ignores_non_state_files() {
let dir = make_codex_dir("agf-test-codex-delete-ignore");
// A non-matching file must not crash the walk.
fs::write(dir.join("history.jsonl"), b"").unwrap();
let db = dir.join("state_1.sqlite");
seed_state_db(&db, &["a"]);
delete_codex_sqlite_rows(&dir, "a").unwrap();
assert_eq!(count_thread(&db, "a"), 0);
}
#[test]
fn delete_codex_sqlite_rows_tolerates_missing_threads_table() {
let dir = make_codex_dir("agf-test-codex-delete-missing-table");
let db = dir.join("state_0.sqlite");
// Empty db (no `threads` table) — Codex versions without the table
// must not abort the delete.
rusqlite::Connection::open(&db).unwrap();
// Should swallow the "no such table: threads" error.
delete_codex_sqlite_rows(&dir, "anything").unwrap();
}
#[test]
fn delete_cursor_agent_removes_transcript_dir_not_sibling() {
let base = make_codex_dir("agf-test-cursor-delete");
let transcripts = base.join("projects/encproj/agent-transcripts");
let target_uuid = "ddddddddddddddddddddddddddddddd1";
let sibling_uuid = "ddddddddddddddddddddddddddddddd2";
let target_dir = transcripts.join(target_uuid);
let sibling_dir = transcripts.join(sibling_uuid);
fs::create_dir_all(&target_dir).unwrap();
fs::create_dir_all(&sibling_dir).unwrap();
fs::write(target_dir.join(format!("{target_uuid}.jsonl")), b"{}").unwrap();
fs::write(sibling_dir.join(format!("{sibling_uuid}.jsonl")), b"{}").unwrap();
let projects_dir = base.join("projects");
remove_dirs_matching_name(&projects_dir, target_uuid).unwrap();
assert!(!target_dir.exists(), "target session dir should be deleted");
assert!(sibling_dir.exists(), "sibling session dir must survive");
}
/// Regression: legacy Cursor sessions live as plain files at
/// `projects/<slug>/agent-transcripts/<uuid>.txt`, not as directories.
/// `remove_dirs_matching_name` filters on `is_dir()`, so the dir-only
/// pass added in #45 left these files behind and the next scan
/// resurrected the orphan. Delete must remove both shapes.
#[test]
fn delete_cursor_agent_removes_legacy_txt_transcript() {
let base = make_codex_dir("agf-test-cursor-legacy-txt");
let transcripts = base.join("projects/encproj/agent-transcripts");
fs::create_dir_all(&transcripts).unwrap();
let target_uuid = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1";
let sibling_uuid = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee2";
let target_file = transcripts.join(format!("{target_uuid}.txt"));
let sibling_file = transcripts.join(format!("{sibling_uuid}.txt"));
fs::write(&target_file, b"legacy transcript").unwrap();
fs::write(&sibling_file, b"legacy transcript").unwrap();
let projects_dir = base.join("projects");
remove_files_matching_name(&projects_dir, &format!("{target_uuid}.txt")).unwrap();
assert!(
!target_file.exists(),
"legacy .txt transcript should be deleted",
);
assert!(
sibling_file.exists(),
"unrelated sibling legacy .txt must survive",
);
}
#[test]
fn delete_yolop_session_removes_only_target_folder_and_legacy_log() {
let base = make_codex_dir("agf-test-yolop-delete");
let target = "session_019e3db018a17450aba5407af5777237";
let sibling = "session_019f4fec10e370b2be16cca7debb6ab1";
fs::create_dir(base.join(target)).unwrap();
fs::create_dir(base.join(sibling)).unwrap();
fs::write(base.join(format!("{target}.jsonl")), b"{}").unwrap();
delete_yolop_session_from(&base, target).unwrap();
assert!(!base.join(target).exists());
assert!(!base.join(format!("{target}.jsonl")).exists());
assert!(base.join(sibling).exists());
}
#[test]
fn delete_pi_style_session_accepts_oh_my_pi_title_slot() {
let root = make_codex_dir("agf-test-omp-delete");
let target = root.join("target.jsonl");
let sibling = root.join("sibling.jsonl");
fs::write(
&target,
concat!(
"{\"type\":\"title\",\"title\":\"Target\"}\n",
"{\"type\":\"session\",\"id\":\"target-id\",\"cwd\":\"/tmp/x\"}\n"
),
)
.unwrap();
fs::write(
&sibling,
"{\"type\":\"session\",\"id\":\"sibling-id\",\"cwd\":\"/tmp/x\"}\n",
)
.unwrap();
let session = Session {
agent: Agent::OhMyPi,
session_id: "target-id".to_string(),
project_name: "x".to_string(),
project_path: "/tmp/x".to_string(),
summaries: Vec::new(),
timestamp: 0,
git_branch: None,
worktree: None,
recap: None,
};
delete_pi_style_session(&session, &root).unwrap();
assert!(!target.exists());
assert!(sibling.exists());
let _ = fs::remove_dir_all(root);
}
}