Skip to content

Session history: Claude reader, discovered records, history list #598

Closed

Description

@barelyworkingcode

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-history lists each ledger record and each discovered record as one row, newest first by lastActiveAt, else by createdAt, at most 500.
  • A row's title is the transcript's latest custom-title, else its latest ai-title, else its first genuine user prompt, else null.
  • A row's lastActiveAt is the newest record timestamp in 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/projects or ~/.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: false for 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 shows present or unknown.
  • relay session history --json prints 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 the Index (scan loop, discovered records, rows).
  • outsidesessions: export LaunchFolder; Inventory.Held.
  • Doors: GET /api/session-history, the session.history admin 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, confirm TestHistoryTitleRule goes 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

  1. 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: SessionID DiscoveredID(...), Kind "claude", Agent "claude", State StateDiscovered, ProjectID empty, Directory the reader's folder, HostID, ConversationID, Created the transcript's first timestamp.
    • No existing reader of the ledger changes. AuthorizeLaunch and authorizeUnsandboxedLaunch already refuse a record that is not dormant, and MarkLiveDormant, cleanupProject and the read-only sweep skip it.
  2. 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
    }
  3. 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 by Prefixes as EndedScanScript filters them.
      • It refuses a symlink on the file, its folder, the root or ~/.claude.
      • It prints the home, then path size mtime per file.
      • The cap reached, the root missing or the root not a folder: Answered: false.
    • 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-title and the last ai-title line in the last 256 KiB, each at most 4 KiB;
      • the first 64 KiB, cut to its first user record that is not isMeta or isSidechain, at most 8 KiB;
      • the first record that carries entrypoint;
      • the last 16 KiB.
      • Total output stays under outsideRun's 8 MiB.
    • Parse.
      • Interactive only: the first entrypoint must be "cli"; any other file yields no entry.
      • Title: the latest customTitle, else the latest aiTitle (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 whose sessionId is the stem and whose cwd maps back to this file). No such record: no entry.
      • LastActiveAt: the newest timestamp in the 16 KiB tail, else the mtime.
      • CreatedAt: the first record's timestamp in the head, else the mtime.
    • Cache. Per machine, keyed by path, holding size, mtime and the Entry, in memory only. A file absent from the listing leaves the cache.
  4. 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 Managed does not hold become discovered records, one PutDiscovered per 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 Managed read adds no records in that scan (fail closed).
    • Every scan writes one session.history.scan event: machine, outcome (ok or error), answered, count, revision.
    • The resume field of a row, the first rule that applies:
    Row resume resumeReason
    state: "live" none live
    launched, kind claude, pi, codex or chat, dormant session none
    launched terminal or discovered, on a host none host_unsupported
    launched terminal or discovered, no conversationId none no_conversation
    conversation in Held for its machine none held
    transcript: "absent" none transcript_absent
    no projectId none no_project
    otherwise history none
    • In this child, resume: "history" answers 404 until relay#599 adds the door. The field is still computed.
    • transcript is present when the machine's last answered listing holds the conversation, absent when an answered listing lacks it, and unknown with no answered listing or no conversationId.
  5. outsidesessions:

    • ended.go: func LaunchFolder(home, cwd, stem, path string) (string, bool), an exported wrapper of launchFolder; nothing else changes.
    • inventory.go: func (i *Inventory) Held(machineKey string) (map[string]bool, bool) returns a copy of the latest successful probe's Held for that machine. Store it in probe where the ended scan already receives it.
  6. Doors (cmd/relay):

    • session_history_ops.go (new): builds the Index options from config.FreshSettings, outsideRun, matchOutsideProject, resolveOutsideProjectPaths and the inventory; historyOps.List(projectID).
    • session_history_routes.go (new): RegisterSessionHistoryRoutes(rr, ops) with rr.Handle(control.ClassExecute, "GET /api/session-history", ...). An unknown projectId answers an empty rows. A history not wired answers 503 history_unavailable.
    • frontend_server.go: build the index beside newOutsideInventory, start Run, register the routes in registerFrontendRoutes.
    • 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 (or Claude — <folder>), LAST ACTIVE, KIND, STATE, RESUME and ID. Row text is untrusted, so the table strips control characters as relay audit does.

File ownership

Dev (19 files):

  • internal/sessions/ledger/ledger.go: owner. relay#599 may add LinkConversation; relay#600 may add MissingSince, SetMissing and RemoveIfPurgeable. Nothing else.
  • internal/sessionhistory/history.go (new): owner. relay#599 may add Verify; 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 Claude Verify read.
  • internal/outsidesessions/ended.go: LaunchFolder only
  • internal/outsidesessions/inventory.go: Held and its stored map only
  • cmd/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 only
  • cmd/relay/admin_ops.go: one table line
  • cmd/relay/cli_verbs.go: one table line
  • docs/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 row
  • docs/cli.md: session history in the synopsis and its section
  • docs/events.md: session.history.scan
  • docs/FEATURES.md: new row G1.56 (below)
  • docs/THREAT-MODEL.md: one note under 3d: the execute holder 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 unchanged
  • CLAUDE.md: one row in "Where things are written down" for docs/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-history cli:relay session history.
  • Gate: none.
  • Proof: event:session.history.scan=ok#revision out:http:GET /api/session-history#.rows[].
  • Test: the e2e names below.

Paths

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, as Instance.boot reads it.
  • A scan: the session.history.scan event line (WaitEvent) with revision above the one read before the plant.
  • After a restart: Instance.Restart returns at ready, then the first session.history.scan event 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 sessionhistory files 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 shows transcript: "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 show transcript: "unknown".
  • TestHistoryDiscoveredAfterRestart asserts 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 in claude.go, history.go and ledger.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's LastActiveAt, else the record's Created.
    Amendment 35: Relay removes the rest with RemoveDiscovered, 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. The session.history.scan event gains evicted (a count).
    Amendment 37: The listing script prints one R line, the base64 folder name, for each folder it refuses and for the folder of each transcript it refuses. Listing gains Refused map[string]bool, keyed by folder name.
    Amendment 38: Absent is also false when a refused folder name equals outsidesessions.FolderName(directory) or starts with it. Such a row shows transcript: "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.
  • TestHistoryScanScope adds a symlinked project folder: the row of a record in it shows transcript: "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 the live rule: a dormant launched agent record with transcript: "absent" gives none, transcript_absent. See Session history: purge a record whose transcript is gone #600, Amendments 6 and 7.

Activity

  1. added
    enhancement
    task
    on Oct 23, 2026
  2. barelyworkingcode commented on Oct 23, 2026

    @barelyworkingcode
    OwnerAuthor

    Coordinator approval: inherits the approved epic's listed batches, 2026-10-22

  3. barelyworkingcode commented on Oct 23, 2026

    @barelyworkingcode
    OwnerAuthor

    Merged in #605 to epic/596-session-history.

  4. barelyworkingcode commented on Oct 23, 2026

    @barelyworkingcode
    OwnerAuthor

    Done in #605 (merged into epic/596-session-history).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementtask

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions