Repository navigation
Description
Child of #596. Read the parent's Contract first: it holds the wire, the merge order, the overlaps with #589 and the joint close task. Branch off epic/596-session-history.
User story
As the owner, I want relay to list every Claude session it knows of, with its own title and last-activity time, so that I can find a past session without remembering where it ran.
Acceptance criteria
GET /api/session-historylists each ledger record and each discovered record as one row, newest first bylastActiveAt, else bycreatedAt, at most 500.- A row's title is the transcript's latest
custom-title, else its latestai-title, else its first genuine user prompt, else null. - A row's
lastActiveAtis the newest recordtimestampin the transcript, else the file's modification time. - Relay writes a discovered record for an interactive Claude transcript that no ledger record links and relay-sessions does not manage.
- A discovered record has
state: "discovered", no project of its own, and no ledger project id. - After a relay restart, the history lists the same discovered records before the first scan ends.
- Each scan reads at most 64 new or changed transcripts, newest first. A row whose transcript is not read yet shows
title: null. - Relay removes a discovered record at the next scan when relay-sessions manages its conversation.
- On an SSH host, relay reads only the transcript folders of that host's projects. On the console, it reads every folder.
- The reader refuses a symbolic link on a transcript, its folder,
~/.claude/projectsor~/.claude, and writes nothing on the machine. - A row whose folder holds a refused transcript or is a refused folder shows
transcript: "unknown". - A machine holds at most 2000 discovered records. Past that, relay removes the oldest in the same scan and writes no audit row.
- A machine whose store root is missing reports
answered: falsefor that scan. - On a machine with more than 4096 transcripts, relay lists the newest 4096 by modification time and still answers.
- A row shows
transcript: "absent"only when its machine's listing is under the cap and its folder is in that listing's scope. Otherwise the row showspresentorunknown. relay session history --jsonprints the same rows.--project <id>filters them.- The Chief of Staff scope and the TCP listener cannot reach
GET /api/session-history.
What I'd notice
relay session history lists my Claude sessions with their names and when I last used them.
Tasks
- Ledger:
StateDiscovered, the new fields,PutDiscovered,DiscoveredID. -
internal/sessionhistory:Reader,Entry,Listing,Machine, the Claude reader (two scripts, parse, per-machine cache), and theIndex(scan loop, discovered records, rows). -
outsidesessions: exportLaunchFolder;Inventory.Held. - Doors:
GET /api/session-history, thesession.historyadmin op,relay session history. - Wiring in
frontend_server.go. - Docs, in the files and line budgets below.
- Tests (test writer, from the criteria and this contract):
e2e/features/g1_session_history_test.go. - Break and restore: make the title rule skip
custom-title, confirmTestHistoryTitleRulegoes red, restore it byte for byte. - Review on the default model: the diff adds a reader of every console transcript (threat model 3d).
Contract
Every file this child may touch is listed below. A file not listed is a question for the planner first.
Interfaces
-
Ledger (
internal/sessions/ledger/ledger.go; this child owns it, and relay#599 and relay#600 have named allowed edits):const StateDiscovered State = "discovered" // Record gains, at the end of the struct: ConversationID string `json:"conversation_id,omitempty"` // the client's own conversation id Agent string `json:"agent,omitempty"` // "claude" on a terminal or discovered record HostID string `json:"host_id,omitempty"` // a discovered record's SSH host; empty on the console // DiscoveredID is "d-" plus the first 16 bytes, hex, of sha256(machineKey, NUL, agent, NUL, conversationID). func DiscoveredID(machineKey, agent, conversationID string) string // PutDiscovered adds the records in one save. It skips an id the ledger already holds and never replaces a record that is not discovered. It returns how many it added. func (l *Ledger) PutDiscovered(recs []Record) (int, error)
- A discovered record:
SessionIDDiscoveredID(...),Kind"claude",Agent"claude",StateStateDiscovered,ProjectIDempty,Directorythe reader's folder,HostID,ConversationID,Createdthe transcript's first timestamp. - No existing reader of the ledger changes.
AuthorizeLaunchandauthorizeUnsandboxedLaunchalready refuse a record that is not dormant, andMarkLiveDormant,cleanupProjectand the read-only sweep skip it.
- A discovered record:
-
Reader (
internal/sessionhistory/history.go, new):type Entry struct { Agent, ConversationID, Directory string Title string // "" when unknown TitleSource string // "client", "prompt" or "" LastActiveAt, CreatedAt time.Time } type Listing struct { Answered bool // the script ran to the end, the store root is a real folder, and the listing is under its cap Entries []Entry // every interactive transcript that exists } type Machine struct { Key string // "console" or the host id HostID *string Run func(ctx context.Context, script string) ([]byte, error) // outsideRun for that machine Prefixes []string // nil: every folder (console); else the mangled project folder names (as m.Ended builds them) } type Reader interface { Agent() string Discover(ctx context.Context, m Machine) (Listing, error) // an error means Answered is false }
-
Claude reader (
internal/sessionhistory/claude.go, new;func NewClaude() Reader):- Script 1, the listing. At most 4096 regular files
~/.claude/projects/<folder>/<id>.jsonl, at depth 2 only, so subagent folders are skipped.- The stem must match the conversation-id charset (
outsidesessions.IsConversationID). Folders are filtered byPrefixesasEndedScanScriptfilters them. - It refuses a symlink on the file, its folder, the root or
~/.claude. - It prints the home, then
path size mtimeper file. - The cap reached, the root missing or the root not a folder:
Answered: false.
- The stem must match the conversation-id charset (
- Script 2, the reads. Only for files new or changed since the last scan (size or mtime), at most 64 per scan, newest first; the rest wait for the next scan. Per file it prints:
- the last
custom-titleand the lastai-titleline in the last 256 KiB, each at most 4 KiB; - the first 64 KiB, cut to its first
userrecord that is notisMetaorisSidechain, at most 8 KiB; - the first record that carries
entrypoint; - the last 16 KiB.
- Total output stays under
outsideRun's 8 MiB.
- the last
- Parse.
- Interactive only: the first
entrypointmust be"cli"; any other file yields no entry. - Title: the latest
customTitle, else the latestaiTitle(TitleSource"client"). Else the first prompt's first non-empty line that does not start with/or<, trimmed ("prompt"). Else"". Cap 120 runes; drop control characters. - Directory:
outsidesessions.LaunchFolder(the ended-row rule: the newest record whosesessionIdis the stem and whosecwdmaps back to this file). No such record: no entry. LastActiveAt: the newesttimestampin the 16 KiB tail, else the mtime.CreatedAt: the first record'stimestampin the head, else the mtime.
- Interactive only: the first
- Cache. Per machine, keyed by path, holding size, mtime and the
Entry, in memory only. A file absent from the listing leaves the cache.
- Script 1, the listing. At most 4096 regular files
-
Index (
internal/sessionhistory/history.go):type Options struct { Clock interface{ Now() time.Time; After(time.Duration) <-chan time.Time } Ledger *ledger.Ledger Readers []Reader // this epic: NewClaude() Machines func() []Machine // the console, then each host with a project (fresh settings) Held func(machineKey string) (map[string]bool, bool) // the latest successful outside probe's Held; false: no answer yet Managed func(ctx context.Context) (map[string]bool, error) // relay-sessions' Claude ids (ManagedClaudeIdentities) Project func(machineKey, directory string) *string // the registered project holding directory on that machine RecordMachine func(r ledger.Record) string // a launched record's machine key: Detached host, else its project's host, else "console" } func New(o Options) *Index func (x *Index) Run(ctx context.Context) // per machine: one scan at start, then one per outsidesessions.ProbeInterval on the clock func (x *Index) Rows(projectID string) Response // wire 1's body func (x *Index) Listing(machineKey string) (Listing, time.Time, bool) // the last answered listing; relay#599 and relay#600 read it
- After each scan, entries that no ledger record links (by machine, agent and conversation id) and that
Manageddoes not hold become discovered records, onePutDiscoveredper scan. At most 2000 discovered records per machine: relay keeps the 2000 newest of the held and new records together and removes the rest (Amendment 34). - A failed
Managedread adds no records in that scan (fail closed). - Every scan writes one
session.history.scanevent:machine,outcome(okorerror),answered,count,revision. - The
resumefield of a row, the first rule that applies:
Row resumeresumeReasonstate: "live"nonelivelaunched, kind claude,pi,codexorchat, dormantsessionnone launched terminal or discovered, on a host nonehost_unsupportedlaunched terminal or discovered, no conversationIdnoneno_conversationconversation in Heldfor its machinenoneheldtranscript: "absent"nonetranscript_absentno projectIdnoneno_projectotherwise historynone - In this child,
resume: "history"answers 404 until relay#599 adds the door. The field is still computed. transcriptispresentwhen the machine's last answered listing holds the conversation,absentwhen an answered listing lacks it, andunknownwith no answered listing or noconversationId.
- After each scan, entries that no ledger record links (by machine, agent and conversation id) and that
-
outsidesessions:
ended.go:func LaunchFolder(home, cwd, stem, path string) (string, bool), an exported wrapper oflaunchFolder; nothing else changes.inventory.go:func (i *Inventory) Held(machineKey string) (map[string]bool, bool)returns a copy of the latest successful probe'sHeldfor that machine. Store it inprobewhere the ended scan already receives it.
-
Doors (
cmd/relay):session_history_ops.go(new): builds theIndexoptions fromconfig.FreshSettings,outsideRun,matchOutsideProject,resolveOutsideProjectPathsand the inventory;historyOps.List(projectID).session_history_routes.go(new):RegisterSessionHistoryRoutes(rr, ops)withrr.Handle(control.ClassExecute, "GET /api/session-history", ...). An unknownprojectIdanswers an emptyrows. A history not wired answers503 history_unavailable.frontend_server.go: build the index besidenewOutsideInventory, startRun, register the routes inregisterFrontendRoutes.admin_ops.go:"session.history": {handle: adminSessionHistory, caller: adminCallerOperator}.cli_verbs.go:{Name: "session history", Run: sessionHistory, Calls: []string{adminDoor("session.history")}}.session_history_verbs.go(new): flags--project,--json. The table shows TITLE (orClaude — <folder>), LAST ACTIVE, KIND, STATE, RESUME and ID. Row text is untrusted, so the table strips control characters asrelay auditdoes.
File ownership
Dev (19 files):
internal/sessions/ledger/ledger.go: owner. relay#599 may addLinkConversation; relay#600 may addMissingSince,SetMissingandRemoveIfPurgeable. Nothing else.internal/sessionhistory/history.go(new): owner. relay#599 may addVerify; relay#600 may add the one call to its purge pass after each scan.internal/sessionhistory/claude.go(new): owner. relay#599 may add the ClaudeVerifyread.internal/outsidesessions/ended.go:LaunchFolderonlyinternal/outsidesessions/inventory.go:Heldand its stored map onlycmd/relay/session_history_ops.go(new): owner. relay#599 adds the resume core; relay#600 adds the purge wiring.cmd/relay/session_history_routes.go(new): owner. relay#599 adds the POST route.cmd/relay/session_history_verbs.go(new)cmd/relay/frontend_server.go: construction,Run, registration onlycmd/relay/admin_ops.go: one table linecmd/relay/cli_verbs.go: one table linedocs/session-history.md(new): owner: records, readers, the title rule, scan bounds, wire 1, the resume table. relay#599 and relay#600 each add their own section.docs/routes.md: the GET rowdocs/cli.md:session historyin the synopsis and its sectiondocs/events.md:session.history.scandocs/FEATURES.md: new rowG1.56(below)docs/THREAT-MODEL.md: one note under 3d: theexecuteholder reads titles and times of every console transcript and of host project transcripts; same symlink refusals; no request field names a path; title text is untrusted display data and grants nothing.docs/outside-sessions.md: one paragraph after "Ended sessions", pointing to session-history.md, saying ended rows are unchangedCLAUDE.md: one row in "Where things are written down" fordocs/session-history.md
Not touched: probe.go, session_launch.go, session_routes.go, outside_session_ops.go, docs/session-host.md, docs/audit-log.md, fakerelay.
Test writer (1 file):
e2e/features/g1_session_history_test.go(new)
docs/FEATURES.md row G1.56 "Session history":
- Claim: the criteria above in one paragraph.
- Simple door: Eve > project > Launcher > Resume (Launcher history: real titles, last activity and resume eve#637).
- Power door:
relay session history. - Doors:
http:GET /api/session-historycli:relay session history. - Gate: none.
- Proof:
event:session.history.scan=ok#revisionout:http:GET /api/session-history#.rows[]. - Test: the e2e names below.
Paths
- Simple: through eve (Launcher history: real titles, last activity and resume eve#637).
- Power:
relay session history [--project <id>] [--json]. - This child adds no setting.
Acceptance mapping and test surface (e2e unless named)
| Criterion | Test |
|---|---|
| Rows, order, cap 500 | TestHistoryListsLedgerAndDiscovered |
Title rule (custom over ai over prompt; / and < prompts skipped; 120 cap; control characters dropped) |
TestHistoryTitleRule |
lastActiveAt from the newest timestamp, not the mtime |
TestHistoryLastActiveFromTimestamp (plant an mtime later than the newest record) |
Discovered record written; not for a managed id; not for sdk-cli; no project id |
TestHistoryDiscoveredRecord |
| Same rows after restart | TestHistoryDiscoveredAfterRestart (Instance.Restart) |
| Host scope; symlink refused; nothing written | TestHistoryScanScope (ssh stub host) |
Root missing: answered: false |
TestHistoryRootMissingNotAnswered |
| CLI | TestHistoryCLI |
| Scope and TCP refused | TestHistoryScopeRefused |
Waits:
- Boot: the bundle's
ready.json, asInstance.bootreads it. - A scan: the
session.history.scanevent line (WaitEvent) withrevisionabove the one read before the plant. - After a restart:
Instance.Restartreturns at ready, then the firstsession.history.scanevent per machine. - Planted transcripts and registry files are written before the wait; no test sleeps.
Budget
- Dev: 19 files; about 900 to 1,050 Go lines (the two new
sessionhistoryfiles about 600 of them); about 220 doc lines. - Tests: 1 file, about 450 lines.
- Past either figure, stop and ask the planner.
Amendments (planner, 2026-10-22)
Amendment 1: Machine gains Name string, the machines[].machine text.
Amendment 2: Machine gains Scope func(ctx context.Context) []string. When set, the scan calls it once and uses its result as Prefixes.
Amendment 3: A host's Scope resolves its project folders on the host and caches them. The row project match reads that cache and makes no round trip.
Amendment 4: The session.history admin op reads the history through a new appRouter.history field. Remove the package variable activeHistoryOps.
Amendment 5: server_core.go sets router.history beside router.persistentSessions. It starts Index.Run(ctx) with app.goFunc, beside outside.Run.
Amendment 6: FrontendServer gets no history context. Serve and Shutdown do not change.
Amendment 7: Ownership adds cmd/relay/router.go (one field) and cmd/relay/server_core.go (the two lines in Amendment 5). Nothing else in either file.
Amendment 8: A discovered row has kind: "terminal". The ledger keeps Kind: "claude" on the discovered record. A launched pty row has kind: "terminal".
Amendment 9: The resume table gets a third rule, after the session rule: a launched row that is not pty gives resume: "none", resumeReason: "kind".
Amendment 10: revision grows by one after each machine scan and when a machine leaves the list. A ledger change shows in rows at once.
Amendment 11: Relay omits a Windows host from Machines(). A launched record on it shows transcript: "unknown".
Amendment 12: Listing gains Present map[string]bool and func (l Listing) Has(agent, conversationID string) bool.
Amendment 13: Present holds every transcript in the listing script's output, read or not, interactive or not. Entries holds only the files read and parsed.
Amendment 14: A row's transcript is present when the machine's last answered listing Has the conversation. It is absent when that listing does not have it.
Amendment 15: A row with transcript: "present" and no parsed entry shows title: null and lastActiveAt: null until a later scan reads its file.
Amendment 16: Index.Listing returns Present with the entries. relay#599 and relay#600 read presence through Has, never through Entries.
Amendment 17: The read script prints at most the first 4 user records that are not isMeta or isSidechain, 8 KiB in total. The prompt title comes from the first of them that gives a title.
Amendment 18: A row with no parsed entry has lastActiveAt: null. The sort uses its createdAt, so it stays inside the 500 cap.
Amendment 19: In this epic, a launched agent record has no conversationId. Its row shows title: null, lastActiveAt: null and transcript: "unknown".
Amendment 20: Budget: 21 dev files; Go at most 1,350 lines. No trim of the current diff.
Amendment 21 (2026-10-22): The listing script sorts transcripts by modification time, newest first, and prints at most 4096. Past 4096 it prints X and still answers.
Amendment 22: Listing gains Complete bool. It is true when the listing printed every transcript, under the cap. Answered no longer depends on the cap.
Amendment 23: Listing gains Scope []string, the prefixes the listing used. Nil means every folder.
Amendment 24: func (l Listing) Absent(agent, conversationID, directory string) bool is true only when Answered and Complete are true, Has is false, and the scope includes outsidesessions.FolderName(directory) by the listing's own prefix test (hasPrefix).
Amendment 25: A row's transcript is present when Has is true, absent when Absent is true, else unknown. This replaces Amendment 14.
Amendment 26: Index.Listing returns Complete and Scope. relay#600 reads absence only through Absent, never as "not Has".
Amendment 27: After each scan whose Managed read succeeds, relay removes, in one save, every discovered record of that machine whose conversation Managed holds. A failed read removes nothing.
Amendment 28: Ledger gains func (l *Ledger) RemoveDiscovered(ids []string) (int, error). It removes, in one save, only the named records that are still discovered.
Amendment 29: The session.history.scan event gains complete (bool) and superseded (the count Amendment 27 removed).
Amendment 30: Each scan still reads at most 64 transcripts, newest first. A store of 4000 transcripts gets every title after about 63 scans. No title cache on disk.
Amendment 31: Tests, in the test writer's file:
TestHistoryListingCap: plant 4097 transcripts. The machine answers, and the oldest transcript's row showstranscript: "unknown".TestHistoryAdoptedDropsFound: a discovered record whose conversation relay-sessions then holds, through the adopt door as the adopt feature tests do, is gone after the next scan.TestHistoryHostScopeUnknown: remove a host project. Its discovered rows showtranscript: "unknown".TestHistoryDiscoveredAfterRestartasserts the rows before the first scan event and the titles after it, with at most 64 planted files.
Amendment 32: Budget: Go at most 1,550 lines. Ownership does not change: the code is inclaude.go,history.goandledger.go.
Amendment 33 (2026-10-22): Amendment 32 now sets 1,550 Go lines, not 1,450. The branch holds about 1,425 after the round-1 review fixes, and Amendments 21 to 31 add about 100.
Amendment 34 (2026-10-22): After each scan, relay keeps the 2000 newest discovered records of the machine, held and new together. It ranks them by the entry'sLastActiveAt, else the record'sCreated.
Amendment 35: Relay removes the rest withRemoveDiscovered, in the save that adds the new records. A removed record is not added again unless its transcript becomes newer than the 2000th.
Amendment 36: This removal is eviction, not purge. It writes no audit row, because a discovered record holds no authority and no data. Thesession.history.scanevent gainsevicted(a count).
Amendment 37: The listing script prints oneRline, the base64 folder name, for each folder it refuses and for the folder of each transcript it refuses.ListinggainsRefused map[string]bool, keyed by folder name.
Amendment 38:Absentis also false when a refused folder name equalsoutsidesessions.FolderName(directory)or starts with it. Such a row showstranscript: "unknown".
Amendment 39: Tests, in the test writer's file:TestHistoryDiscoveredCap: seed the ledger with 2000 discovered records before boot, then plant one newer transcript. After the scan, the machine holds 2000, the new one included, and the audit log has no row for the removed one.TestHistoryScanScopeadds a symlinked project folder: the row of a record in it showstranscript: "unknown".
Amendment 40: Budget: Go at most 1,600 lines. This replaces the figure in Amendments 32 and 33.
Amendment 41 (2026-10-22): relay#600 adds a resume-table rule after theliverule: a dormant launched agent record withtranscript: "absent"givesnone,transcript_absent. See Session history: purge a record whose transcript is gone #600, Amendments 6 and 7.
Activity
barelyworkingcode commentedon Oct 23, 2026
Coordinator approval: inherits the approved epic's listed batches, 2026-10-22
barelyworkingcode commentedon Oct 23, 2026
Merged in #605 to epic/596-session-history.
barelyworkingcode commentedon Oct 23, 2026
Done in #605 (merged into epic/596-session-history).