From f376b6cf66b6ed9cc6cb8034dfdfe80a1222f4ca Mon Sep 17 00:00:00 2001 From: Dev Dalia Date: Sat, 26 Sep 2026 16:51:01 +0530 Subject: [PATCH 1/2] Keep deleted sessions searchable, read-only Claude Code deletes transcripts after 30 days by default, and agsearch dropped its index for a session the moment the file went. The session you come back to for how something was decided is usually older than that, so the one search that mattered found nothing. When a transcript disappears, its indexed text is now kept for 180 days. Only what was said is kept: user and assistant messages, each cut to 2,000 characters. Tool output is two thirds of the index and every search reads the whole index, so keeping it would slow search down month after month. Automation runs are not kept at all. Kept sessions are marked `expired` in the list and in `-n`. They cannot be resumed, so Enter opens them in the pager instead, `read` says what the copy is missing, and ctrl-y copies the read command. A transcript that comes back replaces its copy. --- CHANGELOG.md | 9 +++ README.md | 10 ++- agsearch | 161 +++++++++++++++++++++++++++++++++++++++--- tests/test_expired.py | 138 ++++++++++++++++++++++++++++++++++++ 4 files changed, 305 insertions(+), 13 deletions(-) create mode 100644 tests/test_expired.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e005bd3..78f6753 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ migration in the same line. ## [Unreleased] +### Added + +- **Sessions whose transcript was deleted stay searchable.** Claude Code deletes transcripts + after 30 days by default, and agsearch used to drop a session from its index the moment + the file went. It now keeps what it had indexed for 180 days: your messages and the agent's + replies, each cut to 2,000 characters, with no tool output and no automation runs. The + rows are marked `expired`, Enter and `agsearch read` open them read-only, and ctrl-y copies + the read command, since there is nothing left to resume. + ### Fixed - **`agsearch read` no longer crashes on superscript digits.** A message containing `¹` or diff --git a/README.md b/README.md index 8a9a524..4e9e6cf 100644 --- a/README.md +++ b/README.md @@ -232,8 +232,13 @@ Its cache lives under `~/.cache/agsearch/`. Transcript parsing and ranking happe only changed files are reparsed. > [!IMPORTANT] -> Claude Code deletes transcripts after 30 days by default. To keep a longer searchable history, -> set `cleanupPeriodDays` in `~/.claude/settings.json`: +> Claude Code deletes transcripts after 30 days by default. When a transcript disappears, +> agsearch keeps what it had indexed for 180 days: your messages and the agent's replies, each +> cut to 2,000 characters, without tool output. Those sessions are marked `expired`. They are +> still searchable and readable, and Enter opens them to read, but they cannot be resumed. +> +> To keep sessions resumable for longer, raise `cleanupPeriodDays` in `~/.claude/settings.json` +> (heavy daily use writes about 700 MB of transcripts a month): > > ```json > { "cleanupPeriodDays": 365 } @@ -248,6 +253,7 @@ only changed files are reparsed. - Sessions from deleted worktrees resume from the nearest existing parent directory. - Recently active sessions are marked `●` and require confirmation before reattaching. - Forked Claude Code sessions are marked `fork`, and name the branch they split from. +- Sessions whose transcript was deleted are marked `expired` and open read-only. ## Development diff --git a/agsearch b/agsearch index 7a3966e..6f610b2 100755 --- a/agsearch +++ b/agsearch @@ -54,6 +54,7 @@ import json import shlex import time import shutil +import datetime import hashlib import subprocess @@ -71,6 +72,8 @@ SESSIONS_PATH = os.path.join(CACHE_DIR, "sessions.tsv") # one line per session SUBMAP_PATH = os.path.join(CACHE_DIR, "submap.json") # parent-sid -> [subagent file paths] INDEX_PATH = os.path.join(CACHE_DIR, "index.json") # sid -> {source, path} for preview/resume FORKS_PATH = os.path.join(CACHE_DIR, "forks.json") # forked sid -> {of, at} +EXPIRED_DIR = os.path.join(CACHE_DIR, "expired") # saved text of deleted transcripts +EXPIRED_PATH = os.path.join(CACHE_DIR, "expired.json") # fragment name -> {source, since} CACHE_FMT = 7 # bump when the TSV column layout / keying changes, to invalidate old fragments @@ -107,6 +110,15 @@ W_BODY = 1.0 # surface it. 4,000 recovers that; 20,000 measured no better and costs more to scan. MSG_INDEX_CHARS = 4_000 +# Claude Code deletes transcripts after 30 days by default, and the session you want back to +# learn how something was decided is usually older than that. So when a transcript disappears +# its indexed text is kept, readable and searchable but no longer resumable. Only what someone +# said is kept: tool output is two thirds of the index and not what anyone comes back for, and +# every search reads the whole index, so what is kept has to stay small and has to end. +EXPIRED_KEEP_DAYS = 180 +EXPIRED_MSG_CHARS = 2_000 +EXPIRED_ROLES = ("user", "assistant") + RECENCY_HALFLIFE_DAYS = 45.0 RECENCY_W = 0.35 # max multiplier bump for a session from today USAGE_W = 0.30 # max multiplier bump for a session you resume often @@ -777,6 +789,96 @@ def _frag_path(jsonl_path): return os.path.join(FRAG_DIR, key + ".tsv") +def _slim_expired(frag_lines, live_sids): + """The part of a deleted transcript worth keeping: what you and the agent said, each + message cut to EXPIRED_MSG_CHARS, kind rewritten to "expired". Automation runs are dropped + whole, and so are rows of a session that is still live (a subagent file removed from under + a parent that is not).""" + out = [] + for l in frag_lines: + f = (l.split(SEP) + [""] * 9)[:9] + if f[4] not in EXPIRED_ROLES or f[8] == "auto" or f[0] in live_sids: + continue + f[7] = f[7][:EXPIRED_MSG_CHARS] + f[8] = "expired" + out.append(SEP.join(f)) + return out + + +def _keep_expired(gone, live_frags, index, old_index, today=None): + """Save the text of transcripts that disappeared since the last run, drop what has been + kept longer than EXPIRED_KEEP_DAYS, and return the kept rows. Registers each kept session + in `index` with an `expired` date so preview, read and Enter know not to resume it. + + A transcript that comes back (restored from a backup) is live again and its copy goes. + """ + today = today or datetime.date.today() + os.makedirs(EXPIRED_DIR, exist_ok=True) + try: + kept = json.load(open(EXPIRED_PATH)) + except (OSError, json.JSONDecodeError): + kept = {} + + for path in gone: + fn = os.path.basename(_frag_path(path)) + src = os.path.join(FRAG_DIR, fn) + if fn in kept or not os.path.exists(src): + continue + with open(src, errors="replace") as fh: + frag_lines = fh.read().splitlines() + slim = _slim_expired(frag_lines, index) + if not slim: + continue + sid0 = slim[0].split(SEP, 1)[0] + source = (old_index.get(sid0) or {}).get("source") or DEFAULT_SOURCE + with open(os.path.join(EXPIRED_DIR, fn), "w") as fh: + fh.write("\n".join(slim)) + kept[fn] = {"source": source, "since": today.isoformat()} + + cutoff = (today - datetime.timedelta(days=EXPIRED_KEEP_DAYS)).isoformat() + live = set(index) + lines = [] + for fn in list(kept): + dst = os.path.join(EXPIRED_DIR, fn) + if fn in live_frags or kept[fn]["since"] < cutoff or not os.path.exists(dst): + kept.pop(fn) + try: + os.remove(dst) + except OSError: + pass + continue + with open(dst, errors="replace") as fh: + rows = [l for l in fh.read().splitlines() if l.split(SEP, 1)[0] not in live] + for sid in dict.fromkeys(l.split(SEP, 1)[0] for l in rows): + entry = index.setdefault(sid, {"source": kept[fn]["source"], "path": "", + "expired": kept[fn]["since"], "frags": []}) + entry["frags"].append(fn) + lines.extend(rows) + + json.dump(kept, open(EXPIRED_PATH, "w")) + return lines + + +def _expired_rows(info): + """Saved rows of an expired session, as the 9-field lists a parser returns.""" + rows = [] + for fn in info.get("frags", []): + try: + with open(os.path.join(EXPIRED_DIR, fn), errors="replace") as fh: + rows += [(l.split(SEP) + [""] * 9)[:9] for l in fh.read().splitlines()] + except OSError: + continue + return rows + + +def _expired_since(sid): + """The date `sid`'s transcript was found deleted, or "" if it is still on disk.""" + try: + return json.load(open(INDEX_PATH)).get(sid, {}).get("expired", "") + except (OSError, json.JSONDecodeError): + return "" + + # A cold build over ~1,200 sessions takes several seconds. Silence for that long # reads as "hung" and is the cheapest bounce in the product, so we narrate it — # but only when there is real work and someone watching. Warm runs re-parse a @@ -852,11 +954,16 @@ def build_index(include_thinking=False, force=False): old_index = json.load(open(INDEX_PATH)) except (OSError, json.JSONDecodeError): old_index = {} - if os.path.exists(META_PATH) and not force: - try: - meta = json.load(open(META_PATH)) - except (OSError, json.JSONDecodeError): - meta = {} + try: + meta = json.load(open(META_PATH)) + except (OSError, json.JSONDecodeError): + meta = {} + # Every file the last run indexed, read before a forced rebuild throws the cache away: + # the ones that have since disappeared are the transcripts whose text gets kept. + known_paths = [p for p in meta if not p.startswith("_")] + known_paths += [v["path"] for v in old_index.values() if v.get("path")] + if force: + meta = {} if meta.get("_thinking") != include_thinking or meta.get("_fmt") != CACHE_FMT: force = True # thinking toggle or format change invalidates fragments meta = {} @@ -926,6 +1033,9 @@ def build_index(include_thinking=False, force=False): root = (old_index.get(sid0) or {}).get("root") index[sid0]["root"] = root or _root_uuid(path) + gone = {p for p in known_paths if p not in mtimes and not os.path.exists(p)} + lines.extend(_keep_expired(gone, live_frags, index, old_index)) + for fn in os.listdir(FRAG_DIR): # drop fragments for deleted sessions if fn not in live_frags: try: @@ -1017,14 +1127,15 @@ def _match_entry(f, matched, total, texts, keys, idlen=36, pad=True): spaces costs it a token. """ tag = "auto" if f[C_KIND] == "auto" else _agent_name(f[C_SOURCE]) + title = ("expired " if f[C_KIND] == "expired" else "") + f[C_TITLE][:60] badge = f"{matched}/{total}" if total else "" proj = short_proj(f[C_CWD])[:20] if pad: head = (f"{f[C_SID]} {f[C_DATE]} {tag:<{SOURCE_COL}} {badge:<4} " - f"\033[36m{proj:<20}\033[0m {f[C_TITLE][:60]}") + f"\033[36m{proj:<20}\033[0m {title}") else: head = (f"{f[C_SID][:idlen]} {f[C_DATE]} {tag} {badge} " - f"\033[36m{proj}\033[0m {f[C_TITLE][:60]}") + f"\033[36m{proj}\033[0m {title}") idx = best_matching(texts, keys)[0] if (keys and texts) else () # Matched on the title alone (or no query at all): show what the session opened with. body = texts[idx[0]] if idx else f[C_FIRST] @@ -1378,6 +1489,9 @@ def load_session_rows(sid, thinking=False, limit=MSG_INDEX_CHARS): index = {} info = index.get(sid, {}) source = info.get("source", "cc") + if info.get("expired"): # the transcript is gone; what agsearch kept is all there is + rows = sorted(_expired_rows(info), key=lambda r: r[3]) + return source, [(r, False) for r in rows] path = info.get("path") or _session_path(sid) # Only some harnesses write separate subagent transcripts; the rest are a single file. @@ -1437,6 +1551,13 @@ def _elide(blocks, budget, matched=()): return [blocks[i] for i in sorted(keep)], n - len(keep) +def expired_note(since): + """What a reader of an expired session needs to know before trusting what they read.""" + return (f"The transcript file was deleted (noticed {since}). This is agsearch's saved copy: " + f"your messages and the agent's replies, each cut to {EXPIRED_MSG_CHARS:,} " + f"characters, no tool output. It cannot be resumed.") + + def render_transcript(sid, thinking="0", query="", color=None, budget=None): """The whole conversation, readable, without resuming it. @@ -1460,10 +1581,13 @@ def render_transcript(sid, thinking="0", query="", color=None, budget=None): r0 = rows[0] title = r0[6] or next((r[7] for r, _ in tagged if r[4] == "user"), "") or "(untitled)" n_sub = sum(1 for _, sub in tagged if sub) + since = _expired_since(sid) + how = (f"\033[33m{expired_note(since)}\033[0m\n" if since + else f"\033[2m{resume_line(sid, r0[1])}\033[0m\n") out = [fork_mark(sid) + f"\033[1m{title[:80]}\033[0m", f"\033[2m{short_proj(r0[1])} · {r0[3][:10]} · {len(rows)} msgs" + (f" · {n_sub} subagent" if n_sub else "") + fork_line(sid) + "\033[0m", - f"\033[2m{resume_line(sid, r0[1])}\033[0m\n"] + how] blocks, matched = [], [] for r, sub in tagged: @@ -1508,6 +1632,8 @@ def render_preview(sid, thinking, query): disp_title = r0[6] or next((r[7] for r, _ in tagged if r[4] == "user"), "") or "(untitled)" print(fork_mark(sid) + f"\033[1m{disp_title[:80]}\033[0m") gone = " · orig dir gone" if r0[1] and not os.path.isdir(r0[1]) else "" + if _expired_since(sid): + gone = " · expired, read only" print(f"\033[2m{short_proj(r0[1])} · {r0[3][:10]} · {len(rows)} msgs" + (f" · {n_sub} subagent" if n_sub else "") + gone + fork_line(sid) + "\033[0m") @@ -1780,6 +1906,8 @@ _GONE_MARK = " \033[2morig dir gone\033[0m" # it costs nothing on the other 99% of rows, and every title starts in the same column, so the # marks still line up to be scanned. A word, not a glyph: ⑂ and ⋔ are unreadable at 14px. _FORK_MARK = "\033[2mfork\033[0m " +# Same place and weight as the fork mark: it says, before Enter, that this row opens to read. +_EXPIRED_MARK = "\033[2mexpired\033[0m " def _active_sids(sids): @@ -1820,8 +1948,8 @@ def _row(sid, cwd, date, source, kind, title, badge, active=False, dir_gone=Fals forked=False): mark = _AUTO_MARK if kind == "auto" else _SRC_MARK.get(source, " " * SOURCE_COL) live = _LIVE_MARK if active else " " - forkm = _FORK_MARK if forked else "" - tail = _GONE_MARK if dir_gone else "" + forkm = (_EXPIRED_MARK if kind == "expired" else "") + (_FORK_MARK if forked else "") + tail = _GONE_MARK if dir_gone and kind != "expired" else "" # only matters to resume body = (f"{date} {mark} \033[36m{short_proj(cwd)[:15]:<15}\033[0m " f"{badge} {live}{forkm}{title[:64]}{tail}") if kind == "auto": @@ -2088,6 +2216,16 @@ def run_fzf(lines, query, thinking=False, no_resume=False, fuzzy=False): return 0 f = (sel.split(SEP) + [""] * 4)[:4] sid, cwd, active = f[0], f[1], f[3] == "1" + if _expired_since(sid): # nothing to resume; open what was kept instead + if no_resume: + print(f"agsearch read {sid}") + else: + reader = subprocess.Popen([sys.executable, self, "_transcript", sid, thi, typed], + stdout=subprocess.PIPE) + subprocess.run(shlex.split(pager), stdin=reader.stdout) + reader.stdout.close() + reader.wait() + return 0 if no_resume: _source, _bin, argv, _cwd, target, _exists = resume_plan(sid, cwd) print(resume_command(target or cwd, argv)) @@ -2128,7 +2266,8 @@ def main(argv): sid = argv[1] if len(argv) > 1 else "" cwd = argv[2] if len(argv) > 2 else "" if sid: - copy_to_clipboard(resume_line(sid, cwd)) + copy_to_clipboard(f"agsearch read {sid}" if _expired_since(sid) + else resume_line(sid, cwd)) return 0 no_fzf = no_resume = here = thinking = reindex = fuzzy = False diff --git a/tests/test_expired.py b/tests/test_expired.py new file mode 100644 index 0000000..e92c8d5 --- /dev/null +++ b/tests/test_expired.py @@ -0,0 +1,138 @@ +"""Expired sessions: the transcript is deleted, the text agsearch indexed is kept. + +Claude Code deletes transcripts after 30 days by default, and until now agsearch dropped its +index for a session the moment the file went. The cases that matter: the kept copy is small +(no tool output, no automation, capped messages), it is searchable and readable but never +resumed, it ends after EXPIRED_KEEP_DAYS, and a transcript that comes back replaces it. +""" + +import datetime +import io +import json +import os +import re +import tempfile +import unittest +from contextlib import redirect_stdout + +from load_agsearch import load_agsearch + +strip = lambda s: re.sub(r"\x1b\[[0-9;]*m", "", s) + + +def write_session(d, sid, turns, entrypoint="cli"): + """A Claude transcript. `turns` is [(role, text)]; role "tool" is a tool result.""" + path = os.path.join(d, sid + ".jsonl") + with open(path, "w") as fh: + for i, (role, text) in enumerate(turns): + if role == "tool": + content = [{"type": "tool_result", "content": text}] + role = "user" + else: + content = text + fh.write(json.dumps({ + "type": role, "sessionId": sid, "cwd": "/repo", "entrypoint": entrypoint, + "timestamp": "2026-08-01T10:%02d:00Z" % i, + "message": {"role": role, "content": content}, + }) + "\n") + return path + + +class ExpiredTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + root = self.tmp.name + self.projects = os.path.join(root, "projects") + os.makedirs(self.projects) + cache = os.path.join(root, "cache") + ag = self.ag = load_agsearch() + ag.CACHE_DIR = cache + ag.FRAG_DIR = os.path.join(cache, "frag") + ag.META_PATH = os.path.join(cache, "meta.json") + ag.SESSIONS_PATH = os.path.join(cache, "sessions.tsv") + ag.SUBMAP_PATH = os.path.join(cache, "submap.json") + ag.INDEX_PATH = os.path.join(cache, "index.json") + ag.FORKS_PATH = os.path.join(cache, "forks.json") + ag.EXPIRED_DIR = os.path.join(cache, "expired") + ag.EXPIRED_PATH = os.path.join(cache, "expired.json") + ag.PROJECTS_DIR = self.projects + for name, rec in ag.SOURCES.items(): + rec["roots"] = [self.projects] if name == "cc" else [] + + def tearDown(self): + self.tmp.cleanup() + + def index(self): + return json.load(open(self.ag.INDEX_PATH)) + + def expire(self, sid, turns, **kw): + """Index a session, then delete its transcript and index again.""" + path = write_session(self.projects, sid, turns, **kw) + self.ag.build_index() + os.remove(path) + return self.ag.build_index() + + def test_deleted_transcript_stays_searchable(self): + lines = self.expire("s1", [("user", "webhook retry backoff?"), + ("assistant", "decided: exponential backoff")]) + rows = self.ag.build_sessions(lines) + self.assertEqual([f[self.ag.C_SID] for f in rows], ["s1"]) + self.assertEqual(rows[0][self.ag.C_KIND], "expired") + hits = self.ag.rank_sessions(rows, self.ag.parse_query("exponential backoff")) + self.assertEqual(hits[0][2][self.ag.C_SID], "s1") + self.assertEqual(self.index()["s1"]["expired"], datetime.date.today().isoformat()) + + def test_kept_copy_drops_tool_output_and_caps_messages(self): + lines = self.expire("s1", [("user", "hi"), ("tool", "huge tool dump"), + ("assistant", "x" * 10_000)]) + roles = [l.split(self.ag.SEP)[4] for l in lines] + self.assertEqual(roles, ["user", "assistant"]) + self.assertEqual(len(lines[1].split(self.ag.SEP)[7]), self.ag.EXPIRED_MSG_CHARS) + + def test_automation_runs_are_not_kept(self): + lines = self.expire("s1", [("user", "review this diff")], entrypoint="sdk-py") + self.assertEqual(lines, []) + self.assertNotIn("s1", self.index()) + + def test_read_shows_kept_text_and_says_it_cannot_resume(self): + self.expire("s1", [("user", "webhook retry"), ("assistant", "use backoff")]) + buf = io.StringIO() + with redirect_stdout(buf): + self.assertEqual(self.ag.render_transcript("s1", color=False), 0) + out = strip(buf.getvalue()) + self.assertIn("use backoff", out) + self.assertIn("cannot be resumed", out) + self.assertNotIn("--resume", out) + + def test_row_is_tagged_expired(self): + lines = self.expire("s1", [("user", "webhook retry")]) + f = self.ag.build_sessions(lines)[0] + row = self.ag._row(f[0], f[1], f[2], f[3], f[4], f[5], " ") + self.assertIn("expired webhook retry", strip(row)) + + def test_kept_copy_ends_after_keep_days(self): + self.expire("s1", [("user", "webhook retry")]) + later = datetime.date.today() + datetime.timedelta(days=self.ag.EXPIRED_KEEP_DAYS + 1) + lines = self.ag._keep_expired(set(), set(), {}, {}, today=later) + self.assertEqual(lines, []) + self.assertEqual(os.listdir(self.ag.EXPIRED_DIR), []) + + def test_restored_transcript_replaces_kept_copy(self): + turns = [("user", "webhook retry"), ("tool", "tool text")] + self.expire("s1", turns) + write_session(self.projects, "s1", turns) + lines = self.ag.build_index() + self.assertNotIn("expired", self.index()["s1"]) + self.assertEqual(len(lines), 2) # the live copy only, tool row included + self.assertEqual(os.listdir(self.ag.EXPIRED_DIR), []) + + def test_forced_rebuild_still_notices_the_deletion(self): + path = write_session(self.projects, "s1", [("user", "webhook retry")]) + self.ag.build_index() + os.remove(path) + self.ag.build_index(force=True) + self.assertIn("expired", self.index()["s1"]) + + +if __name__ == "__main__": + unittest.main() From 7f327cbf8715e1b82a1f57bf216b35a845be2343 Mon Sep 17 00:00:00 2001 From: Dev Dalia Date: Sat, 26 Sep 2026 17:38:28 +0530 Subject: [PATCH 2/2] Address review: subagent labels, layout version, pager Subagent turns in a kept copy were shown as the main thread, because the copy did not record that it came from an agent-*.jsonl file. It does now. Kept copies outlive the cache, so they carry their own layout version and a copy in an older layout is dropped rather than split wrongly. Fragments left over from an older CACHE_FMT are not saved at all, since their layout is unknown. Enter on an expired row ran $PAGER without a shell, so a pager that is not a bare binary, or a missing one, raised a traceback. It now goes through the shell like ctrl-o does. Only the pager string does; the session id and query are still passed as arguments. --- agsearch | 37 +++++++++++++++++++++++++------------ tests/test_expired.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/agsearch b/agsearch index 6f610b2..79fc4c7 100755 --- a/agsearch +++ b/agsearch @@ -118,6 +118,10 @@ MSG_INDEX_CHARS = 4_000 EXPIRED_KEEP_DAYS = 180 EXPIRED_MSG_CHARS = 2_000 EXPIRED_ROLES = ("user", "assistant") +# Kept copies outlive the cache, so they carry their own layout version rather than CACHE_FMT, +# which also bumps for parsing changes that leave the 9-field row alone. Bump this only when +# the row layout changes; copies in an older layout are then dropped rather than misread. +EXPIRED_FMT = 1 RECENCY_HALFLIFE_DAYS = 45.0 RECENCY_W = 0.35 # max multiplier bump for a session from today @@ -805,12 +809,14 @@ def _slim_expired(frag_lines, live_sids): return out -def _keep_expired(gone, live_frags, index, old_index, today=None): +def _keep_expired(gone, live_frags, index, old_index, frags_current=True, today=None): """Save the text of transcripts that disappeared since the last run, drop what has been kept longer than EXPIRED_KEEP_DAYS, and return the kept rows. Registers each kept session in `index` with an `expired` date so preview, read and Enter know not to resume it. A transcript that comes back (restored from a backup) is live again and its copy goes. + `frags_current` is False when the fragments on disk predate a CACHE_FMT change: their + layout is then unknown, so nothing is saved from them. """ today = today or datetime.date.today() os.makedirs(EXPIRED_DIR, exist_ok=True) @@ -822,7 +828,7 @@ def _keep_expired(gone, live_frags, index, old_index, today=None): for path in gone: fn = os.path.basename(_frag_path(path)) src = os.path.join(FRAG_DIR, fn) - if fn in kept or not os.path.exists(src): + if not frags_current or fn in kept or not os.path.exists(src): continue with open(src, errors="replace") as fh: frag_lines = fh.read().splitlines() @@ -833,14 +839,18 @@ def _keep_expired(gone, live_frags, index, old_index, today=None): source = (old_index.get(sid0) or {}).get("source") or DEFAULT_SOURCE with open(os.path.join(EXPIRED_DIR, fn), "w") as fh: fh.write("\n".join(slim)) - kept[fn] = {"source": source, "since": today.isoformat()} + kept[fn] = {"source": source, "since": today.isoformat(), "fmt": EXPIRED_FMT, + # a subagent's copy, so read can label its turns as the subagent's + "sub": _source(source)["subagents"] + and os.path.basename(path).startswith("agent-")} cutoff = (today - datetime.timedelta(days=EXPIRED_KEEP_DAYS)).isoformat() live = set(index) lines = [] for fn in list(kept): dst = os.path.join(EXPIRED_DIR, fn) - if fn in live_frags or kept[fn]["since"] < cutoff or not os.path.exists(dst): + if (fn in live_frags or kept[fn]["since"] < cutoff or not os.path.exists(dst) + or kept[fn].get("fmt") != EXPIRED_FMT): kept.pop(fn) try: os.remove(dst) @@ -852,7 +862,7 @@ def _keep_expired(gone, live_frags, index, old_index, today=None): for sid in dict.fromkeys(l.split(SEP, 1)[0] for l in rows): entry = index.setdefault(sid, {"source": kept[fn]["source"], "path": "", "expired": kept[fn]["since"], "frags": []}) - entry["frags"].append(fn) + entry["frags"].append([fn, bool(kept[fn].get("sub"))]) lines.extend(rows) json.dump(kept, open(EXPIRED_PATH, "w")) @@ -860,12 +870,12 @@ def _keep_expired(gone, live_frags, index, old_index, today=None): def _expired_rows(info): - """Saved rows of an expired session, as the 9-field lists a parser returns.""" + """Saved rows of an expired session as (9-field row, is_subagent), like load_session_rows.""" rows = [] - for fn in info.get("frags", []): + for fn, sub in info.get("frags", []): try: with open(os.path.join(EXPIRED_DIR, fn), errors="replace") as fh: - rows += [(l.split(SEP) + [""] * 9)[:9] for l in fh.read().splitlines()] + rows += [((l.split(SEP) + [""] * 9)[:9], sub) for l in fh.read().splitlines()] except OSError: continue return rows @@ -962,6 +972,7 @@ def build_index(include_thinking=False, force=False): # the ones that have since disappeared are the transcripts whose text gets kept. known_paths = [p for p in meta if not p.startswith("_")] known_paths += [v["path"] for v in old_index.values() if v.get("path")] + frags_current = meta.get("_fmt") == CACHE_FMT if force: meta = {} if meta.get("_thinking") != include_thinking or meta.get("_fmt") != CACHE_FMT: @@ -1034,7 +1045,7 @@ def build_index(include_thinking=False, force=False): index[sid0]["root"] = root or _root_uuid(path) gone = {p for p in known_paths if p not in mtimes and not os.path.exists(p)} - lines.extend(_keep_expired(gone, live_frags, index, old_index)) + lines.extend(_keep_expired(gone, live_frags, index, old_index, frags_current)) for fn in os.listdir(FRAG_DIR): # drop fragments for deleted sessions if fn not in live_frags: @@ -1490,8 +1501,7 @@ def load_session_rows(sid, thinking=False, limit=MSG_INDEX_CHARS): info = index.get(sid, {}) source = info.get("source", "cc") if info.get("expired"): # the transcript is gone; what agsearch kept is all there is - rows = sorted(_expired_rows(info), key=lambda r: r[3]) - return source, [(r, False) for r in rows] + return source, sorted(_expired_rows(info), key=lambda x: x[0][3]) path = info.get("path") or _session_path(sid) # Only some harnesses write separate subagent transcripts; the rest are a single file. @@ -2220,9 +2230,12 @@ def run_fzf(lines, query, thinking=False, no_resume=False, fuzzy=False): if no_resume: print(f"agsearch read {sid}") else: + # $PAGER is a shell command by convention (git runs it with sh -c too), and ctrl-o + # hands it to a shell through fzf, so Enter does the same. Only the pager goes to + # the shell; the session id and query are passed as arguments. reader = subprocess.Popen([sys.executable, self, "_transcript", sid, thi, typed], stdout=subprocess.PIPE) - subprocess.run(shlex.split(pager), stdin=reader.stdout) + subprocess.run(pager, shell=True, stdin=reader.stdout) reader.stdout.close() reader.wait() return 0 diff --git a/tests/test_expired.py b/tests/test_expired.py index e92c8d5..8d136df 100644 --- a/tests/test_expired.py +++ b/tests/test_expired.py @@ -126,6 +126,39 @@ def test_restored_transcript_replaces_kept_copy(self): self.assertEqual(len(lines), 2) # the live copy only, tool row included self.assertEqual(os.listdir(self.ag.EXPIRED_DIR), []) + def test_subagent_turns_stay_labelled_as_subagent(self): + write_session(self.projects, "s1", [("user", "main prompt")]) + sub = os.path.join(self.projects, "agent-x1.jsonl") + with open(sub, "w") as fh: + fh.write(json.dumps({"type": "user", "sessionId": "s1", "cwd": "/repo", + "timestamp": "2026-08-01T11:00:00Z", + "message": {"role": "user", "content": "subagent task"}})) + self.ag.build_index() + os.remove(sub) + os.remove(os.path.join(self.projects, "s1.jsonl")) + self.ag.build_index() + _source, tagged = self.ag.load_session_rows("s1") + self.assertEqual([(r[7], s) for r, s in tagged], + [("main prompt", False), ("subagent task", True)]) + + def test_copy_in_an_old_layout_is_dropped_not_misread(self): + self.expire("s1", [("user", "webhook retry")]) + kept = json.load(open(self.ag.EXPIRED_PATH)) + for v in kept.values(): + v["fmt"] = self.ag.EXPIRED_FMT - 1 + json.dump(kept, open(self.ag.EXPIRED_PATH, "w")) + self.assertEqual(self.ag.build_index(), []) + self.assertNotIn("s1", self.index()) + + def test_fragments_from_an_older_cache_format_are_not_saved(self): + path = write_session(self.projects, "s1", [("user", "webhook retry")]) + self.ag.build_index() + meta = json.load(open(self.ag.META_PATH)) + meta["_fmt"] = self.ag.CACHE_FMT - 1 + json.dump(meta, open(self.ag.META_PATH, "w")) + os.remove(path) + self.assertEqual(self.ag.build_index(), []) + def test_forced_rebuild_still_notices_the_deletion(self): path = write_session(self.projects, "s1", [("user", "webhook retry")]) self.ag.build_index()