Skip to content

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

fix(claude): read the workspace from the transcript when the index omits it (#847)

Rudy Mizrahi Celekli91c84326bfcd
diff --git a/cli/beacon/internal/claudesession/claudesession_test.go b/cli/beacon/internal/claudesession/claudesession_test.go
index c5de9206..929fa83d 100644
--- a/cli/beacon/internal/claudesession/claudesession_test.go
+++ b/cli/beacon/internal/claudesession/claudesession_test.go
@@ -285,3 +285,44 @@ func boolString(v bool) string {
}
return "false"
}
+
+func TestListUsesRecordedWorkspaceWhenIndexDoesNotNameIt(t *testing.T) {
+ for _, tc := range []struct{ name, cwd, indexed, want string }{
+ {"recorded hyphenated workspace", "/work/my-project", "", "/work/my-project"},
+ {"index remains authoritative", "/work/my-project", "/indexed/project", "/indexed/project"},
+ {"older record without cwd", "", "", filepath.FromSlash("/work/my/project")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ root := t.TempDir()
+ project := filepath.Join(root, "-work-my-project")
+ path := filepath.Join(project, "sess-1.jsonl")
+ row := map[string]interface{}{"type": "user", "sessionId": "sess-1", "uuid": "u1", "message": map[string]interface{}{"role": "user", "content": "Review the project."}}
+ if tc.cwd != "" {
+ row["cwd"] = tc.cwd
+ }
+ data, err := json.Marshal(row)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, path, `{ "type":"file-history-snapshot", "snapshot":{} }`+"\n"+string(data)+"\n")
+ if tc.indexed != "" {
+ index, err := json.Marshal(map[string]interface{}{"version": 1, "entries": []interface{}{map[string]interface{}{"sessionId": "sess-1", "fullPath": path, "projectPath": tc.indexed}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeFile(t, filepath.Join(project, "sessions-index.json"), string(index))
+ }
+ store, err := NewStore(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(refs) != 1 || refs[0].ProjectPath != tc.want {
+ t.Fatalf("refs=%+v, want workspace %q", refs, tc.want)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/claudesession/head.go b/cli/beacon/internal/claudesession/head.go
new file mode 100644
index 00000000..00b467d9
--- /dev/null
+++ b/cli/beacon/internal/claudesession/head.go
@@ -0,0 +1,104 @@
+package claudesession
+
+import (
+ "bufio"
+ "encoding/json"
+ "io"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
+)
+
+// Bounds for reading the head of a transcript. Listing opens every transcript, so it reads only
+// enough to find where the session ran and what it was about.
+const (
+ headMaxLines = 64
+ headMaxBytes = 4 << 20
+ headMaxLineSize = 1 << 20
+)
+
+// Head is what the start of a transcript records about its session.
+type Head struct {
+ CWD string
+ GitBranch string
+ FirstPrompt string
+}
+
+// ReadHead reads where a Claude session ran, its branch 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. A missing or unreadable file yields an empty
+// Head.
+func ReadHead(path string) Head {
+ var head Head
+ f, err := sessionfs.Open(path)
+ if err != nil {
+ return head
+ }
+ defer f.Close()
+ reader := bufio.NewReaderSize(io.LimitReader(f, headMaxBytes), 64<<10)
+ for range headMaxLines {
+ line, status, _ := readLine(reader, headMaxLineSize)
+ if status == lineOK || status == linePartial {
+ head.consume(line)
+ if head.CWD != "" && head.GitBranch != "" && head.FirstPrompt != "" {
+ return head
+ }
+ }
+ if status != lineOK && status != lineOversized {
+ return head
+ }
+ }
+ return head
+}
+
+func (h *Head) 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 == "" && strings.TrimSpace(entry.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
+}
diff --git a/cli/beacon/internal/claudesession/head_test.go b/cli/beacon/internal/claudesession/head_test.go
new file mode 100644
index 00000000..19cfe874
--- /dev/null
+++ b/cli/beacon/internal/claudesession/head_test.go
@@ -0,0 +1,41 @@
+package claudesession
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestReadHeadSkipsAnOversizedLine(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "big.jsonl")
+ huge := `{"type":"assistant","message":{"content":"` + strings.Repeat("x", headMaxLineSize+10) + `"}}` + "\n"
+ writeFile(t, path, huge+`{"type":"user","cwd":"/after/huge","message":{"role":"user","content":"second line"}}`+"\n")
+ head := ReadHead(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 TestReadHeadStopsAfterTheLineBudget(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "long.jsonl")
+ var b strings.Builder
+ for range headMaxLines {
+ b.WriteString(`{"type":"attachment"}` + "\n")
+ }
+ b.WriteString(`{"type":"user","cwd":"/too/late"}` + "\n")
+ writeFile(t, path, b.String())
+ if head := ReadHead(path); head.CWD != "" {
+ t.Fatalf("head read past its %d-line budget: %+v", headMaxLines, head)
+ }
+}
+
+func TestReadHeadToleratesMissingAndMalformedFiles(t *testing.T) {
+ if head := ReadHead(filepath.Join(t.TempDir(), "missing.jsonl")); head != (Head{}) {
+ t.Fatalf("missing file head = %+v", head)
+ }
+ path := filepath.Join(t.TempDir(), "bad.jsonl")
+ writeFile(t, path, "not json\n{\"type\":\"user\",\"cwd\":\"/ok\"}")
+ if head := ReadHead(path); head.CWD != "/ok" {
+ t.Fatalf("malformed line must be skipped and an unterminated last line read, got %+v", head)
+ }
+}
diff --git a/cli/beacon/internal/claudesession/store.go b/cli/beacon/internal/claudesession/store.go
index 12e9d14f..131de87a 100644
--- a/cli/beacon/internal/claudesession/store.go
+++ b/cli/beacon/internal/claudesession/store.go
@@ -30,6 +30,9 @@ type SessionRef struct {
ParentSessionID string
Meta *SubagentMeta
Index *IndexEntry
+ // Head is the transcript head List read to find the workspace when the index did not name
+ // it; nil when the index supplied the workspace and the head was not read.
+ Head *Head
}
type Store struct {
@@ -119,6 +122,13 @@ func (s *Store) List() ([]SessionRef, error) {
}
ref.IsSidechain = idx.IsSidechain
}
+ if ref.Index == nil || ref.Index.ProjectPath == "" {
+ head := ReadHead(path)
+ ref.Head = &head
+ if head.CWD != "" {
+ ref.ProjectPath = head.CWD
+ }
+ }
if filepath.Base(filepath.Dir(path)) == "subagents" {
ref.IsSidechain = true
ref.ParentSessionID = filepath.Base(filepath.Dir(filepath.Dir(path)))
@@ -154,7 +164,7 @@ func decodeRecords(r io.Reader) ([]Record, Stats, error) {
var stats Stats
lineNo := 0
for {
- line, status, readErr := readLine(br)
+ line, status, readErr := readLine(br, MaxLineBytes)
switch status {
case lineEOF:
return records, stats, nil
@@ -200,15 +210,16 @@ const (
lineError // I/O error
)
-// readLine reads one JSONL line from br, handling oversized lines (consumed and
-// discarded so later lines are still reachable) and partial tails (unterminated
-// trailing fragments from a file still being written).
-func readLine(br *bufio.Reader) ([]byte, lineStatus, error) {
+// readLine reads one JSONL line of at most max bytes from br, handling oversized lines (consumed
+// and discarded so later lines are still reachable) and partial tails (unterminated trailing
+// fragments from a file still being written, returned with linePartial for a caller that wants
+// them).
+func readLine(br *bufio.Reader, max int) ([]byte, lineStatus, error) {
var buf []byte
oversized := false
for {
chunk, err := br.ReadSlice('\n')
- if oversized || len(buf)+len(chunk) > MaxLineBytes {
+ if oversized || len(buf)+len(chunk) > max {
oversized = true
buf = nil
} else {
@@ -222,7 +233,7 @@ func readLine(br *bufio.Reader) ([]byte, lineStatus, error) {
return nil, lineOversized, nil
}
if len(buf) > 0 {
- return nil, linePartial, nil
+ return bytes.TrimSuffix(buf, []byte("\r")), linePartial, nil
}
return nil, lineEOF, nil
}
diff --git a/cli/beacon/internal/handoff/claude.go b/cli/beacon/internal/handoff/claude.go
deleted file mode 100644
index 018b4493..00000000
--- a/cli/beacon/internal/handoff/claude.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package handoff
-
-import (
- "bufio"
- "encoding/json"
- "errors"
- "io"
- "os"
- "strings"
-)
-
-// Bounds for reading the head of a 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 {
- var head claudeHead
- scanHead(path, func(line []byte) bool {
- head.consume(line)
- return head.CWD != "" && head.GitBranch != "" && head.FirstPrompt != ""
- })
- return head
-}
-
-// scanHead passes the first lines of a JSONL transcript to consume until it returns true, within
-// the listing bounds above. A listing opens every transcript, so it reads only its head.
-func scanHead(path string, consume func(line []byte) (done bool)) {
- scanHeadLines(path, claudeHeadMaxLineSize, consume)
-}
-
-// scanHeadLines is scanHead for a transcript whose lines can run longer than a listing's usual
-// bound: a line up to maxLineSize is kept, and one past it is skipped. The byte budget grows with
-// the line bound, so the first long line can still be read whole.
-func scanHeadLines(path string, maxLineSize int, consume func(line []byte) (done bool)) {
- maxBytes := int64(claudeHeadMaxBytes)
- if int64(maxLineSize) > maxBytes {
- maxBytes = int64(maxLineSize) + int64(claudeHeadMaxBytes)
- }
- f, err := os.Open(path)
- if err != nil {
- return
- }
- defer f.Close()
-
- reader := bufio.NewReaderSize(io.LimitReader(f, maxBytes), 64<<10)
- for lines := 0; lines < claudeHeadMaxLines; lines++ {
- line, err := readBoundedLine(reader, maxLineSize)
- if len(line) > 0 && consume(line) {
- return
- }
- if err != nil {
- return
- }
- }
-}
-
-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
index 18cb639e..a70c9926 100644
--- a/cli/beacon/internal/handoff/claude_test.go
+++ b/cli/beacon/internal/handoff/claude_test.go
@@ -59,40 +59,6 @@ func TestClaudeIndexProjectPathWinsOverTheTranscript(t *testing.T) {
}
}
-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"} {
diff --git a/cli/beacon/internal/handoff/head.go b/cli/beacon/internal/handoff/head.go
new file mode 100644
index 00000000..b59eacf4
--- /dev/null
+++ b/cli/beacon/internal/handoff/head.go
@@ -0,0 +1,74 @@
+package handoff
+
+import (
+ "bufio"
+ "errors"
+ "io"
+ "os"
+ "strings"
+)
+
+// Bounds for reading the head of a 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 (
+ headMaxLines = 64
+ headMaxBytes = 4 << 20
+ headMaxLineSize = 1 << 20
+)
+
+// scanHead passes the first lines of a JSONL transcript to consume until it returns true, within
+// the listing bounds above. A listing opens every transcript, so it reads only its head.
+func scanHead(path string, consume func(line []byte) (done bool)) {
+ scanHeadLines(path, headMaxLineSize, consume)
+}
+
+// scanHeadLines is scanHead for a transcript whose lines can run longer than a listing's usual
+// bound: a line up to maxLineSize is kept, and one past it is skipped. The byte budget grows with
+// the line bound, so the first long line can still be read whole.
+func scanHeadLines(path string, maxLineSize int, consume func(line []byte) (done bool)) {
+ maxBytes := int64(headMaxBytes)
+ if int64(maxLineSize) > maxBytes {
+ maxBytes = int64(maxLineSize) + int64(headMaxBytes)
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return
+ }
+ defer f.Close()
+
+ reader := bufio.NewReaderSize(io.LimitReader(f, maxBytes), 64<<10)
+ for lines := 0; lines < headMaxLines; lines++ {
+ line, err := readBoundedLine(reader, maxLineSize)
+ if len(line) > 0 && consume(line) {
+ return
+ }
+ if err != nil {
+ return
+ }
+ }
+}
+
+// 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/sources.go b/cli/beacon/internal/handoff/sources.go
index d26990d8..d1163acd 100644
--- a/cli/beacon/internal/handoff/sources.go
+++ b/cli/beacon/internal/handoff/sources.go
@@ -51,16 +51,16 @@ func (s *claudeSource) List() ([]Session, error) {
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
+ if session.Title == "" || session.Branch == "" {
+ // List already read the head when the index did not name the workspace.
+ head := ref.Head
+ if head == nil {
+ read := claudesession.ReadHead(ref.Path)
+ head = &read
}
session.Title = firstNonEmpty(session.Title, oneLine(head.FirstPrompt))
session.Branch = firstNonEmpty(session.Branch, head.GitBranch)