Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed
- **`context.md` describes the session being saved, even with parallel sessions.**
Several Claude Code sessions often run in one project folder. Three fixes:
- **The summary comes from the session's own transcript**, not the cumulative
`history.md`, which mixed older sessions' work into the one being saved.
- **Each session logs to its own file**, `.recall/history/<id8>.md`. All
sessions used to append to one `history.md`, so their turns interleaved and no
slice of it was reliably one session. The id is sanitised to 8 safe
characters and cannot name a path outside `history/`.
- **`/recall:save` saves its own session.** It took the newest `.jsonl` in the
project's transcript dir, i.e. whichever parallel session wrote last. It now
uses `CLAUDE_CODE_SESSION_ID`; a known id with no transcript returns nothing
rather than a guess, and without an id it falls back to the newest file as
before. Each save also writes `.recall/context/<id8>.md`, so a parallel
session's save cannot overwrite it; `context.md` stays the latest save.
- **Goal skips image-only messages.** A session that opened with a pasted
screenshot got a temp-file path (`[Image: source: …png]`) as its Goal.
- The session-slice test moved from `scripts/` to `tests/` (bandit flagged its
asserts, and it did not run under pytest).

## [0.4.0] - 2026-07-18

### Added
Expand Down
9 changes: 7 additions & 2 deletions scripts/capture.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env python3
"""Stop / SessionEnd hook: append new session activity to .recall/history.md.
"""Stop / SessionEnd hook: append new session activity to .recall/history/<id8>.md
(one file per session - parallel sessions in one folder used to interleave in a
single history.md).

history.md is the append-only running log of everything done. We track how many
transcript lines we've already captured per session (in .recall/.capture.json)
Expand Down Expand Up @@ -85,7 +87,10 @@ def capture_session(data):
complete.decode("utf-8", "replace").splitlines())
if events:
ensure_output_dir(cwd, cfg)
hist = history_path(cwd, cfg)
hist = history_path(cwd, cfg, session_id) # this session's own file
if not hist:
return
os.makedirs(os.path.dirname(hist), exist_ok=True)
prefix = ""
if not os.path.exists(hist):
prefix += f"# Recall History — {project_name(cwd)}\n"
Expand Down
47 changes: 44 additions & 3 deletions scripts/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,32 @@ def context_path(cwd, cfg):
return _in_output_dir(cwd, cfg, "context.md")


def history_path(cwd, cfg):
def history_path(cwd, cfg, session_id=None):
"""With a session id: that session's OWN log, .recall/history/<id8>.md.

Several sessions often run in one project folder at once. When they all
appended to one history.md, each session's turns landed inside another
session's block and no summary of it was reliably one session. A file per
session is per-session by construction. Without an id: the legacy shared file.
"""
sid = _short_sid(session_id)
if sid:
return _in_output_dir(cwd, cfg, os.path.join("history", sid + ".md"))
return _in_output_dir(cwd, cfg, "history.md")


def session_context_path(cwd, cfg, session_id):
"""This session's own saved context, .recall/context/<id8>.md, so a later save
by a parallel session never overwrites it. context.md stays the latest save."""
sid = _short_sid(session_id)
return _in_output_dir(cwd, cfg, os.path.join("context", sid + ".md")) if sid else None


def _short_sid(session_id):
"""First 8 safe chars of a session id; never a path separator or '..'."""
return re.sub(r"[^0-9A-Za-z-]", "", str(session_id or ""))[:8]


def state_path(cwd, cfg):
return _in_output_dir(cwd, cfg, ".capture.json")

Expand Down Expand Up @@ -230,11 +252,30 @@ def _candidates(cwd):
return out


def locate_transcript(cwd):
"""Find the current session transcript when a hook didn't provide one."""
def locate_transcript(cwd, session_id=None):
"""Find the current session transcript when a hook didn't provide one.

Claude Code puts CLAUDE_CODE_SESSION_ID in every tool call's environment, so
/recall:save can name ITS OWN transcript. Taking the newest .jsonl instead
picked whichever parallel session in the folder wrote last, and saved that
session's goal and state under this one (2026-09-24). The id is globally
unique, so matching it exactly in any project dir cannot pick the wrong one.
Known id but no file -> None, never a guess. No id -> newest, as before.
"""
projects = Path.home() / ".claude" / "projects"
if not projects.is_dir():
return None
raw = session_id or os.environ.get("CLAUDE_CODE_SESSION_ID") or ""
sid = re.sub(r"[^0-9A-Za-z-]", "", str(raw))
if sid:
for name in _candidates(cwd):
hit = projects / name / (sid + ".jsonl")
if hit.is_file():
return str(hit)
try:
return next((str(p) for p in projects.glob("*/" + sid + ".jsonl")), None)
except OSError:
return None
for name in _candidates(cwd):
cand = projects / name
if cand.is_dir():
Expand Down
66 changes: 60 additions & 6 deletions scripts/make_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
project_name,
project_transcripts,
read_text,
session_context_path,
write_text,
)
from config import load_config # noqa: E402
Expand Down Expand Up @@ -130,18 +131,67 @@ def _facts_events(cwd, transcript_path, located_events):
return located_events


# history.md accumulates EVERY session for the project under "## Session <id> — <when>"
# headers. Summarizing all of it made context.md describe the project's whole past
# instead of the session being saved: Goal, Files and Commands came from this
# transcript while Summary and Next steps came from unrelated older threads, which
# reads as this session's state and is not. On a long-lived project that is dozens
# of sessions and tens of thousands of lines of drift.
_SESSION_HEADER = re.compile(r"^## Session ([0-9a-f]+) .*$", re.MULTILINE)


def _sid_of(transcript_path):
return os.path.basename(transcript_path or "").split(".")[0]


def _session_slice(history_text, transcript_path):
"""The current session's portion of history.md.

Matched on the transcript's id, so the right block is used even if a parallel
session has appended after it. Falls back to the LAST block when this session
is not in the file yet (capture lags the save), and to the whole text when
there are no session headers at all — one session's worth either way.
"""
heads = list(_SESSION_HEADER.finditer(history_text))
if not heads:
return history_text
sid = os.path.basename(transcript_path or "").split(".")[0]
if sid:
for h in heads:
if sid.startswith(h.group(1)):
return history_text[h.end():]
return history_text[heads[-1].end():]


def build(cwd, cfg, transcript_path, events=None):
"""events=None is the Claude Code path (parse the .jsonl transcript);
a harness adapter passes pre-parsed events instead."""
if events is None:
located = parse_transcript.parse(transcript_path)
events = _facts_events(cwd, transcript_path, located)

# Summarize the captured history if present (it's what the user expects to be
# condensed); otherwise summarize the transcript prose directly.
history_text = read_text(history_path(cwd, cfg))
corpus = _clean_for_summary(history_text) if history_text else \
parse_transcript.prose(events, cfg["max_input_chars"])
# Summarize THIS SESSION'S OWN TRANSCRIPT.
#
# history.md used to be preferred here, on the reasoning that the captured
# history is what the user expects condensed. It is shared mutable state: when
# several sessions run in one project folder at once they all append to the one
# file, and a session that has not written its own header lands inside another
# session's block. So neither the whole file nor a per-header slice of it is
# reliably THIS session, and the summary drifted into unrelated work while Goal
# and Files stayed correct — the worst of both, because it reads as current
# state.
#
# The transcript is per-session by construction. history.md stays as the
# fallback for a transcript that yields no prose, sliced to one block.
corpus = parse_transcript.prose(events, cfg["max_input_chars"])
if not corpus.strip():
own = read_text(history_path(cwd, cfg, _sid_of(transcript_path)))
if own:
corpus = _clean_for_summary(own)
else: # a session captured before per-session logs existed
history_text = read_text(history_path(cwd, cfg))
if history_text:
corpus = _clean_for_summary(_session_slice(history_text, transcript_path))
corpus = corpus[-cfg["max_input_chars"]:]
summary = summarizer.summarize(corpus, cfg["summary_sentences"])

Expand Down Expand Up @@ -211,9 +261,13 @@ def run(cwd, transcript_path=None, quiet=False, harness="claude"):
return 1
path = context_path(cwd, cfg)
write_text(path, md)
own = session_context_path(cwd, cfg, _sid_of(transcript_path))
if own:
os.makedirs(os.path.dirname(own), exist_ok=True)
write_text(own, md)

if not quiet:
print(f"Recall: wrote {path}")
print(f"Recall: wrote {path}" + (f" (and {own})" if own else ""))
print(f"Recall: summarizer = {summarizer.backend_name()}")
return 0

Expand Down
12 changes: 11 additions & 1 deletion scripts/parse_transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import json
import re

_TOOL_ARG = {
"Edit": "file_path",
Expand Down Expand Up @@ -158,10 +159,19 @@ def commands(events):
return out


# A pasted screenshot reaches the transcript as "[Image: source: C:\...png]". A
# message that is ONLY that says nothing about the goal - it made Goal a temp-file
# path whenever a session opened with a screenshot.
_IMAGE_REF = re.compile(r"\[Image\b[^\]]*\]")


def first_user_goal(events):
"""First user message with real text; image placeholders are dropped."""
for ev in events:
if ev["role"] == "user" and ev["text"]:
return " ".join(ev["text"].split())
text = " ".join(_IMAGE_REF.sub(" ", ev["text"]).split())
if text:
return text
return ""


Expand Down
4 changes: 3 additions & 1 deletion scripts/session_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ def main():

if cfg.get("capture_history", True) and not paused:
lines.append(
f"- This session is being logged locally to `{out_dir}/history.md`. "
"- This session is being logged locally to "
f"`{out_dir}/history/{(data.get('session_id') or 'session')[:8]}.md` "
"(one file per session). "
"Ask the user if they'd like to keep logging this session; if not, "
f"create the file `{out_dir}/.capture-paused` to pause it."
)
Expand Down
33 changes: 32 additions & 1 deletion tests/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@


def _history(cwd):
return common.read_text(common.history_path(cwd, load_config(cwd)))
"""Every per-session log in this (single-test) project, concatenated."""
d = os.path.join(common.output_dir(cwd, load_config(cwd)), "history")
if not os.path.isdir(d):
return ""
return "".join(common.read_text(os.path.join(d, f)) for f in sorted(os.listdir(d)))


def test_incremental_capture_dedupes_header_and_redacts(tmp_path):
Expand Down Expand Up @@ -83,3 +87,30 @@ def test_corrupt_offset_state_does_not_crash_capture(tmp_path):
make_jsonl(t, [user("recover cleanly"), assistant("ok")])
run_capture(cwd, t, "sessGGGG7777")
assert "recover cleanly" in _history(cwd)


def test_parallel_sessions_log_to_separate_files(tmp_path):
# Two sessions in one project folder, turns interleaved: each must land in
# its own file and never in the other one (they shared history.md before).
cwd = str(tmp_path)
ta = os.path.join(cwd, "aaaa1111-x.jsonl")
tb = os.path.join(cwd, "bbbb2222-y.jsonl")
make_jsonl(ta, [user("session A builds the invoice report")])
run_capture(cwd, ta, "aaaa1111-x")
make_jsonl(tb, [user("session B fixes the payroll import")])
run_capture(cwd, tb, "bbbb2222-y")
make_jsonl(ta, [user("session A builds the invoice report"), assistant("A adds totals")])
run_capture(cwd, ta, "aaaa1111-x")
cfg = load_config(cwd)
a = common.read_text(common.history_path(cwd, cfg, "aaaa1111-x"))
b = common.read_text(common.history_path(cwd, cfg, "bbbb2222-y"))
assert "invoice report" in a and "A adds totals" in a and "payroll" not in a
assert "payroll import" in b and "invoice" not in b
assert a.count("## Session") == 1
assert not os.path.exists(common.history_path(cwd, cfg)), "shared history.md was written"


def test_session_id_cannot_escape_history_dir(tmp_path):
cwd = str(tmp_path)
p = common.history_path(cwd, load_config(cwd), "../../etc/passwd")
assert os.path.dirname(p).endswith("history") and ".." not in os.path.basename(p)
11 changes: 11 additions & 0 deletions tests/test_parse_transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,14 @@ def test_tool_event_tolerates_non_dict_input():
assert ev["tool"] == "Bash"
assert ev["detail"] == ""
assert ev["files"] == []


def test_goal_skips_image_only_messages():
img = r"[Image: source: C:\Users\x\AppData\Local\Temp\claude\s\images\1.png]"

def ev(t):
return {"role": "user", "text": t}

assert p.first_user_goal([ev(img), ev("draft a reply to Derek")]) == "draft a reply to Derek"
assert p.first_user_goal([ev(img + "\n\nwhy is this late?")]) == "why is this late?"
assert p.first_user_goal([ev(img), ev(img)]) == ""
23 changes: 23 additions & 0 deletions tests/test_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,26 @@ def git(*args):
info = common.git_info(cwd) # runs git diff/log internally
assert not marker.exists(), "malicious diff.external was executed"
assert "git diff --stat" in info # still produced real output


def test_locate_transcript_prefers_own_session_over_newest(tmp_path, monkeypatch):
# /recall:save used to take the NEWEST transcript in the project dir, i.e.
# whichever parallel session wrote last. With the session id known it must
# return that session's own file even when a peer's is newer.
import time
home = tmp_path / "home"
cwd = str(tmp_path / "proj")
tdir = home / ".claude" / "projects" / "p" # short: Windows MAX_PATH
monkeypatch.setattr(common, "_candidates", lambda c: ["p"])
tdir.mkdir(parents=True)
mine = tdir / "11111111-mine.jsonl"
mine.write_text("{}")
time.sleep(0.05)
(tdir / "22222222-peer.jsonl").write_text("{}") # newer
monkeypatch.setattr(common.Path, "home", classmethod(lambda cls: home))
monkeypatch.setenv("CLAUDE_CODE_SESSION_ID", "11111111-mine")
assert common.locate_transcript(cwd) == str(mine)
monkeypatch.setenv("CLAUDE_CODE_SESSION_ID", "99999999-missing")
assert common.locate_transcript(cwd) is None, "a known id with no file must not guess"
monkeypatch.delenv("CLAUDE_CODE_SESSION_ID")
assert common.locate_transcript(cwd).endswith("22222222-peer.jsonl"), "no id: newest, as before"
2 changes: 1 addition & 1 deletion tests/test_session_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_session_end_captures_but_does_not_autosave_by_default(tmp_path):
t = _transcript(cwd)
run_session_end(cwd, t, "sessFFFF6666")
cfg = load_config(cwd)
assert os.path.exists(common.history_path(cwd, cfg)) # history captured
assert os.path.exists(common.history_path(cwd, cfg, "sessFFFF6666")) # history captured
assert not os.path.exists(common.context_path(cwd, cfg)) # but no auto-save


Expand Down
45 changes: 45 additions & 0 deletions tests/test_session_slice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""The legacy shared history.md is sliced to ONE session's block.

Only the fallback path reads it now (sessions log to history/<id8>.md), but a
project captured before that change still has the shared file, and summarizing all
of it mixed unrelated older sessions into the one being saved.
"""

from make_context import _session_slice

HISTORY = """# Recall History - Example Project

## Session aaaaaaaa - 2026-09-15 10:00
**You:** rename the widget
**Claude:** OLD_SESSION_MARKER renamed it.

## Session bbbbbbbb - 2026-09-22 15:39
**You:** add a column to the report
**Claude:** NEW_SESSION_MARKER shipped it.
"""


def test_named_session_wins():
got = _session_slice(HISTORY, "/x/y/bbbbbbbb-1234-5678.jsonl")
assert "NEW_SESSION_MARKER" in got
assert "OLD_SESSION_MARKER" not in got


def test_unknown_id_falls_back_to_last_block():
got = _session_slice(HISTORY, "/x/y/cccccccc-0000.jsonl")
assert "NEW_SESSION_MARKER" in got
assert "OLD_SESSION_MARKER" not in got


def test_earlier_session_still_reachable():
# A parallel session appending after this one must not steal the slice.
assert "OLD_SESSION_MARKER" in _session_slice(HISTORY, "/x/y/aaaaaaaa-9999.jsonl")


def test_history_without_headers_passes_through():
text = "just prose, no headers"
assert _session_slice(text, "/x/y/bbbbbbbb.jsonl") == text


def test_missing_transcript_path_still_scopes():
assert "OLD_SESSION_MARKER" not in _session_slice(HISTORY, "")