diff options
| author | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 22:45:27 -0300 |
|---|---|---|
| committer | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 22:45:27 -0300 |
| commit | f546a8a1578bef9fbc144580b84f51e3e90480b1 (patch) | |
| tree | 5ef61bcbc9729878ced017429a7d21a644c82060 | |
| parent | 5fc59b6936b2d4a05f5f5192458145d0112431d3 (diff) | |
| download | claude-logbook-f546a8a1578bef9fbc144580b84f51e3e90480b1.tar.gz claude-logbook-f546a8a1578bef9fbc144580b84f51e3e90480b1.zip | |
Show branches with their inherited history and mark directory changes
| -rw-r--r-- | README.es.md | 16 | ||||
| -rw-r--r-- | README.md | 16 | ||||
| -rw-r--r-- | claude_logbook/__init__.py | 2 | ||||
| -rw-r--r-- | claude_logbook/sessions.py | 67 | ||||
| -rw-r--r-- | claude_logbook/template.html | 44 | ||||
| -rw-r--r-- | claude_logbook/terminal.py | 24 | ||||
| -rw-r--r-- | server/render.go | 31 | ||||
| -rw-r--r-- | server/server_test.go | 20 | ||||
| -rw-r--r-- | tests/test_sessions.py | 63 | ||||
| -rw-r--r-- | tests/test_terminal.py | 12 |
10 files changed, 260 insertions, 35 deletions
diff --git a/README.es.md b/README.es.md index 710a3e7..fe976a0 100644 --- a/README.es.md +++ b/README.es.md @@ -304,6 +304,14 @@ Algunos detalles que conviene saber: - **Compactación.** Cuando se acaba el contexto (o con `/compact`) Claude Code reemplaza la conversación anterior por un resumen. Ese resumen se muestra como una marca "context compacted here", no como un mensaje tuyo, y no se cuenta. +- **Ramas.** `/branch` (y `/fork`) arrancan una sesión nueva que copia el + historial de la original. claude-logbook toma esa copia como heredada: se + muestra colapsada bajo "Inherited history", y solo lo que vino después cuenta + para los mensajes, la duración y la fecha de inicio. En la tabla la sesión + lleva un chip `branch`. +- **Cambios de directorio.** Cuando la sesión pasa a otro directorio (un `cd` + que queda, `/cd`, un worktree) la transcripción muestra ahí `→ /ruta/nueva`, y + `-p` también encuentra la sesión por cualquiera de los directorios donde trabajó. - **Duración** es tiempo activo: los intervalos entre mensajes, sin las pausas de más de 30 minutos. Una sesión retomada a lo largo de varios días no cuenta los días del medio. @@ -348,11 +356,13 @@ Cada sesión de `s`: | `e` | `true` si la sesión no tiene mensajes. | | `i` | `true` si `p` se dedujo de otra sesión del mismo proyecto. | | `f` / `l` | Timestamp del primer y del último evento (ISO 8601). | -| `d` | Minutos activos (sin las pausas de más de 30 minutos). | -| `u` / `a` | Cantidad de mensajes tuyos / de Claude. | +| `d` | Minutos activos (sin las pausas de más de 30 minutos). En una rama, solo su parte propia. | +| `u` / `a` | Cantidad de mensajes tuyos / de Claude. En una rama, solo su parte propia. | | `k` | Tamaño del archivo en KB. | | `v` | Versión de Claude Code. | -| `c` | Transcripción: `[{"r": "u"|"a"|"t"|"c", "x": texto}]`; `t` es una llamada a herramienta, `c` un resumen de compactación. | +| `c` | Transcripción: `[{"r": "u"|"a"|"t"|"c"|"d", "x": texto}]`; `t` es una llamada a herramienta, `c` un resumen de compactación, `d` un cambio de directorio de trabajo. | +| `h` | Cuántos bloques al principio de `c` se heredaron de la sesión de la que salió esta rama (0 si no es una rama). | +| `o` / `ot` | Id y título de esa sesión (`null` si no es una rama; `ot` también si ya no está en disco). | Cada memoria de `m`: @@ -304,6 +304,14 @@ A few details worth knowing: - **Compaction.** When the context runs out (or on `/compact`) Claude Code replaces the earlier conversation with a summary. That summary is shown as a "context compacted here" mark, not as a message of yours, and is not counted. +- **Branches.** `/branch` (and `/fork`) start a new session that copies the + history of the original. claude-logbook reads the copy as inherited: it is + shown collapsed under "Inherited history", and only what came after counts + towards the messages, the duration and the start date. In the table the + session carries a `branch` chip. +- **Directory changes.** When the session moves to another directory (a `cd` + that sticks, `/cd`, a worktree) the transcript shows `→ /new/path` there, and + `-p` also finds the session by any directory it worked in. - **Duration** is active time: the gaps between messages, leaving out pauses longer than 30 minutes. A session resumed over several days does not count the days in between. @@ -346,11 +354,13 @@ Each session in `s`: | `e` | `true` if the session has no messages. | | `i` | `true` if `p` was inferred from a sibling session. | | `f` / `l` | First and last event timestamps (ISO 8601). | -| `d` | Active minutes (pauses over 30 minutes left out). | -| `u` / `a` | Message counts, yours / Claude's. | +| `d` | Active minutes (pauses over 30 minutes left out). In a branch, only its own part. | +| `u` / `a` | Message counts, yours / Claude's. In a branch, only its own part. | | `k` | File size in KB. | | `v` | Claude Code version. | -| `c` | Transcript: `[{"r": "u"|"a"|"t"|"c", "x": text}]`; `t` is a tool call, `c` a compaction summary. | +| `c` | Transcript: `[{"r": "u"|"a"|"t"|"c"|"d", "x": text}]`; `t` is a tool call, `c` a compaction summary, `d` a change of working directory. | +| `h` | How many blocks at the start of `c` were inherited from the session this one branched from (0 if not a branch). | +| `o` / `ot` | Id and title of that session (`null` if not a branch; `ot` also if it is no longer on disk). | Each memory in `m`: diff --git a/claude_logbook/__init__.py b/claude_logbook/__init__.py index 0128116..334c56b 100644 --- a/claude_logbook/__init__.py +++ b/claude_logbook/__init__.py @@ -3,6 +3,6 @@ No dependencies: standard library only. """ -__version__ = "1.5.2" +__version__ = "1.6.0" __all__ = ["__version__"] diff --git a/claude_logbook/sessions.py b/claude_logbook/sessions.py index 5f3035d..75db116 100644 --- a/claude_logbook/sessions.py +++ b/claude_logbook/sessions.py @@ -19,8 +19,16 @@ Schema of the record returned by `read_session`: u/a number of messages from you / from Claude k size of the .jsonl in KB v Claude Code version - c transcript: [{"r": "u" | "a" | "t" | "c", "x": text}] - (t: tool call summary, c: compaction summary) + c transcript: [{"r": "u" | "a" | "t" | "c" | "d", "x": text}] + (t: tool call summary, c: compaction summary, d: the working + directory changed to x) + h how many blocks at the start of `c` were copied from the session + this one branched from (/branch); 0 if it is not a branch + o id of that session, or None + ot its title, if it is still on disk (filled in by `_fill_gaps`) + +A branch starts as a copy of the original's history. Only what came after +counts towards `u`, `a`, `d` and `f`; the copy stays in `c`, first. `project_dir` and `mtime` are internal and never leave the module: `public_records()` drops them before the record is serialized. @@ -34,7 +42,7 @@ from datetime import datetime, timezone # Bump it when the record schema changes: it invalidates old caches instead of # reading records with the previous shape. -CACHE_VERSION = 3 +CACHE_VERSION = 4 EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) @@ -162,7 +170,10 @@ def active_minutes(stamps): def read_session(path): """Parses a whole .jsonl and returns that session's record.""" session_id = os.path.basename(path)[:-6] # without .jsonl - first_ts = last_ts = cwd = git_branch = version = None + first_ts = last_ts = cwd = here = git_branch = version = None + origin = None # the session /branch copied the history from + inherited = None # blocks of c that came with that copy + old_first_ts = None # first timestamp of the copied rows ai_title = custom_title = fallback_title = None stamps = [] # of the messages, for the active time user_msgs = assistant_msgs = 0 @@ -191,13 +202,22 @@ def read_session(path): custom_title = obj["customTitle"] # /rename, wins over the AI one continue + # /branch copies the original rows into the new file, each one + # marked with where it came from. They come first. + forked = obj.get("forkedFrom") + copied = isinstance(forked, dict) + if copied and forked.get("sessionId"): + origin = forked["sessionId"] + ts = obj.get("timestamp") if ts: - if first_ts is None: + if copied: + old_first_ts = old_first_ts or ts + elif first_ts is None: first_ts = ts last_ts = ts if cwd is None and obj.get("cwd"): - cwd = obj["cwd"] + cwd = here = obj["cwd"] if git_branch is None and obj.get("gitBranch"): git_branch = obj["gitBranch"] if obj.get("version"): @@ -209,8 +229,17 @@ def read_session(path): message = obj.get("message") if not isinstance(message, dict): continue - if ts: - stamps.append(ts) + if not copied: + if origin and inherited is None: + inherited = len(convo) # the branch's own part starts here + if ts: + stamps.append(ts) + # A `cd` that sticks, /cd or a worktree: from here on the session + # works somewhere else. Only messages count, so a subagent or a + # hook running elsewhere does not move it. + if obj.get("cwd") and obj["cwd"] != here: + here = obj["cwd"] + convo.append({"r": "d", "x": here}) if kind == "user": if obj.get("isMeta"): @@ -229,7 +258,7 @@ def read_session(path): if b.get("type") == "text": text = clean_text(b.get("text")) if text: - user_msgs += 1 + user_msgs += not copied if fallback_title is None: fallback_title = text[:TITLE_MAX] convo.append({"r": "u", "x": text}) @@ -247,7 +276,7 @@ def read_session(path): counted = True elif b.get("type") == "tool_use": convo.append({"r": "t", "x": tool_summary(b)}) - if counted: + if counted and not copied: assistant_msgs += 1 st = os.stat(path) @@ -255,8 +284,8 @@ def read_session(path): # `claude -p` with something piped on stdin (e.g. a git diff to write the # commit message), not of a conversation. noninteractive = ( - user_msgs == 1 and not (ai_title or custom_title) and bool(convo) - and len(convo[0]["x"]) > NONINTERACTIVE_CHARS + user_msgs == 1 and not (ai_title or custom_title) and not origin + and len(next((b["x"] for b in convo if b["r"] == "u"), "")) > NONINTERACTIVE_CHARS ) return { @@ -267,8 +296,8 @@ def read_session(path): "t": custom_title or ai_title or fallback_title, "ai": bool(custom_title or ai_title), "n": noninteractive, - "e": not convo, - "f": first_ts, + "e": all(b["r"] == "d" for b in convo), + "f": first_ts or old_first_ts, "l": last_ts, "d": active_minutes(stamps), "u": user_msgs, @@ -276,6 +305,8 @@ def read_session(path): "k": round(st.st_size / 1024, 1), "v": version, "c": convo, + "h": (len(convo) if inherited is None else inherited) if origin else 0, + "o": origin, "mtime": datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).isoformat(), } @@ -324,6 +355,8 @@ def drop_from_cache(paths, cache_path=None): def _fill_gaps(sessions): """Fills in what is missing after parsing every file. + A branch gets the title of the session it came from, if it is still there. + Some sessions (a cancelled /resume) never record a cwd. The directory name cannot be reliably reversed because "/" and "." are both encoded as "-", so the path is borrowed from another session of the same project and flagged in @@ -334,7 +367,9 @@ def _fill_gaps(sessions): if s["p"]: known.setdefault(s["project_dir"], s["p"]) + titles = {s["id"]: s["t"] for s in sessions} for s in sessions: + s["ot"] = titles.get(s["o"]) if s["o"] else None s["i"] = not s["p"] if not s["p"]: s["p"] = known.get(s["project_dir"], s["project_dir"]) @@ -403,7 +438,9 @@ def apply_filters(sessions, project=None, grep=None, query=None, if project: needle = os.path.expanduser(project).rstrip("/").lower() - out = [s for s in out if needle in s["p"].lower()] + # Any directory it worked in: where it started or one it moved to. + out = [s for s in out if needle in s["p"].lower() + or any(m["r"] == "d" and needle in m["x"].lower() for m in s["c"])] if grep: needle = grep.lower() diff --git a/claude_logbook/template.html b/claude_logbook/template.html index cd3d8b5..39740ac 100644 --- a/claude_logbook/template.html +++ b/claude_logbook/template.html @@ -547,6 +547,28 @@ .compact[open] summary::before { content: '▾ '; } .compact .bubble { margin-top: 8px; font-size: 13.5px; } + .inherited { margin: 0 0 6px; } + .inherited summary { border-top: 0; } + .inherited-body { padding: 14px 0 4px; opacity: .78; } + .inherited-body > :first-child { margin-top: 0; } + .inherited-end { + font-family: var(--mono); + font-size: 11.5px; + color: var(--muted); + text-align: center; + padding: 6px 0; + margin-top: 14px; + border-bottom: 1px dashed var(--line); + } + + .cwd { + font-family: var(--mono); + font-size: 11.5px; + color: var(--muted); + padding: 3px 0 3px 12px; + overflow-wrap: anywhere; + } + .reader-empty { color: var(--muted); font-family: var(--mono); font-size: 13px; text-align: center; padding: 60px 20px; } /* ---------- toast ---------- */ @@ -1079,6 +1101,7 @@ function renderSessions() { d.n ? '<span class="chip chip-auto">non-interactive</span>' : '', d.b && d.b !== 'HEAD' ? `<span class="chip chip-branch">${esc(d.b)}</span>` : '', d.i ? '<span class="chip" title="Path deduced from other sessions of the same project">inferred path</span>' : '', + d.o ? `<span class="chip" title="Branched from ${esc(d.ot || d.o)}">branch</span>` : '', ].join(''); return ` @@ -1193,6 +1216,16 @@ function showReader() { if (!SINGLE) readerEl.focus(); } +function blockHtml(m) { + return m.r === 't' + ? `<div class="tool"><b>⚒</b><span>${esc(m.x)}</span></div>` + : m.r === 'd' + ? `<div class="cwd">→ ${esc(m.x)}</div>` + : m.r === 'c' + ? `<details class="compact"><summary>Context compacted here · the summary Claude kept</summary><div class="bubble">${renderBody(m.x)}</div></details>` + : `<div class="turn turn-${m.r}"><span class="who">${WHO[m.r]}</span><div class="bubble">${renderBody(m.x)}</div></div>`; +} + function openChat(id) { const d = BY_ID.get(id); if (!d || (d.e && !SINGLE)) return; @@ -1210,13 +1243,12 @@ function openChat(id) { `<span class="chip">${d.id.slice(0, 8)}</span>`, ].filter(Boolean).join(''); + const h = d.h || 0, old = d.c.slice(0, h), own = d.c.slice(h); + const inherited = h + ? `<details class="compact inherited"><summary>Inherited history · ${old.filter(m => m.r === 'u' || m.r === 'a').length} messages from “${esc(d.ot || d.o.slice(0, 8))}”</summary><div class="inherited-body">${old.map(blockHtml).join('')}<div class="inherited-end">the branch starts here</div></div></details>` + : ''; bodyEl.innerHTML = d.c.length - ? d.c.map(m => m.r === 't' - ? `<div class="tool"><b>⚒</b><span>${esc(m.x)}</span></div>` - : m.r === 'c' - ? `<details class="compact"><summary>Context compacted here · the summary Claude kept</summary><div class="bubble">${renderBody(m.x)}</div></details>` - : `<div class="turn turn-${m.r}"><span class="who">${WHO[m.r]}</span><div class="bubble">${renderBody(m.x)}</div></div>` - ).join('') + ? inherited + own.map(blockHtml).join('') : `<p class="reader-empty">This session has no messages.</p>`; if (!SINGLE && location.hash.slice(1) !== id) history.replaceState(null, '', '#' + id); diff --git a/claude_logbook/terminal.py b/claude_logbook/terminal.py index 61d05d8..351c9bf 100644 --- a/claude_logbook/terminal.py +++ b/claude_logbook/terminal.py @@ -212,17 +212,33 @@ def print_chat(s, st, out, show_tools=True, width=None): print(f"{st.dim}This session has no messages.{st.reset}", file=out) return + def divider(label): + side = max(3, (min(width, 80) - len(label)) // 2) + print(f"{st.faint}{'─' * side}{label}{'─' * side}{st.reset}", file=out) + first = True - for m in s["c"]: + blocks = s["c"] + if s.get("h"): + # A branch: what it copied from the original is in that session, so + # here it is only a mark of where its own part starts. + old = blocks[:s["h"]] + n = sum(m["r"] in "ua" for m in old) + origin = s.get("ot") or (s.get("o") or "?")[:8] + divider(f" {n} messages inherited from {clip(origin, 40)} ") + blocks = blocks[s["h"]:] + first = False + for m in blocks: if m["r"] == "c": # The summary is long and Claude's, not part of the dialogue: # only the mark of where the earlier context was folded. if not first: print(file=out) first = False - label = " context compacted here " - side = max(3, (min(width, 80) - len(label)) // 2) - print(f"{st.faint}{'─' * side}{label}{'─' * side}{st.reset}", file=out) + divider(" context compacted here ") + continue + if m["r"] == "d": + print(f" {st.faint}→ {clip(m['x'], body - 4)}{st.reset}", file=out) + first = False continue if m["r"] == "t": if show_tools: diff --git a/server/render.go b/server/render.go index be3ba01..2c72c1a 100644 --- a/server/render.go +++ b/server/render.go @@ -45,6 +45,9 @@ type Session struct { K float64 `json:"k"` V *string `json:"v"` C []Block `json:"c"` + H int `json:"h"` + O *string `json:"o"` + OT *string `json:"ot"` } type Payload struct { @@ -81,10 +84,16 @@ func ParsePayload(raw []byte, maxSessions int) (*Payload, []byte, error) { return nil, nil, fmt.Errorf("payload: session %d: no c", i) } for j, b := range s.C { - if b.R != "u" && b.R != "a" && b.R != "t" && b.R != "c" { + if b.R != "u" && b.R != "a" && b.R != "t" && b.R != "c" && b.R != "d" { return nil, nil, fmt.Errorf("payload: session %d block %d: bad r", i, j) } } + if s.H < 0 || s.H > len(s.C) { + return nil, nil, fmt.Errorf("payload: session %d: bad h", i) + } + if s.O != nil && !sessionIDRE.MatchString(*s.O) { + return nil, nil, fmt.Errorf("payload: session %d: bad o", i) + } } p.M = []json.RawMessage{} clean, err := json.Marshal(p) @@ -185,12 +194,28 @@ func RenderText(p *Payload) []byte { continue } prev := "" - for _, c := range s.C { + for j, c := range s.C { + if s.H > 0 && j == 0 { + origin := deref(s.OT, "") + if origin == "" && s.O != nil { + origin = *s.O + } + fmt.Fprintf(&b, "\n--- inherited history, from %s ---\n", origin) + } + if s.H > 0 && j == s.H { + b.WriteString("\n--- the branch starts here ---\n") + prev = "" + } switch c.R { + case "d": + if prev != "t" && prev != "d" { + b.WriteString("\n") + } + fmt.Fprintf(&b, "> cd: %s\n", c.X) case "c": b.WriteString("\n--- context compacted here ---\n") case "t": - if prev != "t" { + if prev != "t" && prev != "d" { b.WriteString("\n") } fmt.Fprintf(&b, "> tool: %s\n", strings.ReplaceAll(c.X, "\n", " ")) diff --git a/server/server_test.go b/server/server_test.go index d19c5e8..1ad36ee 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -127,6 +127,24 @@ func TestCompactionBlock(t *testing.T) { } } +func TestBranchAndDirectoryChange(t *testing.T) { + h := newHarness(t, nil) + branch := strings.Replace(session, `"c":[`, `"h":1,"o":"bbbbbbbb-0000","ot":"The original",`+ + `"c":[{"r":"u","x":"old question"},{"r":"d","x":"/home/u/proj/sub"},`, 1) + r := h.create(`{"payload":` + payload(branch) + `}`) + txt := h.do("GET", "/share/"+r.ID+".txt", "", "").Body.String() + for _, want := range []string{"--- inherited history, from The original ---\n\n## User\n\nold question", + "--- the branch starts here ---\n\n> cd: /home/u/proj/sub\n"} { + if !strings.Contains(txt, want) { + t.Fatalf("missing %q in txt: %s", want, txt) + } + } + js := h.do("GET", "/share/"+r.ID+".json", "", "").Body.String() + if !strings.Contains(js, `"h":1,"o":"bbbbbbbb-0000","ot":"The original"`) { + t.Fatalf("json: %s", js) + } +} + func TestUpdateAndDeleteNeedTheSecret(t *testing.T) { h := newHarness(t, nil) r := h.create(`{"payload":` + payload() + `}`) @@ -187,6 +205,8 @@ func TestRejectsBadPayloads(t *testing.T) { "two sessions": `{"payload":` + payload(session, session) + `}`, "bad role": `{"payload":` + payload(strings.Replace(session, `"r":"t"`, `"r":"z"`, 1)) + `}`, "bad type": `{"payload":` + payload(strings.Replace(session, `"u":1`, `"u":"1"`, 1)) + `}`, + "h too big": `{"payload":` + payload(strings.Replace(session, `"c":[`, `"h":9,"c":[`, 1)) + `}`, + "bad origin": `{"payload":` + payload(strings.Replace(session, `"c":[`, `"o":"../x","c":[`, 1)) + `}`, "memories": `{"payload":{"s":[` + session + `],"m":[{"name":"x"}]}}`, "bad expire": `{"payload":` + payload() + `,"expire":"never"}`, "extra field": `{"payload":` + payload() + `,"html":"x"}`, diff --git a/tests/test_sessions.py b/tests/test_sessions.py index 7342058..a938e85 100644 --- a/tests/test_sessions.py +++ b/tests/test_sessions.py @@ -142,6 +142,69 @@ class TestTitlesCompactionDuration(TempRoot): self.assertEqual(S.active_minutes([ts(0), ts(30), ts(31, hour=11)]), 30) +class TestBranchesAndDirectories(TempRoot): + ORIGIN = "33333333-0000-0000-0000-000000000001" + + def branch(self, own=True): + fork = {"forkedFrom": {"sessionId": self.ORIGIN, "messageUuid": "x"}} + events = [ + user("the original question", at=ts(0, hour=8), **fork), + assistant("the original answer", at=ts(5, hour=8), **fork), + {"type": "custom-title", "customTitle": "Try another way (Branch)"}, + ] + if own: + events += [user("and now this", at=ts(0)), assistant("ok", at=ts(10))] + return write_session(self.root, "-home-u-proj", + "33333333-0000-0000-0000-000000000002", events) + + def test_the_copied_history_is_inherited(self): + rec = S.read_session(self.branch()) + self.assertEqual(rec["o"], self.ORIGIN) + self.assertEqual(rec["h"], 2) + self.assertEqual([m["x"] for m in rec["c"][2:]], ["and now this", "ok"]) + self.assertEqual((rec["u"], rec["a"], rec["d"]), (1, 1, 10)) + self.assertEqual(rec["f"], ts(0)) + self.assertEqual(rec["t"], "Try another way (Branch)") + + def test_a_branch_with_nothing_of_its_own(self): + rec = S.read_session(self.branch(own=False)) + self.assertEqual((rec["h"], rec["u"], rec["a"]), (2, 0, 0)) + self.assertFalse(rec["e"]) + self.assertEqual(rec["f"], ts(0, hour=8)) + + def test_not_a_branch(self): + path = write_session(self.root, "-p", "33333333-0000-0000-0000-000000000003", [ + user("hello", at=ts(0))]) + rec = S.read_session(path) + self.assertEqual((rec["h"], rec["o"]), (0, None)) + + def test_the_origin_title_is_filled_in(self): + self.branch() + write_session(self.root, "-home-u-proj", self.ORIGIN, [ + ai_title("The original"), user("the original question", at=ts(0, hour=8))]) + by_id = {s["id"]: s for s in S.load_sessions(self.root, use_cache=False)} + self.assertEqual(by_id["33333333-0000-0000-0000-000000000002"]["ot"], "The original") + self.assertIsNone(by_id[self.ORIGIN]["ot"]) + + def test_directory_changes_are_marked_and_filtered(self): + path = write_session(self.root, "-home-u-proj", "33333333-0000-0000-0000-000000000004", [ + {"type": "system", "timestamp": ts(0), "cwd": "/home/u/proj"}, + user("build it", at=ts(1)), + assistant("ok", at=ts(2), cwd="/home/u/proj/server"), + assistant("again", at=ts(3), cwd="/home/u/proj/server"), + assistant("isSidechain", at=ts(3), cwd="/elsewhere", isSidechain=True), + user("back", at=ts(4)), + ]) + rec = S.read_session(path) + self.assertEqual(rec["p"], "/home/u/proj") + self.assertEqual([(m["r"], m["x"]) for m in rec["c"]], [ + ("u", "build it"), ("d", "/home/u/proj/server"), ("a", "ok"), + ("a", "again"), ("d", "/home/u/proj"), ("u", "back")]) + S._fill_gaps([rec]) + self.assertEqual(S.apply_filters([rec], project="proj/server"), [rec]) + self.assertEqual(S.apply_filters([rec], project="/elsewhere"), []) + + class TestToolSummary(unittest.TestCase): def test_uses_the_representative_parameter(self): self.assertEqual( diff --git a/tests/test_terminal.py b/tests/test_terminal.py index e7e6d69..7752e37 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -135,6 +135,18 @@ class TestOutput(unittest.TestCase): self.assertIn("context compacted here", out) self.assertNotIn("SUMMARY TEXT", out) + def test_branch_hides_what_it_inherited(self): + buf = io.StringIO() + c = [{"r": "u", "x": "OLD QUESTION"}, {"r": "a", "x": "OLD ANSWER"}, + {"r": "d", "x": "/home/u/proj/sub"}, {"r": "u", "x": "new one"}] + T.print_chat(self.session_item(c=c, h=2, o="12345678-aa", ot="The original"), + T.Style(False), buf) + out = buf.getvalue() + self.assertIn("2 messages inherited from The original", out) + self.assertNotIn("OLD", out) + self.assertIn("→ /home/u/proj/sub", out) + self.assertIn("new one", out) + def test_empty_session_says_so(self): buf = io.StringIO() T.print_chat(self.session_item(c=[], t=None), T.Style(False), buf) |