Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Add beacon handoff list over local runtime session stores

Claude08a98e1ca24b
diff --git a/cli/beacon/cmd/handoff.go b/cli/beacon/cmd/handoff.go
new file mode 100644
index 00000000..3db8c98d
--- /dev/null
+++ b/cli/beacon/cmd/handoff.go
@@ -0,0 +1,162 @@
+package cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "text/tabwriter"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"
+)
+
+type handoffOptions struct {
+ jsonOutput bool
+ harness string
+ here bool
+ directory string
+ includeSubagents bool
+ limit int
+ dirs handoff.StoreDirs
+}
+
+var handoffOpts handoffOptions
+
+var handoffCmd = &cobra.Command{
+ Use: "handoff",
+ Short: "Pick up a local agent session again, in the same runtime or another one",
+ Long: `Pick up a local agent session again, in the same runtime or another one.
+
+Sessions are read from each runtime's own local session store (Claude Code, Codex CLI, OpenCode
+and Cline). Nothing is uploaded and no runtime file is modified.`,
+}
+
+var handoffListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List resumable local agent sessions, newest first",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runHandoffList,
+}
+
+// handoffSources is swapped by tests.
+var handoffSources = func(dirs handoff.StoreDirs) []handoff.Source { return handoff.DefaultSources(dirs) }
+
+func runHandoffList(cmd *cobra.Command, args []string) error {
+ harness, err := handoff.ParseHarness(handoffOpts.harness)
+ if err != nil {
+ return err
+ }
+ filter := handoff.Filter{
+ Harness: harness,
+ Directory: strings.TrimSpace(handoffOpts.directory),
+ IncludeSubagents: handoffOpts.includeSubagents,
+ Limit: handoffOpts.limit,
+ }
+ if handoffOpts.here {
+ if filter.Directory != "" {
+ return fmt.Errorf("--here and --dir cannot be combined")
+ }
+ wd, err := os.Getwd()
+ if err != nil {
+ return fmt.Errorf("resolve current directory: %w", err)
+ }
+ filter.Directory = wd
+ }
+ sessions, listErr := handoff.List(handoffSources(handoffOpts.dirs), filter)
+ out := cmd.OutOrStdout()
+ if handoffOpts.jsonOutput {
+ result := handoffListResult{Sessions: sessions}
+ if result.Sessions == nil {
+ result.Sessions = []handoff.Session{}
+ }
+ if listErr != nil {
+ result.Warnings = strings.Split(listErr.Error(), "\n")
+ }
+ encoder := json.NewEncoder(out)
+ encoder.SetIndent("", " ")
+ return encoder.Encode(result)
+ }
+ if listErr != nil {
+ for _, line := range strings.Split(listErr.Error(), "\n") {
+ fmt.Fprintf(cmd.ErrOrStderr(), "warning: could not read %s\n", line)
+ }
+ }
+ printHandoffSessions(out, sessions, time.Now())
+ return nil
+}
+
+type handoffListResult struct {
+ Sessions []handoff.Session `json:"sessions"`
+ Warnings []string `json:"warnings,omitempty"`
+}
+
+func printHandoffSessions(out io.Writer, sessions []handoff.Session, now time.Time) {
+ if len(sessions) == 0 {
+ fmt.Fprintln(out, "No resumable sessions found.")
+ return
+ }
+ w := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "ID\tRUNTIME\tUPDATED\tDIRECTORY\tTITLE")
+ for _, s := range sessions {
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", s.ID, handoffRuntimeLabel(s), handoffAge(s.UpdatedAt, now), s.Directory, truncateRunes(s.Title, 60))
+ }
+ w.Flush()
+}
+
+func handoffRuntimeLabel(s handoff.Session) string {
+ if s.Subagent {
+ return s.Harness + " (subagent)"
+ }
+ return s.Harness
+}
+
+func handoffAge(when, now time.Time) string {
+ if when.IsZero() {
+ return "-"
+ }
+ d := now.Sub(when)
+ switch {
+ case d < time.Minute:
+ return "just now"
+ case d < time.Hour:
+ return fmt.Sprintf("%dm ago", int(d.Minutes()))
+ case d < 48*time.Hour:
+ return fmt.Sprintf("%dh ago", int(d.Hours()))
+ default:
+ return when.Local().Format("2006-01-02")
+ }
+}
+
+func truncateRunes(s string, max int) string {
+ runes := []rune(s)
+ if len(runes) <= max {
+ return s
+ }
+ return string(runes[:max-1]) + "…"
+}
+
+func addHandoffStoreFlags(cmd *cobra.Command) {
+ f := cmd.Flags()
+ f.StringVar(&handoffOpts.harness, "harness", "", "Only this runtime: claude, codex, opencode or cline")
+ f.StringVar(&handoffOpts.dirs.ClaudeProjects, "claude-projects-dir", "", "Claude projects directory (default ~/.claude/projects)")
+ f.StringVar(&handoffOpts.dirs.Codex, "codex-dir", "", "Codex directory (default ~/.codex)")
+ f.StringVar(&handoffOpts.dirs.OpenCode, "opencode-dir", "", "OpenCode data directory or opencode.db path")
+ f.StringVar(&handoffOpts.dirs.Cline, "cline-dir", "", "Cline directory (default ~/.cline)")
+}
+
+func init() {
+ rootCmd.AddCommand(handoffCmd)
+ handoffCmd.AddCommand(handoffListCmd)
+ addHandoffStoreFlags(handoffListCmd)
+ f := handoffListCmd.Flags()
+ f.BoolVar(&handoffOpts.jsonOutput, "json", false, "Print sessions as JSON")
+ f.BoolVar(&handoffOpts.here, "here", false, "Only sessions that ran in the current directory or below it")
+ f.StringVar(&handoffOpts.directory, "dir", "", "Only sessions that ran in this directory or below it")
+ f.BoolVar(&handoffOpts.includeSubagents, "subagents", false, "Include subagent sessions")
+ f.IntVar(&handoffOpts.limit, "limit", 25, "Maximum sessions to list (0 for all)")
+}
diff --git a/cli/beacon/cmd/handoff_test.go b/cli/beacon/cmd/handoff_test.go
new file mode 100644
index 00000000..85e7692f
--- /dev/null
+++ b/cli/beacon/cmd/handoff_test.go
@@ -0,0 +1,233 @@
+package cmd
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/spf13/pflag"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"
+)
+
+type stubHandoffSource struct {
+ harness string
+ sessions []handoff.Session
+ err error
+}
+
+func (s stubHandoffSource) Harness() string { return s.harness }
+func (s stubHandoffSource) List() ([]handoff.Session, error) { return s.sessions, s.err }
+
+func stubHandoffSources(t *testing.T, sources ...handoff.Source) *handoff.StoreDirs {
+ t.Helper()
+ var seen handoff.StoreDirs
+ prev := handoffSources
+ handoffSources = func(dirs handoff.StoreDirs) []handoff.Source {
+ seen = dirs
+ return sources
+ }
+ t.Cleanup(func() { handoffSources = prev })
+ return &seen
+}
+
+// runHandoff executes `beacon handoff ...` through the root command with fresh flag values.
+func runHandoff(t *testing.T, args ...string) (string, string, error) {
+ t.Helper()
+ handoffOpts = handoffOptions{}
+ for _, cmd := range handoffCmd.Commands() {
+ cmd.Flags().VisitAll(func(f *pflag.Flag) {
+ _ = f.Value.Set(f.DefValue)
+ f.Changed = false
+ })
+ }
+ var stdout, stderr bytes.Buffer
+ rootCmd.SetOut(&stdout)
+ rootCmd.SetErr(&stderr)
+ rootCmd.SetArgs(append([]string{"handoff"}, args...))
+ t.Cleanup(func() {
+ rootCmd.SetOut(nil)
+ rootCmd.SetErr(nil)
+ rootCmd.SetArgs(nil)
+ })
+ err := rootCmd.Execute()
+ return stdout.String(), stderr.String(), err
+}
+
+func handoffFixtureSessions() []handoff.Source {
+ now := time.Now()
+ return []handoff.Source{
+ stubHandoffSource{harness: handoff.HarnessClaude, sessions: []handoff.Session{
+ {Harness: handoff.HarnessClaude, ID: "claude-1", Title: "Add a health endpoint", Directory: "/work/api", UpdatedAt: now.Add(-5 * time.Minute)},
+ {Harness: handoff.HarnessClaude, ID: "claude-sub", Directory: "/work/api", UpdatedAt: now.Add(-4 * time.Minute), Subagent: true, ParentID: "claude-1"},
+ }},
+ stubHandoffSource{harness: handoff.HarnessCodex, sessions: []handoff.Session{
+ {Harness: handoff.HarnessCodex, ID: "codex-1", Title: strings.Repeat("long title ", 10), Directory: "/work/web", UpdatedAt: now.Add(-3 * time.Hour)},
+ }},
+ }
+}
+
+func TestHandoffListCommandRegistered(t *testing.T) {
+ cmd, _, err := rootCmd.Find([]string{"handoff", "list"})
+ if err != nil || cmd == nil || cmd.Name() != "list" {
+ t.Fatalf("handoff list not registered: %v %#v", err, cmd)
+ }
+ for _, flag := range []string{"json", "harness", "here", "dir", "subagents", "limit", "claude-projects-dir", "codex-dir", "opencode-dir", "cline-dir"} {
+ if cmd.Flags().Lookup(flag) == nil {
+ t.Fatalf("handoff list missing --%s", flag)
+ }
+ }
+}
+
+func TestHandoffListPrintsATable(t *testing.T) {
+ stubHandoffSources(t, handoffFixtureSessions()...)
+ out, _, err := runHandoff(t, "list")
+ if err != nil {
+ t.Fatalf("handoff list: %v", err)
+ }
+ lines := strings.Split(strings.TrimSpace(out), "\n")
+ if len(lines) != 3 {
+ t.Fatalf("want a header and two sessions (subagent hidden), got:\n%s", out)
+ }
+ if !strings.HasPrefix(lines[0], "ID") || !strings.Contains(lines[0], "RUNTIME") {
+ t.Fatalf("header = %q", lines[0])
+ }
+ if !strings.HasPrefix(lines[1], "claude-1 ") || !strings.Contains(lines[1], "5m ago") || !strings.Contains(lines[1], "/work/api") {
+ t.Fatalf("newest session row = %q", lines[1])
+ }
+ if !strings.HasPrefix(lines[2], "codex-1 ") || !strings.Contains(lines[2], "3h ago") || !strings.HasSuffix(lines[2], "…") {
+ t.Fatalf("codex row = %q; long titles are cut with an ellipsis", lines[2])
+ }
+}
+
+func TestHandoffListJSONAndSubagents(t *testing.T) {
+ stubHandoffSources(t, handoffFixtureSessions()...)
+ out, _, err := runHandoff(t, "list", "--json", "--subagents")
+ if err != nil {
+ t.Fatalf("handoff list --json: %v", err)
+ }
+ var result handoffListResult
+ if err := json.Unmarshal([]byte(out), &result); err != nil {
+ t.Fatalf("output is not JSON: %v\n%s", err, out)
+ }
+ if len(result.Sessions) != 3 || result.Sessions[0].ID != "claude-sub" || !result.Sessions[0].Subagent {
+ t.Fatalf("sessions = %+v", result.Sessions)
+ }
+ if result.Warnings != nil {
+ t.Fatalf("warnings = %v, want none", result.Warnings)
+ }
+}
+
+func TestHandoffListJSONIsAnEmptyArrayNotNull(t *testing.T) {
+ stubHandoffSources(t)
+ out, _, err := runHandoff(t, "list", "--json")
+ if err != nil {
+ t.Fatalf("handoff list --json: %v", err)
+ }
+ if !strings.Contains(out, `"sessions": []`) {
+ t.Fatalf("empty listing must encode sessions as [], got %s", out)
+ }
+ text, _, _ := runHandoff(t, "list")
+ if strings.TrimSpace(text) != "No resumable sessions found." {
+ t.Fatalf("empty text listing = %q", text)
+ }
+}
+
+func TestHandoffListFilters(t *testing.T) {
+ stubHandoffSources(t, handoffFixtureSessions()...)
+ out, _, err := runHandoff(t, "list", "--harness", "codex")
+ if err != nil || !strings.Contains(out, "codex-1") || strings.Contains(out, "claude-1") {
+ t.Fatalf("--harness codex = %v\n%s", err, out)
+ }
+ out, _, err = runHandoff(t, "list", "--dir", "/work/api")
+ if err != nil || !strings.Contains(out, "claude-1") || strings.Contains(out, "codex-1") {
+ t.Fatalf("--dir /work/api = %v\n%s", err, out)
+ }
+ out, _, err = runHandoff(t, "list", "--limit", "1")
+ if err != nil || strings.Count(strings.TrimSpace(out), "\n") != 1 {
+ t.Fatalf("--limit 1 = %v\n%s", err, out)
+ }
+}
+
+func TestHandoffListHereUsesTheWorkingDirectory(t *testing.T) {
+ dir := t.TempDir()
+ t.Chdir(dir)
+ here, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stubHandoffSources(t, stubHandoffSource{harness: handoff.HarnessCline, sessions: []handoff.Session{
+ {Harness: handoff.HarnessCline, ID: "in-here", Directory: filepath.Join(here, "pkg")},
+ {Harness: handoff.HarnessCline, ID: "elsewhere", Directory: "/other"},
+ }})
+ out, _, err := runHandoff(t, "list", "--here")
+ if err != nil {
+ t.Fatalf("handoff list --here: %v", err)
+ }
+ if !strings.Contains(out, "in-here") || strings.Contains(out, "elsewhere") {
+ t.Fatalf("--here listing:\n%s", out)
+ }
+ if _, _, err := runHandoff(t, "list", "--here", "--dir", "/x"); err == nil || !strings.Contains(err.Error(), "cannot be combined") {
+ t.Fatalf("--here with --dir err = %v", err)
+ }
+}
+
+func TestHandoffListWarnsAboutUnreadableStores(t *testing.T) {
+ stubHandoffSources(t,
+ stubHandoffSource{harness: handoff.HarnessClaude, err: errors.New("permission denied")},
+ stubHandoffSource{harness: handoff.HarnessCodex, sessions: []handoff.Session{{Harness: handoff.HarnessCodex, ID: "codex-1"}}},
+ )
+ out, stderr, err := runHandoff(t, "list")
+ if err != nil {
+ t.Fatalf("an unreadable store must not fail the listing: %v", err)
+ }
+ if !strings.Contains(out, "codex-1") || !strings.Contains(stderr, "warning: could not read claude_code: permission denied") {
+ t.Fatalf("stdout:\n%s\nstderr:\n%s", out, stderr)
+ }
+ out, _, err = runHandoff(t, "list", "--json")
+ if err != nil || !strings.Contains(out, `"claude_code: permission denied"`) {
+ t.Fatalf("--json should carry the warning: %v\n%s", err, out)
+ }
+}
+
+func TestHandoffListRejectsUnknownRuntime(t *testing.T) {
+ stubHandoffSources(t)
+ if _, _, err := runHandoff(t, "list", "--harness", "cursor"); err == nil || !strings.Contains(err.Error(), "unsupported runtime") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestHandoffListPassesStoreDirectories(t *testing.T) {
+ seen := stubHandoffSources(t)
+ if _, _, err := runHandoff(t, "list", "--claude-projects-dir", "/c", "--codex-dir", "/x", "--opencode-dir", "/o", "--cline-dir", "/l"); err != nil {
+ t.Fatal(err)
+ }
+ want := handoff.StoreDirs{ClaudeProjects: "/c", Codex: "/x", OpenCode: "/o", Cline: "/l"}
+ if *seen != want {
+ t.Fatalf("store dirs = %+v, want %+v", *seen, want)
+ }
+}
+
+func TestHandoffAge(t *testing.T) {
+ now := time.Date(2026, 9, 25, 12, 0, 0, 0, time.UTC)
+ for _, tc := range []struct {
+ when time.Time
+ want string
+ }{
+ {time.Time{}, "-"},
+ {now.Add(-10 * time.Second), "just now"},
+ {now.Add(-59 * time.Minute), "59m ago"},
+ {now.Add(-47 * time.Hour), "47h ago"},
+ } {
+ if got := handoffAge(tc.when, now); got != tc.want {
+ t.Fatalf("handoffAge(%s) = %q, want %q", tc.when, got, tc.want)
+ }
+ }
+ if got := handoffAge(now.Add(-72*time.Hour), now); len(got) != len("2006-01-02") {
+ t.Fatalf("old sessions show a date, got %q", got)
+ }
+}
diff --git a/cli/beacon/internal/handoff/claude.go b/cli/beacon/internal/handoff/claude.go
new file mode 100644
index 00000000..0d1c395e
--- /dev/null
+++ b/cli/beacon/internal/handoff/claude.go
@@ -0,0 +1,128 @@
+package handoff
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "strings"
+)
+
+// Bounds for reading the head of a Claude transcript while listing. A listing opens every
+// transcript, so it reads only enough to find where the session ran and what it was about.
+const (
+ claudeHeadMaxLines = 64
+ claudeHeadMaxBytes = 4 << 20
+ claudeHeadMaxLineSize = 1 << 20
+)
+
+type claudeHead struct {
+ CWD string
+ GitBranch string
+ FirstPrompt string
+}
+
+// readClaudeHead reads where a Claude session ran and its first prompt from the start of its
+// transcript. Claude names each project directory after its path with every separator turned into
+// a dash, which cannot be decoded back when the path itself contains one, so a session without an
+// index entry needs the cwd its transcript records.
+func readClaudeHead(path string) claudeHead {
+ f, err := os.Open(path)
+ if err != nil {
+ return claudeHead{}
+ }
+ defer f.Close()
+
+ var head claudeHead
+ reader := bufio.NewReaderSize(io.LimitReader(f, claudeHeadMaxBytes), 64<<10)
+ for lines := 0; lines < claudeHeadMaxLines; lines++ {
+ line, err := readBoundedLine(reader, claudeHeadMaxLineSize)
+ if len(line) > 0 {
+ head.consume(line)
+ }
+ if head.CWD != "" && head.GitBranch != "" && head.FirstPrompt != "" {
+ break
+ }
+ if err != nil {
+ break
+ }
+ }
+ return head
+}
+
+func (h *claudeHead) consume(line []byte) {
+ var entry struct {
+ Type string `json:"type"`
+ CWD string `json:"cwd"`
+ GitBranch string `json:"gitBranch"`
+ IsMeta bool `json:"isMeta"`
+ Message struct {
+ Role string `json:"role"`
+ Content json.RawMessage `json:"content"`
+ } `json:"message"`
+ }
+ if json.Unmarshal(line, &entry) != nil {
+ return
+ }
+ if h.CWD == "" {
+ h.CWD = entry.CWD
+ }
+ if h.GitBranch == "" {
+ h.GitBranch = entry.GitBranch
+ }
+ if h.FirstPrompt == "" && entry.Type == "user" && !entry.IsMeta && entry.Message.Role == "user" {
+ h.FirstPrompt = promptText(entry.Message.Content)
+ }
+}
+
+// promptText returns the text a person typed, skipping tool results and the tagged blocks Claude
+// injects for slash commands and local command output.
+func promptText(content json.RawMessage) string {
+ var text string
+ if json.Unmarshal(content, &text) != nil {
+ var blocks []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ }
+ if json.Unmarshal(content, &blocks) != nil {
+ return ""
+ }
+ for _, block := range blocks {
+ if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
+ text = block.Text
+ break
+ }
+ }
+ }
+ text = strings.TrimSpace(text)
+ if strings.HasPrefix(text, "<") {
+ return ""
+ }
+ return text
+}
+
+// readBoundedLine returns the next line without its newline. A line longer than max is skipped
+// whole and returned empty, so one huge tool result cannot stall a listing.
+func readBoundedLine(r *bufio.Reader, max int) ([]byte, error) {
+ var line []byte
+ oversized := false
+ for {
+ chunk, err := r.ReadSlice('\n')
+ if !oversized {
+ if len(line)+len(chunk) > max {
+ oversized = true
+ line = nil
+ } else {
+ line = append(line, chunk...)
+ }
+ }
+ if errors.Is(err, bufio.ErrBufferFull) {
+ continue
+ }
+ if oversized {
+ return nil, err
+ }
+ return []byte(strings.TrimRight(string(line), "\r\n")), err
+ }
+}
diff --git a/cli/beacon/internal/handoff/claude_test.go b/cli/beacon/internal/handoff/claude_test.go
new file mode 100644
index 00000000..d465aa97
--- /dev/null
+++ b/cli/beacon/internal/handoff/claude_test.go
@@ -0,0 +1,104 @@
+package handoff
+
+import (
+ "bufio"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func claudeLine(t *testing.T, entry map[string]interface{}) string {
+ return jsonLine(t, entry)
+}
+
+// A project directory name turns every separator into a dash, so /work/my-app and /work/my/app
+// share one name. Without an index entry, only the transcript knows which it was.
+func TestClaudeSessionWithoutIndexUsesTheTranscriptCWD(t *testing.T) {
+ projects := filepath.Join(t.TempDir(), "projects")
+ path := filepath.Join(projects, "-work-my-app", "sess-dash.jsonl")
+ writeFixture(t, path, strings.Join([]string{
+ claudeLine(t, map[string]interface{}{"type": "queue-operation", "operation": "enqueue", "content": "ignored"}),
+ claudeLine(t, map[string]interface{}{"type": "user", "cwd": "/work/my-app", "gitBranch": "main", "message": map[string]interface{}{"role": "user", "content": "<command-name>/clear</command-name>"}}),
+ claudeLine(t, map[string]interface{}{"type": "user", "isMeta": true, "message": map[string]interface{}{"role": "user", "content": "caveat: meta"}}),
+ claudeLine(t, map[string]interface{}{"type": "user", "message": map[string]interface{}{"role": "user", "content": []interface{}{
+ map[string]interface{}{"type": "tool_result", "content": "not a prompt"},
+ }}}),
+ claudeLine(t, map[string]interface{}{"type": "user", "message": map[string]interface{}{"role": "user", "content": []interface{}{
+ map[string]interface{}{"type": "image"},
+ map[string]interface{}{"type": "text", "text": " make the build\nfaster "},
+ }}}),
+ }, ""))
+
+ sessions, err := (&claudeSource{dir: projects}).List()
+ if err != nil || len(sessions) != 1 {
+ t.Fatalf("List = %+v, %v", sessions, err)
+ }
+ got := sessions[0]
+ if got.Directory != "/work/my-app" {
+ t.Fatalf("directory = %q, want the transcript cwd rather than the lossy directory-name decode", got.Directory)
+ }
+ if got.Branch != "main" || got.Title != "make the build faster" {
+ t.Fatalf("branch/title = %q/%q", got.Branch, got.Title)
+ }
+}
+
+func TestClaudeIndexProjectPathWinsOverTheTranscript(t *testing.T) {
+ f := newStoreFixture(t)
+ path := filepath.Join(f.dirs.ClaudeProjects, "-work-api", "claude-sess-1.jsonl")
+ // The index says /work/api; a transcript cwd of a subdirectory the agent moved into must not
+ // override it.
+ writeFixture(t, path, claudeLine(t, map[string]interface{}{"type": "user", "cwd": "/work/api/cmd", "message": map[string]interface{}{"role": "user", "content": "hi"}}))
+ sessions, err := (&claudeSource{dir: f.dirs.ClaudeProjects}).List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range sessions {
+ if s.ID == "claude-sess-1" && s.Directory != "/work/api" {
+ t.Fatalf("directory = %q, want the index projectPath", s.Directory)
+ }
+ }
+}
+
+func TestClaudeHeadSkipsAnOversizedLine(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "big.jsonl")
+ huge := `{"type":"assistant","message":{"content":"` + strings.Repeat("x", claudeHeadMaxLineSize+10) + `"}}` + "\n"
+ writeFixture(t, path, huge+claudeLine(t, map[string]interface{}{"type": "user", "cwd": "/after/huge", "message": map[string]interface{}{"role": "user", "content": "second line"}}))
+ head := readClaudeHead(path)
+ if head.CWD != "/after/huge" || head.FirstPrompt != "second line" {
+ t.Fatalf("head = %+v; a line over the size cap must be skipped, not stop the read", head)
+ }
+}
+
+func TestClaudeHeadStopsAfterTheLineBudget(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "long.jsonl")
+ var b strings.Builder
+ for i := 0; i < claudeHeadMaxLines; i++ {
+ b.WriteString(`{"type":"attachment"}` + "\n")
+ }
+ b.WriteString(claudeLine(t, map[string]interface{}{"type": "user", "cwd": "/too/late"}))
+ writeFixture(t, path, b.String())
+ if head := readClaudeHead(path); head.CWD != "" {
+ t.Fatalf("head read past its %d-line budget: %+v", claudeHeadMaxLines, head)
+ }
+}
+
+func TestClaudeHeadToleratesMissingAndMalformedFiles(t *testing.T) {
+ if head := readClaudeHead(filepath.Join(t.TempDir(), "missing.jsonl")); head != (claudeHead{}) {
+ t.Fatalf("missing file head = %+v", head)
+ }
+ path := filepath.Join(t.TempDir(), "bad.jsonl")
+ writeFixture(t, path, "not json\n{\"type\":\"user\",\"cwd\":\"/ok\"}")
+ if head := readClaudeHead(path); head.CWD != "/ok" {
+ t.Fatalf("malformed line must be skipped and an unterminated last line read, got %+v", head)
+ }
+}
+
+func TestReadBoundedLine(t *testing.T) {
+ r := bufio.NewReaderSize(strings.NewReader("short\r\n"+strings.Repeat("y", 40)+"\nlast"), 16)
+ for _, want := range []string{"short", "", "last"} {
+ line, _ := readBoundedLine(r, 32)
+ if string(line) != want {
+ t.Fatalf("line = %q, want %q", line, want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/handoff/fixtures_test.go b/cli/beacon/internal/handoff/fixtures_test.go
new file mode 100644
index 00000000..5e7cdc04
--- /dev/null
+++ b/cli/beacon/internal/handoff/fixtures_test.go
@@ -0,0 +1,168 @@
+package handoff
+
+import (
+ "database/sql"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ _ "modernc.org/sqlite"
+)
+
+// Fixture timestamps, oldest first, so ordering assertions read in one direction.
+var (
+ clineUpdated = time.Date(2026, 9, 20, 9, 0, 0, 0, time.UTC)
+ codexUpdated = time.Date(2026, 9, 21, 9, 0, 0, 0, time.UTC)
+ openCodeUpdated = time.Date(2026, 9, 22, 9, 0, 0, 0, time.UTC)
+ claudeUpdated = time.Date(2026, 9, 23, 9, 0, 0, 0, time.UTC)
+)
+
+// storeFixture lays down one session store per supported runtime, in the formats each runtime
+// writes, under a temporary directory.
+type storeFixture struct {
+ root string
+ dirs StoreDirs
+}
+
+func newStoreFixture(t *testing.T) storeFixture {
+ t.Helper()
+ root := t.TempDir()
+ f := storeFixture{
+ root: root,
+ dirs: StoreDirs{
+ ClaudeProjects: filepath.Join(root, ".claude", "projects"),
+ Codex: filepath.Join(root, ".codex"),
+ OpenCode: filepath.Join(root, "opencode"),
+ Cline: filepath.Join(root, ".cline"),
+ },
+ }
+ f.writeClaude(t)
+ f.writeCodex(t)
+ f.writeOpenCode(t)
+ f.writeCline(t)
+ return f
+}
+
+func (f storeFixture) writeClaude(t *testing.T) {
+ t.Helper()
+ project := filepath.Join(f.dirs.ClaudeProjects, "-work-api")
+ main := filepath.Join(project, "claude-sess-1.jsonl")
+ writeFixture(t, main, jsonLine(t, map[string]interface{}{
+ "type": "user", "uuid": "u1", "sessionId": "claude-sess-1", "cwd": "/work/api", "gitBranch": "feat/health",
+ "timestamp": "2026-09-23T08:59:00.000Z",
+ "message": map[string]interface{}{"role": "user", "content": "add a health endpoint"},
+ }))
+ writeFixture(t, filepath.Join(project, "sessions-index.json"), mustJSON(t, map[string]interface{}{
+ "version": 1,
+ "entries": []interface{}{map[string]interface{}{
+ "sessionId": "claude-sess-1", "fullPath": main, "projectPath": "/work/api",
+ "gitBranch": "feat/health", "summary": "Add a\nhealth endpoint", "firstPrompt": "add a health endpoint",
+ }},
+ }))
+ setModTime(t, main, claudeUpdated)
+
+ sub := filepath.Join(project, "claude-sess-1", "subagents", "agent-a.jsonl")
+ writeFixture(t, sub, jsonLine(t, map[string]interface{}{
+ "type": "user", "uuid": "s1", "sessionId": "claude-sess-1", "isSidechain": true,
+ "message": map[string]interface{}{"role": "user", "content": "inspect the router"},
+ }))
+ setModTime(t, sub, claudeUpdated.Add(time.Minute))
+}
+
+func (f storeFixture) writeCodex(t *testing.T) {
+ t.Helper()
+ // A thread with two rollout files, both carrying the thread id.
+ older := filepath.Join(f.dirs.Codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T09-00-00-codex-thread-1.jsonl")
+ newer := filepath.Join(f.dirs.Codex, "sessions", "2026", "09", "21", "rollout-2026-09-21T09-00-00-codex-thread-1.jsonl")
+ for _, path := range []string{older, newer} {
+ writeFixture(t, path, jsonLine(t, map[string]interface{}{
+ "timestamp": "2026-09-21T09:00:00.000Z", "type": "session_meta",
+ "payload": map[string]interface{}{"id": "codex-thread-1", "session_id": "codex-thread-1", "cwd": "/work/web"},
+ }))
+ }
+ setModTime(t, older, codexUpdated.Add(-24*time.Hour))
+ setModTime(t, newer, codexUpdated)
+ writeFixture(t, filepath.Join(f.dirs.Codex, "session_index.jsonl"), jsonLine(t, map[string]interface{}{
+ "id": "codex-thread-1", "thread_name": "Fix the login form",
+ }))
+}
+
+func (f storeFixture) writeOpenCode(t *testing.T) {
+ t.Helper()
+ if err := os.MkdirAll(f.dirs.OpenCode, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", filepath.Join(f.dirs.OpenCode, "opencode.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ for _, stmt := range []string{
+ `CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT, directory TEXT, parent_id TEXT, time_created INTEGER, time_updated INTEGER)`,
+ `CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT)`,
+ `CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT)`,
+ } {
+ if _, err := db.Exec(stmt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ updated := openCodeUpdated.UnixMilli()
+ if _, err := db.Exec(`INSERT INTO session VALUES ('ses_parent', 'Refactor the cache', '/work/cache', NULL, ?, ?)`, updated-1000, updated); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec(`INSERT INTO session VALUES ('ses_child', 'Explore cache callers', '/work/cache', 'ses_parent', ?, ?)`, updated-500, updated-100); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (f storeFixture) writeCline(t *testing.T) {
+ t.Helper()
+ sessionDir := filepath.Join(f.dirs.Cline, "data", "sessions", "cline-task-1")
+ writeFixture(t, filepath.Join(sessionDir, "cline-task-1.json"), mustJSON(t, map[string]interface{}{
+ "task": "Write the release notes", "workspacePath": "/work/docs",
+ }))
+ messages := filepath.Join(sessionDir, "cline-task-1.messages.json")
+ writeFixture(t, messages, mustJSON(t, map[string]interface{}{"messages": []interface{}{
+ map[string]interface{}{"role": "user", "content": "Write the release notes", "ts": clineUpdated.UnixMilli()},
+ }}))
+ setModTime(t, messages, clineUpdated)
+
+ // The same task id in the older task history must not list twice.
+ history := filepath.Join(f.dirs.Cline, "data", "tasks", "cline-task-1", "api_conversation_history.json")
+ writeFixture(t, history, mustJSON(t, []interface{}{
+ map[string]interface{}{"role": "user", "content": "Write the release notes", "ts": clineUpdated.Add(time.Hour).UnixMilli()},
+ }))
+ setModTime(t, history, clineUpdated.Add(time.Hour))
+}
+
+func writeFixture(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func setModTime(t *testing.T, path string, when time.Time) {
+ t.Helper()
+ if err := os.Chtimes(path, when, when); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func mustJSON(t *testing.T, value interface{}) string {
+ t.Helper()
+ data, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func jsonLine(t *testing.T, value interface{}) string {
+ return mustJSON(t, value) + "\n"
+}
diff --git a/cli/beacon/internal/handoff/session.go b/cli/beacon/internal/handoff/session.go
new file mode 100644
index 00000000..e2a23128
--- /dev/null
+++ b/cli/beacon/internal/handoff/session.go
@@ -0,0 +1,167 @@
+// Package handoff finds agent sessions on this machine so they can be picked up again, in the same
+// runtime or a different one.
+//
+// A handoff reads the runtime's own session store, never Beacon's runtime log alone: the store is
+// what the runtime itself resumes from, and it keeps content that the runtime log truncates. Every
+// read is local and read-only.
+package handoff
+
+import (
+ "errors"
+ "fmt"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+)
+
+// Session is one resumable agent session as its runtime recorded it.
+type Session struct {
+ Harness string `json:"harness"`
+ ID string `json:"id"`
+ Title string `json:"title,omitempty"`
+ Directory string `json:"directory,omitempty"`
+ Branch string `json:"branch,omitempty"`
+ SourcePath string `json:"source_path,omitempty"`
+ // Store names which of a runtime's stores holds the session when it has more than one, such as
+ // Cline's CLI sessions and its older task history.
+ Store string `json:"store,omitempty"`
+ UpdatedAt time.Time `json:"updated_at"`
+ // Subagent marks a child session a runtime spawned for delegated work. Those are listed only on
+ // request, because resuming one resumes a fragment of the parent's task.
+ Subagent bool `json:"subagent,omitempty"`
+ ParentID string `json:"parent_id,omitempty"`
+}
+
+// Source lists the sessions one runtime has stored locally.
+type Source interface {
+ Harness() string
+ List() ([]Session, error)
+}
+
+// Filter narrows a session listing. The zero value lists every top-level session.
+type Filter struct {
+ Harness string
+ Directory string
+ IncludeSubagents bool
+ Limit int
+}
+
+// SourceError reports a runtime whose store could not be read. The other runtimes still list.
+type SourceError struct {
+ Harness string
+ Err error
+}
+
+func (e *SourceError) Error() string { return fmt.Sprintf("%s: %v", e.Harness, e.Err) }
+func (e *SourceError) Unwrap() error { return e.Err }
+
+// List returns the sessions every source has stored, newest first. A source that fails is reported
+// in the returned error while the sessions from the others are still returned.
+func List(sources []Source, filter Filter) ([]Session, error) {
+ var sessions []Session
+ var errs []error
+ for _, source := range sources {
+ if filter.Harness != "" && source.Harness() != filter.Harness {
+ continue
+ }
+ found, err := source.List()
+ if err != nil {
+ errs = append(errs, &SourceError{Harness: source.Harness(), Err: err})
+ }
+ for _, session := range found {
+ if session.ID == "" {
+ continue
+ }
+ if session.Subagent && !filter.IncludeSubagents {
+ continue
+ }
+ if filter.Directory != "" && !withinDirectory(session.Directory, filter.Directory) {
+ continue
+ }
+ sessions = append(sessions, session)
+ }
+ }
+ sort.SliceStable(sessions, func(i, j int) bool {
+ if !sessions[i].UpdatedAt.Equal(sessions[j].UpdatedAt) {
+ return sessions[i].UpdatedAt.After(sessions[j].UpdatedAt)
+ }
+ if sessions[i].Harness != sessions[j].Harness {
+ return sessions[i].Harness < sessions[j].Harness
+ }
+ return sessions[i].ID < sessions[j].ID
+ })
+ if filter.Limit > 0 && len(sessions) > filter.Limit {
+ sessions = sessions[:filter.Limit]
+ }
+ return sessions, errors.Join(errs...)
+}
+
+// MinPrefixLength is the shortest session id prefix Find accepts, so a stray short argument cannot
+// silently pick one of many sessions.
+const MinPrefixLength = 6
+
+// ErrNotFound reports that no stored session has the requested id.
+var ErrNotFound = errors.New("session not found")
+
+// AmbiguousError reports an id or prefix that names more than one stored session.
+type AmbiguousError struct {
+ ID string
+ Candidates []Session
+}
+
+func (e *AmbiguousError) Error() string {
+ names := make([]string, 0, len(e.Candidates))
+ for _, candidate := range e.Candidates {
+ names = append(names, candidate.Harness+" "+candidate.ID)
+ }
+ return fmt.Sprintf("session %q matches %d sessions (%s); pass the full id or --harness", e.ID, len(e.Candidates), strings.Join(names, ", "))
+}
+
+// Find returns the one session whose id is id, or, failing an exact match, the one session whose id
+// starts with id. Subagent sessions are searched too, since naming one explicitly is deliberate.
+func Find(sources []Source, harness, id string) (Session, error) {
+ id = strings.TrimSpace(id)
+ if id == "" {
+ return Session{}, errors.New("session id is required")
+ }
+ sessions, err := List(sources, Filter{Harness: harness, IncludeSubagents: true})
+ var exact, prefixed []Session
+ for _, session := range sessions {
+ switch {
+ case session.ID == id:
+ exact = append(exact, session)
+ case len(id) >= MinPrefixLength && strings.HasPrefix(session.ID, id):
+ prefixed = append(prefixed, session)
+ }
+ }
+ matches := exact
+ if len(matches) == 0 {
+ matches = prefixed
+ }
+ switch len(matches) {
+ case 1:
+ return matches[0], nil
+ case 0:
+ if err != nil {
+ return Session{}, fmt.Errorf("%w: %s (some session stores could not be read: %v)", ErrNotFound, id, err)
+ }
+ return Session{}, fmt.Errorf("%w: %s", ErrNotFound, id)
+ default:
+ return Session{}, &AmbiguousError{ID: id, Candidates: matches}
+ }
+}
+
+// withinDirectory reports whether a session recorded in dir ran in root or below it.
+func withinDirectory(dir, root string) bool {
+ if dir == "" {
+ return false
+ }
+ dir = filepath.Clean(dir)
+ root = filepath.Clean(root)
+ if dir == root {
+ return true
+ }
+ rel, err := filepath.Rel(root, dir)
+ return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
+}
diff --git a/cli/beacon/internal/handoff/session_test.go b/cli/beacon/internal/handoff/session_test.go
new file mode 100644
index 00000000..f269a8c1
--- /dev/null
+++ b/cli/beacon/internal/handoff/session_test.go
@@ -0,0 +1,296 @@
+package handoff
+
+import (
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+func fixtureSources(t *testing.T) (storeFixture, []Source) {
+ t.Helper()
+ // Cline also reads VS Code's global storage under HOME; keep it inside the test.
+ testenv.SetHome(t, t.TempDir())
+ f := newStoreFixture(t)
+ return f, DefaultSources(f.dirs)
+}
+
+func sessionKeys(sessions []Session) []string {
+ keys := make([]string, 0, len(sessions))
+ for _, s := range sessions {
+ keys = append(keys, s.Harness+"/"+s.ID)
+ }
+ return keys
+}
+
+func TestListReadsEveryRuntimeStoreNewestFirst(t *testing.T) {
+ _, sources := fixtureSources(t)
+ sessions, err := List(sources, Filter{})
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ got := strings.Join(sessionKeys(sessions), ",")
+ want := "claude_code/claude-sess-1,opencode/ses_parent,codex_cli/codex-thread-1,cline/cline-task-1"
+ if got != want {
+ t.Fatalf("sessions = %s\nwant %s", got, want)
+ }
+}
+
+func TestListCarriesEachRuntimesMetadata(t *testing.T) {
+ f, sources := fixtureSources(t)
+ sessions, err := List(sources, Filter{})
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ byHarness := map[string]Session{}
+ for _, s := range sessions {
+ byHarness[s.Harness] = s
+ }
+
+ claude := byHarness[HarnessClaude]
+ if claude.Directory != "/work/api" || claude.Branch != "feat/health" {
+ t.Fatalf("claude directory/branch = %q/%q", claude.Directory, claude.Branch)
+ }
+ if claude.Title != "Add a health endpoint" {
+ t.Fatalf("claude title = %q, want the index summary on one line", claude.Title)
+ }
+ if !claude.UpdatedAt.Equal(claudeUpdated) {
+ t.Fatalf("claude updated = %s, want %s", claude.UpdatedAt, claudeUpdated)
+ }
+ if claude.SourcePath != filepath.Join(f.dirs.ClaudeProjects, "-work-api", "claude-sess-1.jsonl") {
+ t.Fatalf("claude source = %q", claude.SourcePath)
+ }
+
+ codex := byHarness[HarnessCodex]
+ if codex.Directory != "/work/web" || codex.Title != "Fix the login form" {
+ t.Fatalf("codex = %+v", codex)
+ }
+ if !strings.Contains(codex.SourcePath, filepath.Join("2026", "09", "21")) || !codex.UpdatedAt.Equal(codexUpdated) {
+ t.Fatalf("codex should stand for its newest rollout file, got %q at %s", codex.SourcePath, codex.UpdatedAt)
+ }
+
+ openCode := byHarness[HarnessOpenCode]
+ if openCode.Directory != "/work/cache" || openCode.Title != "Refactor the cache" || openCode.Store != "sqlite" {
+ t.Fatalf("opencode = %+v", openCode)
+ }
+ if !openCode.UpdatedAt.Equal(openCodeUpdated) {
+ t.Fatalf("opencode updated = %s, want %s", openCode.UpdatedAt, openCodeUpdated)
+ }
+
+ cline := byHarness[HarnessCline]
+ if cline.Directory != "/work/docs" || cline.Title != "Write the release notes" {
+ t.Fatalf("cline = %+v", cline)
+ }
+ if cline.Store != "messages" {
+ t.Fatalf("cline store = %q; the CLI session must win over the task-history copy of the same id", cline.Store)
+ }
+}
+
+func TestListHidesSubagentsUnlessAsked(t *testing.T) {
+ _, sources := fixtureSources(t)
+ sessions, err := List(sources, Filter{IncludeSubagents: true})
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ var subagents []Session
+ for _, s := range sessions {
+ if s.Subagent {
+ subagents = append(subagents, s)
+ }
+ }
+ if len(subagents) != 2 {
+ t.Fatalf("subagents = %v, want the Claude and OpenCode children", sessionKeys(subagents))
+ }
+ for _, s := range subagents {
+ want := map[string]string{HarnessClaude: "claude-sess-1", HarnessOpenCode: "ses_parent"}[s.Harness]
+ if s.ParentID != want {
+ t.Fatalf("%s subagent parent = %q, want %q", s.Harness, s.ParentID, want)
+ }
+ }
+}
+
+func TestListFilters(t *testing.T) {
+ _, sources := fixtureSources(t)
+ for _, tc := range []struct {
+ name string
+ filter Filter
+ want string
+ }{
+ {"harness", Filter{Harness: HarnessCodex}, "codex_cli/codex-thread-1"},
+ {"directory", Filter{Directory: "/work/cache"}, "opencode/ses_parent"},
+ {"parent directory", Filter{Directory: "/work"}, "claude_code/claude-sess-1,opencode/ses_parent,codex_cli/codex-thread-1,cline/cline-task-1"},
+ {"sibling prefix is not a parent", Filter{Directory: "/work/ap"}, ""},
+ {"child of the session directory is not a match", Filter{Directory: "/work/api/cmd"}, ""},
+ {"limit", Filter{Limit: 2}, "claude_code/claude-sess-1,opencode/ses_parent"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ sessions, err := List(sources, tc.filter)
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ if got := strings.Join(sessionKeys(sessions), ","); got != tc.want {
+ t.Fatalf("sessions = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestListToleratesMissingStores(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ empty := t.TempDir()
+ sources := DefaultSources(StoreDirs{
+ ClaudeProjects: filepath.Join(empty, "claude"),
+ Codex: filepath.Join(empty, "codex"),
+ OpenCode: filepath.Join(empty, "opencode"),
+ Cline: filepath.Join(empty, "cline"),
+ })
+ sessions, err := List(sources, Filter{})
+ if err != nil || len(sessions) != 0 {
+ t.Fatalf("List over missing stores = %v, %v; want nothing and no error", sessions, err)
+ }
+}
+
+type fakeSource struct {
+ harness string
+ sessions []Session
+ err error
+}
+
+func (s fakeSource) Harness() string { return s.harness }
+func (s fakeSource) List() ([]Session, error) { return s.sessions, s.err }
+
+func TestListReportsAFailingStoreAndKeepsTheOthers(t *testing.T) {
+ broken := errors.New("permission denied")
+ sources := []Source{
+ fakeSource{harness: HarnessClaude, err: broken},
+ fakeSource{harness: HarnessCodex, sessions: []Session{{Harness: HarnessCodex, ID: "c1"}}},
+ }
+ sessions, err := List(sources, Filter{})
+ if len(sessions) != 1 || sessions[0].ID != "c1" {
+ t.Fatalf("sessions = %v, want the readable store's session", sessionKeys(sessions))
+ }
+ var sourceErr *SourceError
+ if !errors.As(err, &sourceErr) || sourceErr.Harness != HarnessClaude || !errors.Is(err, broken) {
+ t.Fatalf("err = %v, want a SourceError naming claude_code", err)
+ }
+}
+
+func TestListOrdersTiesDeterministically(t *testing.T) {
+ when := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)
+ sources := []Source{
+ fakeSource{harness: HarnessCodex, sessions: []Session{{Harness: HarnessCodex, ID: "b", UpdatedAt: when}, {Harness: HarnessCodex, ID: "a", UpdatedAt: when}}},
+ fakeSource{harness: HarnessClaude, sessions: []Session{{Harness: HarnessClaude, ID: "z", UpdatedAt: when}, {Harness: HarnessClaude, ID: ""}}},
+ }
+ sessions, _ := List(sources, Filter{})
+ if got := strings.Join(sessionKeys(sessions), ","); got != "claude_code/z,codex_cli/a,codex_cli/b" {
+ t.Fatalf("sessions = %s; ties break on harness then id, and id-less sessions are dropped", got)
+ }
+}
+
+func TestFind(t *testing.T) {
+ _, sources := fixtureSources(t)
+ for _, tc := range []struct {
+ name, harness, id, want string
+ }{
+ {"exact id", "", "codex-thread-1", "codex_cli/codex-thread-1"},
+ {"unique prefix", "", "claude-s", "claude_code/claude-sess-1"},
+ {"subagent by exact id", "", "ses_child", "opencode/ses_child"},
+ {"harness narrows", HarnessCline, "cline-task-1", "cline/cline-task-1"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := Find(sources, tc.harness, tc.id)
+ if err != nil {
+ t.Fatalf("Find: %v", err)
+ }
+ if key := got.Harness + "/" + got.ID; key != tc.want {
+ t.Fatalf("Find = %s, want %s", key, tc.want)
+ }
+ })
+ }
+}
+
+func TestFindRefusesAmbiguousShortAndUnknownIDs(t *testing.T) {
+ _, sources := fixtureSources(t)
+
+ if _, err := Find(sources, "", "ses_"); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("a prefix shorter than %d characters must not match, got %v", MinPrefixLength, err)
+ }
+ if _, err := Find(sources, "", "no-such-session"); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("unknown id err = %v, want ErrNotFound", err)
+ }
+ if _, err := Find(sources, HarnessCodex, "claude-sess-1"); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("--harness must scope the search, got %v", err)
+ }
+ if _, err := Find(sources, "", " "); err == nil {
+ t.Fatal("empty id must be rejected")
+ }
+
+ var ambiguous *AmbiguousError
+ _, err := Find(sources, "", "ses_pa")
+ if err != nil {
+ t.Fatalf("ses_pa names only the parent: %v", err)
+ }
+ dupes := []Source{
+ fakeSource{harness: HarnessClaude, sessions: []Session{{Harness: HarnessClaude, ID: "same-id-1"}}},
+ fakeSource{harness: HarnessCodex, sessions: []Session{{Harness: HarnessCodex, ID: "same-id-1"}}},
+ }
+ if _, err := Find(dupes, "", "same-id-1"); !errors.As(err, &ambiguous) || len(ambiguous.Candidates) != 2 {
+ t.Fatalf("an id two runtimes share must be ambiguous, got %v", err)
+ }
+ if !strings.Contains(ambiguous.Error(), "--harness") {
+ t.Fatalf("ambiguity error should say how to resolve it: %v", ambiguous)
+ }
+ prefixDupes := []Source{fakeSource{harness: HarnessCodex, sessions: []Session{{Harness: HarnessCodex, ID: "abcdef-1"}, {Harness: HarnessCodex, ID: "abcdef-2"}}}}
+ if _, err := Find(prefixDupes, "", "abcdef"); !errors.As(err, &ambiguous) {
+ t.Fatalf("a prefix naming two sessions must be ambiguous, got %v", err)
+ }
+ exactWins := []Source{fakeSource{harness: HarnessCodex, sessions: []Session{{Harness: HarnessCodex, ID: "abcdef"}, {Harness: HarnessCodex, ID: "abcdef-2"}}}}
+ if got, err := Find(exactWins, "", "abcdef"); err != nil || got.ID != "abcdef" {
+ t.Fatalf("an exact match must beat a longer prefix match, got %v, %v", got, err)
+ }
+}
+
+func TestFindMentionsUnreadableStoresWhenNothingMatches(t *testing.T) {
+ sources := []Source{fakeSource{harness: HarnessClaude, err: errors.New("disk on fire")}}
+ _, err := Find(sources, "", "missing-id")
+ if !errors.Is(err, ErrNotFound) || !strings.Contains(err.Error(), "disk on fire") {
+ t.Fatalf("err = %v, want not-found that names the unreadable store", err)
+ }
+}
+
+func TestParseHarness(t *testing.T) {
+ for in, want := range map[string]string{
+ "": "", "claude": HarnessClaude, "Claude-Code": HarnessClaude, "claude_code": HarnessClaude,
+ "codex": HarnessCodex, "codex_cli": HarnessCodex, " opencode ": HarnessOpenCode, "cline": HarnessCline,
+ } {
+ got, err := ParseHarness(in)
+ if err != nil || got != want {
+ t.Fatalf("ParseHarness(%q) = %q, %v; want %q", in, got, err, want)
+ }
+ }
+ if _, err := ParseHarness("cursor"); err == nil || !strings.Contains(err.Error(), "supported") {
+ t.Fatalf("unsupported runtime err = %v", err)
+ }
+}
+
+func TestWithinDirectory(t *testing.T) {
+ for _, tc := range []struct {
+ dir, root string
+ want bool
+ }{
+ {"/a/b", "/a/b", true},
+ {"/a/b/c", "/a/b", true},
+ {"/a/b/", "/a/b", true},
+ {"/a/bc", "/a/b", false},
+ {"/a", "/a/b", false},
+ {"", "/a", false},
+ {"/a/..b", "/a", true},
+ } {
+ if got := withinDirectory(tc.dir, tc.root); got != tc.want {
+ t.Fatalf("withinDirectory(%q, %q) = %v, want %v", tc.dir, tc.root, got, tc.want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/handoff/sources.go b/cli/beacon/internal/handoff/sources.go
new file mode 100644
index 00000000..7207598a
--- /dev/null
+++ b/cli/beacon/internal/handoff/sources.go
@@ -0,0 +1,271 @@
+package handoff
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/clinesession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/codexsession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/opencodesession"
+)
+
+// Harness names, as the endpoint event schema spells them.
+const (
+ HarnessClaude = claudesession.Harness
+ HarnessCodex = codexsession.Harness
+ HarnessOpenCode = opencodesession.Harness
+ HarnessCline = clinesession.Harness
+)
+
+// Harnesses lists the runtimes handoff supports, in display order.
+var Harnesses = []string{HarnessClaude, HarnessCodex, HarnessOpenCode, HarnessCline}
+
+var harnessAliases = map[string]string{
+ "claude": HarnessClaude,
+ "claude-code": HarnessClaude,
+ "claude_code": HarnessClaude,
+ "codex": HarnessCodex,
+ "codex-cli": HarnessCodex,
+ "codex_cli": HarnessCodex,
+ "opencode": HarnessOpenCode,
+ "cline": HarnessCline,
+}
+
+// ParseHarness resolves a user-supplied runtime name to its harness name. An empty name stays
+// empty, meaning every runtime.
+func ParseHarness(name string) (string, error) {
+ name = strings.ToLower(strings.TrimSpace(name))
+ if name == "" {
+ return "", nil
+ }
+ if harness, ok := harnessAliases[name]; ok {
+ return harness, nil
+ }
+ return "", fmt.Errorf("unsupported runtime %q (supported: claude, codex, opencode, cline)", name)
+}
+
+// StoreDirs overrides where each runtime's session store is read from. An empty field means the
+// runtime's default location.
+type StoreDirs struct {
+ ClaudeProjects string
+ Codex string
+ OpenCode string
+ Cline string
+}
+
+// DefaultSources returns a source for every supported runtime.
+func DefaultSources(dirs StoreDirs) []Source {
+ return []Source{
+ &claudeSource{dir: dirs.ClaudeProjects},
+ &codexSource{dir: dirs.Codex},
+ &openCodeSource{dir: dirs.OpenCode},
+ &clineSource{dir: dirs.Cline},
+ }
+}
+
+func unixMS(ms int64) time.Time {
+ if ms <= 0 {
+ return time.Time{}
+ }
+ return time.UnixMilli(ms).UTC()
+}
+
+func oneLine(s string) string {
+ return strings.Join(strings.Fields(s), " ")
+}
+
+type claudeSource struct{ dir string }
+
+func (s *claudeSource) Harness() string { return HarnessClaude }
+
+func (s *claudeSource) store() (*claudesession.Store, error) { return claudesession.NewStore(s.dir) }
+
+func (s *claudeSource) List() ([]Session, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ if !store.Exists() {
+ return nil, nil
+ }
+ refs, err := store.List()
+ if err != nil {
+ return nil, err
+ }
+ sessions := make([]Session, 0, len(refs))
+ for _, ref := range refs {
+ session := Session{
+ Harness: HarnessClaude,
+ ID: ref.ID,
+ Directory: ref.ProjectPath,
+ SourcePath: ref.Path,
+ UpdatedAt: unixMS(ref.ModTimeUnixMS),
+ Subagent: ref.IsSidechain,
+ ParentID: ref.ParentSessionID,
+ }
+ var indexPath string
+ if ref.Index != nil {
+ indexPath = ref.Index.ProjectPath
+ session.Title = oneLine(firstNonEmpty(ref.Index.Summary, ref.Index.FirstPrompt))
+ session.Branch = ref.Index.GitBranch
+ }
+ if indexPath == "" || session.Title == "" || session.Branch == "" {
+ head := readClaudeHead(ref.Path)
+ if indexPath == "" && head.CWD != "" {
+ session.Directory = head.CWD
+ }
+ session.Title = firstNonEmpty(session.Title, oneLine(head.FirstPrompt))
+ session.Branch = firstNonEmpty(session.Branch, head.GitBranch)
+ }
+ sessions = append(sessions, session)
+ }
+ return sessions, nil
+}
+
+type codexSource struct{ dir string }
+
+func (s *codexSource) Harness() string { return HarnessCodex }
+
+func (s *codexSource) store() (*codexsession.Store, error) { return codexsession.NewStore(s.dir) }
+
+func (s *codexSource) List() ([]Session, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ if !store.Exists() {
+ return nil, nil
+ }
+ refs, err := store.List()
+ if err != nil {
+ return nil, err
+ }
+ // A thread can own more than one rollout file, each carrying the thread's id. The newest file
+ // stands for the thread.
+ newest := map[string]codexsession.SessionRef{}
+ for _, ref := range refs {
+ if current, ok := newest[ref.ID]; !ok || ref.ModTimeUnixMS >= current.ModTimeUnixMS {
+ newest[ref.ID] = ref
+ }
+ }
+ sessions := make([]Session, 0, len(newest))
+ for _, ref := range newest {
+ session := Session{
+ Harness: HarnessCodex,
+ ID: ref.ID,
+ Directory: ref.Workspace,
+ SourcePath: ref.Path,
+ UpdatedAt: unixMS(ref.ModTimeUnixMS),
+ }
+ if ref.Index != nil {
+ session.Title = oneLine(ref.Index.ThreadName)
+ }
+ sessions = append(sessions, session)
+ }
+ sort.Slice(sessions, func(i, j int) bool { return sessions[i].ID < sessions[j].ID })
+ return sessions, nil
+}
+
+type openCodeSource struct{ dir string }
+
+func (s *openCodeSource) Harness() string { return HarnessOpenCode }
+
+func (s *openCodeSource) store() (*opencodesession.Store, error) {
+ return opencodesession.NewStore(s.dir)
+}
+
+func (s *openCodeSource) List() ([]Session, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ if !store.Exists() {
+ return nil, nil
+ }
+ // OpenCode reads two stores; List returns what it could read alongside any error.
+ refs, err := store.List()
+ sessions := make([]Session, 0, len(refs))
+ for _, ref := range refs {
+ sessions = append(sessions, Session{
+ Harness: HarnessOpenCode,
+ ID: ref.ID,
+ Title: oneLine(firstNonEmpty(ref.Title, ref.Preview)),
+ Directory: ref.Directory,
+ SourcePath: ref.SourcePath,
+ Store: string(ref.Kind),
+ UpdatedAt: unixMS(ref.UpdatedAtUnixMS),
+ Subagent: ref.RelationshipType == "subagent",
+ ParentID: relatedParent(ref.RelationshipType, ref.RelatedTo),
+ })
+ }
+ return sessions, err
+}
+
+type clineSource struct{ dir string }
+
+func (s *clineSource) Harness() string { return HarnessCline }
+
+func (s *clineSource) store() (*clinesession.Store, error) { return clinesession.NewStore(s.dir) }
+
+func (s *clineSource) List() ([]Session, error) {
+ store, err := s.store()
+ if err != nil {
+ return nil, err
+ }
+ if !store.Exists() {
+ return nil, nil
+ }
+ refs, err := store.List()
+ if err != nil {
+ return nil, err
+ }
+ // A task can be stored both as a CLI session and in the older task history under one id. The
+ // CLI session is the copy `cline --id` reopens, so it wins.
+ byID := map[string]Session{}
+ for _, ref := range refs {
+ // Kanban cards are Cline's board view of work, not sessions the CLI can reopen.
+ if ref.Kind == clinesession.SourceKanban {
+ continue
+ }
+ if prev, ok := byID[ref.ID]; ok && prev.Store == clinesession.SourceMessages {
+ continue
+ }
+ byID[ref.ID] = Session{
+ Harness: HarnessCline,
+ ID: ref.ID,
+ Title: oneLine(firstNonEmpty(ref.Title, ref.Preview)),
+ Directory: ref.Directory,
+ SourcePath: ref.SourcePath,
+ UpdatedAt: unixMS(ref.UpdatedAtUnixMS),
+ Store: ref.Kind,
+ Subagent: ref.RelationshipType == "subagent",
+ ParentID: relatedParent(ref.RelationshipType, ref.RelatedTo),
+ }
+ }
+ sessions := make([]Session, 0, len(byID))
+ for _, session := range byID {
+ sessions = append(sessions, session)
+ }
+ sort.Slice(sessions, func(i, j int) bool { return sessions[i].ID < sessions[j].ID })
+ return sessions, nil
+}
+
+func relatedParent(relationship, relatedTo string) string {
+ if relationship != "subagent" {
+ return ""
+ }
+ parent, _, _ := strings.Cut(relatedTo, "#")
+ return parent
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdx
new file mode 100644
index 00000000..af16bd10
--- /dev/null
+++ b/docs/cli/handoff.mdx
@@ -0,0 +1,48 @@
+---
+title: "beacon handoff"
+description: "Pick up a local agent session again, in the same runtime or another one"
+---
+
+## Command overview
+
+`beacon handoff` finds the agent sessions stored on this machine so you can pick one up again.
+
+```bash title="Command syntax"
+beacon handoff list [flags]
+```
+
+Sessions come from each runtime's own local session store, not from Beacon's runtime log. That store is what the runtime resumes from, and it keeps content the runtime log truncates. Every read is local and read-only: nothing is uploaded, and no runtime file is changed.
+
+## Supported runtimes
+
+| Runtime | Session store | `--harness` |
+|---------|---------------|-------------|
+| Claude Code | `~/.claude/projects` | `claude` |
+| Codex CLI | `~/.codex/sessions` | `codex` |
+| OpenCode | `~/.config/opencode` (SQLite and the legacy file store) | `opencode` |
+| Cline | `~/.cline/data` | `cline` |
+
+When a Codex thread has more than one rollout file, `beacon handoff` lists it once, under its newest file. Cline can hold the same task both as a CLI session and in its older task history; the CLI session is the copy that is listed. Cline kanban cards are not sessions and are not listed.
+
+## `beacon handoff list`
+
+Lists resumable sessions, newest first.
+
+```bash
+beacon handoff list
+beacon handoff list --here # sessions that ran in this directory or below it
+beacon handoff list --harness codex # one runtime
+beacon handoff list --json
+```
+
+| Flag | Description |
+|------|-------------|
+| `--harness` | Only this runtime: `claude`, `codex`, `opencode`, or `cline`. |
+| `--here` | Only sessions that ran in the current directory or below it. |
+| `--dir` | Only sessions that ran in this directory or below it. |
+| `--subagents` | Include subagent sessions. They are hidden by default, because resuming one resumes a fragment of its parent's task. |
+| `--limit` | Maximum sessions to list. Default `25`; `0` lists all. |
+| `--json` | Print `{"sessions": [...], "warnings": [...]}`. |
+| `--claude-projects-dir`, `--codex-dir`, `--opencode-dir`, `--cline-dir` | Read a runtime's store from a non-default location. |
+
+A store that cannot be read is reported as a warning (on stderr, or under `warnings` in JSON), and the sessions from the other runtimes are still listed.
diff --git a/docs/docs.json b/docs/docs.json
index 358bf4ff..7a29dad6 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -353,6 +353,7 @@
"cli/scan-ci-gates"
]
},
+ "cli/handoff",
"cli/token-usage",
"cli/version"
]