Skip to content

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

add cline session sync

Justin D'Souza621f932fcd75
diff --git a/cli/beacon/cmd/endpoint_cline.go b/cli/beacon/cmd/endpoint_cline.go
new file mode 100644
index 00000000..681fcbfb
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_cline.go
@@ -0,0 +1,227 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/clinesession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/spf13/cobra"
+)
+
+var endpointClineCmd = &cobra.Command{
+ Use: "cline",
+ Short: "Collect telemetry from Cline local sessions",
+ Long: `Collect endpoint telemetry from Cline's local session store.
+
+Beacon's normal Cline integration uses a managed plugin for live capture. This
+command reads Cline's committed local history files under ~/.cline and the VS
+Code extension task store so historical sessions and sessions that ran without
+Beacon's plugin can still be represented in the local endpoint log. Every emitted
+event is marked harness.collection_method=poll: Beacon sees what Cline already
+wrote, so nothing here can hold or deny a tool call.`,
+}
+
+var endpointClineSyncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Read new Cline session records into the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointClineSync,
+}
+
+var endpointClineStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show Cline local sessions and collection progress",
+ SilenceUsage: true,
+ RunE: runEndpointClineStatus,
+}
+
+var endpointClineOpts struct {
+ clineDir string
+ statePath string
+ logPath string
+ print bool
+ watch bool
+ interval time.Duration
+}
+
+func init() {
+ endpointCmd.AddCommand(endpointClineCmd)
+ endpointClineCmd.AddCommand(endpointClineSyncCmd)
+ endpointClineCmd.AddCommand(endpointClineStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointClineSyncCmd, endpointClineStatusCmd} {
+ f := c.Flags()
+ f.StringVar(&endpointClineOpts.clineDir, "cline-dir", "", "Cline directory (default ~/.cline)")
+ f.StringVar(&endpointClineOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/cline-sessions.json)")
+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")
+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")
+ }
+
+ sync := endpointClineSyncCmd.Flags()
+ sync.StringVar(&endpointClineOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ sync.BoolVar(&endpointClineOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")
+ sync.BoolVar(&endpointClineOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")
+ sync.DurationVar(&endpointClineOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+}
+
+func runEndpointClineSync(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ opts := clinesession.CollectOptions{
+ ClineDir: endpointClineOpts.clineDir,
+ Print: endpointClineOpts.print,
+ Out: cmd.OutOrStdout(),
+ Write: !endpointClineOpts.print,
+ UserMode: userMode,
+ }
+ if !endpointClineOpts.print {
+ opts.StatePath = resolveClineStatePath(endpointClineOpts.statePath, userMode)
+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointClineOpts.logPath).EffectiveLogPath
+ }
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if endpointClineOpts.watch && !endpointClineOpts.print {
+ return watchCline(ctx, cmd, opts)
+ }
+ summary, err := clinesession.CollectOnce(opts)
+ reportClineSweep(cmd, summary)
+ return err
+}
+
+func watchCline(ctx context.Context, cmd *cobra.Command, opts clinesession.CollectOptions) error {
+ interval := endpointClineOpts.interval
+ if interval < 5*time.Second {
+ interval = 5 * time.Second
+ }
+ for {
+ summary, err := clinesession.CollectOnce(opts)
+ if err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "cline sync error: %v\n", err)
+ }
+ reportClineSweep(cmd, summary)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ }
+}
+
+func reportClineSweep(cmd *cobra.Command, summary clinesession.Summary) {
+ if endpointClineOpts.print {
+ return
+ }
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
+ return
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "cline sync: %d traces, %d changed, %d events, %d errors\n",
+ summary.Traces, summary.TracesChanged, summary.EventsEmitted, summary.Errors)
+}
+
+type clineStatusRef struct {
+ ID string `json:"id"`
+ Source string `json:"source"`
+ Workspace string `json:"workspace,omitempty"`
+ UpdatedAt string `json:"updated_at,omitempty"`
+ Collected bool `json:"collected"`
+ EventsRead int `json:"events_read"`
+ SizeBytes int64 `json:"size_bytes"`
+ SourcePath string `json:"source_path,omitempty"`
+}
+
+type clineStatusReport struct {
+ ClineDir string `json:"cline_dir"`
+ SessionsDir string `json:"sessions_dir"`
+ KanbanDir string `json:"kanban_workspaces_dir"`
+ TasksDirs []string `json:"tasks_dirs"`
+ Present bool `json:"present"`
+ StatePath string `json:"state_path,omitempty"`
+ Traces []clineStatusRef `json:"traces"`
+}
+
+func runEndpointClineStatus(cmd *cobra.Command, args []string) error {
+ store, err := clinesession.NewStore(endpointClineOpts.clineDir)
+ if err != nil {
+ return err
+ }
+ statePath := resolveClineStatePath(endpointClineOpts.statePath, endpointUserMode())
+ state, err := clinesession.LoadState(statePath)
+ if err != nil {
+ return err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return err
+ }
+ report := clineStatusReport{
+ ClineDir: store.ClineDir,
+ SessionsDir: store.SessionsDir,
+ KanbanDir: store.KanbanWorkspacesDir,
+ TasksDirs: store.TasksDirs,
+ Present: store.Exists(),
+ StatePath: statePath,
+ Traces: make([]clineStatusRef, 0, len(refs)),
+ }
+ for _, ref := range refs {
+ cursor := state.Traces[ref.Kind+":"+ref.ID]
+ status := clineStatusRef{
+ ID: ref.ID,
+ Source: ref.Kind,
+ Workspace: ref.Directory,
+ Collected: cursor != nil && cursor.UpdatedAtMS >= ref.UpdatedAtUnixMS,
+ SizeBytes: ref.SizeBytes,
+ SourcePath: ref.SourcePath,
+ }
+ if ref.UpdatedAtUnixMS > 0 {
+ status.UpdatedAt = time.UnixMilli(ref.UpdatedAtUnixMS).UTC().Format(time.RFC3339)
+ }
+ if cursor != nil {
+ status.EventsRead = cursor.LastOrder
+ }
+ report.Traces = append(report.Traces, status)
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)
+ }
+ if !report.Present {
+ fmt.Fprintf(cmd.OutOrStdout(), "Cline session store not found at %s\n", report.ClineDir)
+ return nil
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "Cline session store: %s\n", report.ClineDir)
+ fmt.Fprintf(cmd.OutOrStdout(), "State: %s\n", report.StatePath)
+ for _, trace := range report.Traces {
+ collected := "pending"
+ if trace.Collected {
+ collected = "collected"
+ }
+ updated := trace.UpdatedAt
+ if updated == "" {
+ updated = "unknown"
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), " %s [%s] %s events=%d updated=%s", trace.ID, trace.Source, collected, trace.EventsRead, updated)
+ if trace.Workspace != "" {
+ fmt.Fprintf(cmd.OutOrStdout(), " workspace=%s", trace.Workspace)
+ }
+ fmt.Fprintln(cmd.OutOrStdout())
+ }
+ return nil
+}
+
+func resolveClineStatePath(path string, userMode bool) string {
+ if strings.TrimSpace(path) != "" {
+ return path
+ }
+ base := filepath.Join("/var", "lib", "beacon", "endpoint", "state")
+ if userMode {
+ base = filepath.Dir(clinesession.DefaultStatePath())
+ }
+ return filepath.Join(base, "cline-sessions.json")
+}
diff --git a/cli/beacon/internal/clinesession/collect.go b/cli/beacon/internal/clinesession/collect.go
new file mode 100644
index 00000000..f541b998
--- /dev/null
+++ b/cli/beacon/internal/clinesession/collect.go
@@ -0,0 +1,196 @@
+package clinesession
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+const StateVersion = 1
+
+type Cursor struct {
+ LastOrder int `json:"last_order"`
+ UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`
+ Started bool `json:"started"`
+}
+
+type State struct {
+ Version int `json:"version"`
+ Traces map[string]*Cursor `json:"traces"`
+}
+
+func LoadState(path string) (*State, error) {
+ state := &State{Version: StateVersion, Traces: map[string]*Cursor{}}
+ if strings.TrimSpace(path) == "" {
+ return state, nil
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return state, nil
+ }
+ return nil, err
+ }
+ var stored State
+ if err := json.Unmarshal(data, &stored); err != nil {
+ return nil, fmt.Errorf("read Cline collector state %s: %w", path, err)
+ }
+ if stored.Version != StateVersion || stored.Traces == nil {
+ return state, nil
+ }
+ return &stored, nil
+}
+
+func (s *State) Save(path string) error {
+ if strings.TrimSpace(path) == "" {
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ s.Version = StateVersion
+ data, err := json.MarshalIndent(s, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, 0o600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+func (s *State) cursor(ref TraceRef) *Cursor {
+ if s.Traces == nil {
+ s.Traces = map[string]*Cursor{}
+ }
+ key := ref.Kind + ":" + ref.ID
+ cursor := s.Traces[key]
+ if cursor == nil {
+ cursor = &Cursor{}
+ s.Traces[key] = cursor
+ }
+ return cursor
+}
+
+func DefaultStatePath() string {
+ base := filepath.Join(os.TempDir(), "beacon")
+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
+ base = filepath.Join(home, ".beacon")
+ }
+ return filepath.Join(base, "endpoint", "state", "cline-sessions.json")
+}
+
+type CollectOptions struct {
+ ClineDir string
+ StatePath string
+ Write bool
+ LogPath string
+ UserMode bool
+ Print bool
+ Out io.Writer
+}
+
+type Summary struct {
+ Traces int `json:"traces"`
+ TracesChanged int `json:"traces_changed"`
+ EventsEmitted int `json:"events_emitted"`
+ Errors int `json:"errors"`
+}
+
+func CollectOnce(opts CollectOptions) (summary Summary, err error) {
+ store, err := NewStore(opts.ClineDir)
+ if err != nil {
+ return summary, err
+ }
+ refs, err := store.List()
+ if err != nil {
+ return summary, err
+ }
+ summary.Traces = len(refs)
+ state, err := LoadState(opts.StatePath)
+ if err != nil {
+ return summary, err
+ }
+ defer func() {
+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {
+ err = fmt.Errorf("save Cline collector state: %w", saveErr)
+ }
+ }()
+
+ var errs []error
+ for _, ref := range refs {
+ changed, collectErr := collectTrace(store, ref, state, opts, &summary)
+ if collectErr != nil {
+ summary.Errors++
+ errs = append(errs, fmt.Errorf("Cline trace %s: %w", ref.ID, collectErr))
+ continue
+ }
+ if changed {
+ summary.TracesChanged++
+ }
+ }
+ if len(errs) > 0 {
+ return summary, errors.Join(errs...)
+ }
+ return summary, nil
+}
+
+func collectTrace(store *Store, ref TraceRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {
+ cursor := state.cursor(ref)
+ if ref.UpdatedAtUnixMS > 0 && ref.UpdatedAtUnixMS <= cursor.UpdatedAtMS {
+ return false, nil
+ }
+ records, err := store.Read(ref)
+ if err != nil {
+ return false, err
+ }
+ mapped := MapTrace(ref, records, MapOptions{MinOrder: cursor.LastOrder, SkipStarted: cursor.Started})
+ if len(mapped) == 0 {
+ if len(records) > 0 && records[len(records)-1].Order > cursor.LastOrder {
+ cursor.LastOrder = records[len(records)-1].Order
+ }
+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS
+ return false, nil
+ }
+ for i, item := range mapped {
+ if err := emit(item.Event, opts); err != nil {
+ if i > 0 {
+ cursor.LastOrder = mapped[i-1].SourceOrder
+ }
+ return true, err
+ }
+ cursor.LastOrder = item.SourceOrder
+ if item.Event.Event.Action == "session.started" {
+ cursor.Started = true
+ }
+ summary.EventsEmitted++
+ }
+ cursor.UpdatedAtMS = ref.UpdatedAtUnixMS
+ return true, nil
+}
+
+func emit(event schema.Event, opts CollectOptions) error {
+ if opts.Print && opts.Out != nil {
+ data, err := json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {
+ return err
+ }
+ }
+ if opts.Write {
+ if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/cli/beacon/internal/clinesession/helpers.go b/cli/beacon/internal/clinesession/helpers.go
new file mode 100644
index 00000000..e7ea4366
--- /dev/null
+++ b/cli/beacon/internal/clinesession/helpers.go
@@ -0,0 +1,443 @@
+package clinesession
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+)
+
+func RecordsFromEntries(ref TraceRef, entries []Entry) []Record {
+ var records []Record
+ calls := map[string]toolState{}
+ order := 1
+ var lastModel string
+ for _, entry := range entries {
+ role := strings.ToLower(strings.TrimSpace(entry.Role))
+ if role != "user" && role != "assistant" {
+ continue
+ }
+ model := firstNonEmpty(entry.ModelID, entry.Model, stringValue(entry.ModelInfo["modelId"]), stringValue(entry.ModelInfo["model"]), stringValue(entry.ModelInfo["id"]), lastModel)
+ if model != "" {
+ lastModel = model
+ }
+ ts := parseTimestampMS(entry.Timestamp, ref.UpdatedAtUnixMS)
+ before := len(records)
+ for _, block := range normalizeContentBlocks(entry.Content, entry.Text, entry.Message) {
+ record, more := recordFromContentBlock(role, block, calls, entry, model, ts, order)
+ if record != nil {
+ records = append(records, *record)
+ order++
+ }
+ for _, extra := range more {
+ extra.Order = order
+ records = append(records, extra)
+ order++
+ }
+ }
+ if len(records) == before {
+ text := extractVisibleText(role, firstNonEmpty(extractText(entry.Content), entry.Text, entry.Message))
+ if text != "" {
+ typ := "agent_text"
+ if role == "user" {
+ typ = "user_message"
+ }
+ records = append(records, Record{Order: order, Type: typ, TimestampMS: ts, Content: text, ModelID: model, Raw: entry.Raw})
+ order++
+ }
+ }
+ if role == "assistant" {
+ usage := tokenUsage(firstNonNil(entry.Metrics, entry.Usage))
+ if usage != nil {
+ for i := len(records) - 1; i >= before; i-- {
+ if records[i].Type == "agent_text" || records[i].Type == "agent_reasoning" || records[i].Type == "tool_call" {
+ records[i].Tokens = usage
+ break
+ }
+ }
+ }
+ }
+ }
+ return records
+}
+
+func recordFromContentBlock(role string, block interface{}, calls map[string]toolState, entry Entry, model string, ts int64, order int) (*Record, []Record) {
+ if text, ok := block.(string); ok {
+ return recordFromText(role, text, calls, entry, model, ts, order), nil
+ }
+ obj, ok := block.(map[string]interface{})
+ if !ok || obj == nil {
+ return nil, nil
+ }
+ typ := strings.ToLower(strings.TrimSpace(stringValue(obj["type"])))
+ if typ == "" || typ == "text" {
+ text := firstNonEmpty(extractText(obj["text"]), extractText(obj["content"]), extractText(obj["value"]), extractText(obj["message"]))
+ return recordFromText(role, text, calls, entry, model, ts, order), nil
+ }
+ if typ == "thinking" || typ == "reasoning" || typ == "redacted_thinking" {
+ text := firstNonEmpty(extractText(obj["thinking"]), extractText(obj["text"]), extractText(obj["content"]))
+ if role == "assistant" && strings.TrimSpace(text) != "" {
+ return &Record{Order: order, Type: "agent_reasoning", TimestampMS: ts, Content: text, ModelID: model, Raw: entry.Raw}, nil
+ }
+ return nil, nil
+ }
+ if typ == "tool_use" || typ == "tool-call" || typ == "tool_call" {
+ callID := firstNonEmpty(stringValue(obj["id"]), stringValue(obj["tool_use_id"]), stringValue(obj["callId"]), fmt.Sprintf("entry-%d-call-%d", entry.Order, order))
+ name := firstNonEmpty(stringValue(obj["name"]), stringValue(obj["toolName"]), "unknown")
+ args := parseToolArgs(firstNonNil(obj["input"], obj["args"], obj["arguments"]))
+ calls[callID] = toolState{Name: name, Args: args}
+ record := &Record{Order: order, Type: "tool_call", TimestampMS: ts, ModelID: model, ToolName: name, CallID: callID, Args: args, Raw: entry.Raw}
+ var extra []Record
+ if role == "assistant" {
+ if text := assistantToolMessage(name, args); text != "" {
+ extra = append(extra, Record{Type: "agent_text", TimestampMS: ts, Content: text, ModelID: model, Raw: entry.Raw})
+ }
+ }
+ return record, extra
+ }
+ if typ == "tool_result" || typ == "tool-result" || typ == "tool_response" {
+ callID := firstNonEmpty(stringValue(obj["tool_use_id"]), stringValue(obj["callId"]), stringValue(obj["id"]), fmt.Sprintf("entry-%d-call", entry.Order))
+ state := calls[callID]
+ name := firstNonEmpty(state.Name, stringValue(obj["name"]), stringValue(obj["toolName"]), "unknown")
+ args := state.Args
+ if args == nil {
+ args = map[string]interface{}{}
+ }
+ output := firstNonNil(obj["content"], obj["output"], obj["result"])
+ outputText := extractToolResultOutput(output)
+ status := "success"
+ if obj["is_error"] == true || strings.ToLower(stringValue(obj["status"])) == "error" {
+ status = "error"
+ }
+ delete(calls, callID)
+ record := &Record{Order: order, Type: "tool_result", TimestampMS: ts, ModelID: model, ToolName: name, CallID: callID, Args: args, Output: output, OutputText: outputText, Status: status, Raw: entry.Raw}
+ var extra []Record
+ if role == "user" && name == "attempt_completion" {
+ if feedback := extractTaggedText(outputText, "feedback"); feedback != "" {
+ extra = append(extra, Record{Type: "user_message", TimestampMS: ts, Content: feedback, ModelID: model, Raw: entry.Raw})
+ }
+ }
+ return record, extra
+ }
+ return nil, nil
+}
+
+func recordFromText(role, text string, calls map[string]toolState, entry Entry, model string, ts int64, order int) *Record {
+ if role == "user" {
+ if result := parseTextToolResult(text, calls, fmt.Sprintf("entry-%d-call", entry.Order)); result != nil {
+ return &Record{Order: order, Type: "tool_result", TimestampMS: ts, ModelID: model, ToolName: result.ToolName, CallID: result.CallID, OutputText: result.Output, Output: result.Output, Status: "success", Raw: entry.Raw}
+ }
+ }
+ visible := extractVisibleText(role, text)
+ if visible == "" {
+ return nil
+ }
+ typ := "agent_text"
+ if role == "user" {
+ typ = "user_message"
+ }
+ return &Record{Order: order, Type: typ, TimestampMS: ts, Content: visible, ModelID: model, Raw: entry.Raw}
+}
+
+type toolState struct {
+ Name string
+ Args map[string]interface{}
+}
+
+type parsedTextResult struct {
+ CallID string
+ ToolName string
+ Output string
+}
+
+func parseTextToolResult(text string, calls map[string]toolState, fallbackID string) *parsedTextResult {
+ text = strings.TrimSpace(text)
+ if !strings.HasPrefix(text, "[") {
+ return nil
+ }
+ end := strings.Index(text, "]")
+ if end <= 1 {
+ return nil
+ }
+ rest := strings.TrimSpace(text[end+1:])
+ if !strings.HasPrefix(rest, "Result:") {
+ return nil
+ }
+ name := text[1:end]
+ if idx := strings.Index(strings.ToLower(name), " for "); idx > 0 {
+ name = name[:idx]
+ }
+ name = strings.TrimSpace(name)
+ callID := fallbackID
+ for id, tool := range calls {
+ if normalizeToolKey(tool.Name) == normalizeToolKey(name) {
+ callID = id
+ name = tool.Name
+ break
+ }
+ }
+ return &parsedTextResult{CallID: callID, ToolName: name, Output: strings.TrimSpace(strings.TrimPrefix(rest, "Result:"))}
+}
+
+func normalizeToolKey(value string) string {
+ var b strings.Builder
+ for _, r := range strings.ToLower(value) {
+ if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+func normalizeContentBlocks(values ...interface{}) []interface{} {
+ for _, value := range values {
+ switch v := value.(type) {
+ case nil:
+ continue
+ case []interface{}:
+ return v
+ case string:
+ if strings.TrimSpace(v) != "" {
+ return []interface{}{v}
+ }
+ default:
+ return []interface{}{v}
+ }
+ }
+ return nil
+}
+
+func extractVisibleText(role, text string) string {
+ text = strings.TrimSpace(text)
+ if text == "" {
+ return ""
+ }
+ if role == "assistant" {
+ return text
+ }
+ for _, tag := range []string{"user_message", "user_input", "feedback", "task"} {
+ if tagged := extractTaggedText(text, tag); tagged != "" {
+ return tagged
+ }
+ }
+ if idx := strings.Index(text, "[TASK RESUMPTION]"); idx >= 0 {
+ return strings.TrimSpace(text[idx:])
+ }
+ if strings.Contains(text, "<environment_details>") || strings.HasPrefix(text, "# task_progress") || strings.HasPrefix(text, "[ERROR] You did not use a tool") || strings.HasPrefix(text, "New instructions for task continuation:") || strings.HasPrefix(text, "Command executed.\nOutput:") || strings.HasPrefix(text, "The user has provided feedback on the results.") {
+ return ""
+ }
+ return text
+}
+
+func extractTaggedText(text, tag string) string {
+ open := "<" + tag
+ start := strings.Index(strings.ToLower(text), strings.ToLower(open))
+ if start < 0 {
+ return ""
+ }
+ gt := strings.Index(text[start:], ">")
+ if gt < 0 {
+ return ""
+ }
+ bodyStart := start + gt + 1
+ close := "</" + tag + ">"
+ end := strings.Index(strings.ToLower(text[bodyStart:]), strings.ToLower(close))
+ if end < 0 {
+ return ""
+ }
+ return strings.TrimSpace(text[bodyStart : bodyStart+end])
+}
+
+func extractText(value interface{}) string {
+ switch v := value.(type) {
+ case string:
+ return strings.TrimSpace(v)
+ case []interface{}:
+ var parts []string
+ for _, item := range v {
+ if text := extractText(item); text != "" {
+ parts = append(parts, text)
+ }
+ }
+ return strings.Join(parts, "\n\n")
+ case map[string]interface{}:
+ if stringValue(v["type"]) == "image" {
+ return ""
+ }
+ return firstNonEmpty(stringValue(v["text"]), stringValue(v["content"]), stringValue(v["message"]), stringValue(v["value"]), stringValue(v["output"]))
+ default:
+ return ""
+ }
+}
+
+func extractToolResultOutput(value interface{}) string {
+ if text := extractText(value); text != "" {
+ return text
+ }
+ if value == nil {
+ return "(no output)"
+ }
+ data, err := json.MarshalIndent(value, "", " ")
+ if err != nil {
+ return fmt.Sprint(value)
+ }
+ return string(data)
+}
+
+func parseToolArgs(value interface{}) map[string]interface{} {
+ if obj, ok := value.(map[string]interface{}); ok && obj != nil {
+ return obj
+ }
+ if text, ok := value.(string); ok {
+ var obj map[string]interface{}
+ if err := json.Unmarshal([]byte(text), &obj); err == nil && obj != nil {
+ return obj
+ }
+ if strings.TrimSpace(text) != "" {
+ return map[string]interface{}{"raw": text}
+ }
+ }
+ if value == nil {
+ return map[string]interface{}{}
+ }
+ return map[string]interface{}{"raw": value}
+}
+
+func assistantToolMessage(name string, args map[string]interface{}) string {
+ switch name {
+ case "attempt_completion":
+ return stringValue(args["result"])
+ case "ask_followup_question":
+ return stringValue(args["question"])
+ default:
+ return ""
+ }
+}
+
+func tokenUsage(value interface{}) *TokenUsage {
+ obj, ok := value.(map[string]interface{})
+ if !ok || obj == nil {
+ return nil
+ }
+ usage := &TokenUsage{
+ Input: intValue(firstNonNil(obj["inputTokens"], obj["input_tokens"], obj["tokensIn"], obj["promptTokens"])),
+ Output: intValue(firstNonNil(obj["outputTokens"], obj["output_tokens"], obj["tokensOut"], obj["completionTokens"])),
+ CacheRead: intValue(firstNonNil(obj["cacheReadTokens"], obj["cache_read_tokens"], obj["cachedTokens"])),
+ CacheWrite: intValue(firstNonNil(obj["cacheWriteTokens"], obj["cache_write_tokens"], obj["cacheCreationTokens"])),
+ Reasoning: intValue(firstNonNil(obj["thoughtsTokenCount"], obj["reasoningTokenCount"], obj["reasoningTokens"])),
+ CostUSD: floatValue(firstNonNil(obj["totalCost"], obj["total_cost"], obj["costUsd"], obj["cost_usd"], obj["cost"])),
+ }
+ if usage.Input == 0 && usage.Output == 0 && usage.CacheRead == 0 && usage.CacheWrite == 0 && usage.Reasoning == 0 && usage.CostUSD == 0 {
+ return nil
+ }
+ return usage
+}
+
+func parseTimestampMS(value interface{}, fallback int64) int64 {
+ switch v := value.(type) {
+ case int64:
+ if v > 0 && v < 1_000_000_000_000 {
+ return v * 1000
+ }
+ return v
+ case int:
+ return parseTimestampMS(int64(v), fallback)
+ case float64:
+ if !math.IsNaN(v) && v > 0 {
+ if v < 1_000_000_000_000 {
+ return int64(v * 1000)
+ }
+ return int64(v)
+ }
+ case string:
+ if n, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
+ return parseTimestampMS(n, fallback)
+ }
+ if t, err := time.Parse(time.RFC3339Nano, v); err == nil {
+ return t.UnixMilli()
+ }
+ if t, err := time.Parse(time.RFC3339, v); err == nil {
+ return t.UnixMilli()
+ }
+ }
+ return fallback
+}
+
+func stringValue(value interface{}) string {
+ if value == nil {
+ return ""
+ }
+ switch v := value.(type) {
+ case string:
+ return strings.TrimSpace(v)
+ case fmt.Stringer:
+ return strings.TrimSpace(v.String())
+ default:
+ return ""
+ }
+}
+
+func intValue(value interface{}) int64 {
+ switch v := value.(type) {
+ case int:
+ return int64(v)
+ case int64:
+ return v
+ case float64:
+ return int64(v)
+ case string:
+ n, _ := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
+ return n
+ default:
+ return 0
+ }
+}
+
+func floatValue(value interface{}) float64 {
+ switch v := value.(type) {
+ case float64:
+ return v
+ case int:
+ return float64(v)
+ case int64:
+ return float64(v)
+ case string:
+ n, _ := strconv.ParseFloat(strings.TrimSpace(v), 64)
+ return n
+ default:
+ return 0
+ }
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ return strings.TrimSpace(value)
+ }
+ }
+ return ""
+}
+
+func firstNonNil(values ...interface{}) interface{} {
+ for _, value := range values {
+ if value != nil {
+ return value
+ }
+ }
+ return nil
+}
+
+func truncate(value string, limit int) string {
+ if limit <= 0 || len(value) <= limit {
+ return value
+ }
+ return value[:limit]
+}
+
+func fileLanguage(path string) string {
+ ext := strings.TrimPrefix(filepath.Ext(path), ".")
+ return ext
+}
diff --git a/cli/beacon/internal/clinesession/mapper.go b/cli/beacon/internal/clinesession/mapper.go
new file mode 100644
index 00000000..60169f23
--- /dev/null
+++ b/cli/beacon/internal/clinesession/mapper.go
@@ -0,0 +1,389 @@
+package clinesession
+
+import (
+ "crypto/sha1"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "path"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+type MappedEvent struct {
+ SourceOrder int
+ Event schema.Event
+}
+
+type MapOptions struct {
+ MinOrder int
+ SkipStarted bool
+}
+
+func MapTrace(ref TraceRef, records []Record, opts MapOptions) []MappedEvent {
+ m := &mapper{ref: ref, opts: opts}
+ if !opts.SkipStarted {
+ m.emitSessionStarted()
+ }
+ for i := range records {
+ m.consume(records[i])
+ }
+ return m.out
+}
+
+type mapper struct {
+ ref TraceRef
+ opts MapOptions
+ out []MappedEvent
+}
+
+func (m *mapper) consume(record Record) {
+ if record.Order <= m.opts.MinOrder {
+ return
+ }
+ switch record.Type {
+ case "user_message":
+ m.emitPrompt(record)
+ case "agent_text":
+ m.emitAgentMessage(record)
+ case "agent_reasoning":
+ m.emitReasoning(record)
+ case "tool_call":
+ m.emitToolCall(record)
+ case "tool_result":
+ m.emitToolResult(record)
+ }
+}
+
+func (m *mapper) base(record Record, action, category string, severity schema.Severity, message string) schema.Event {
+ ev := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: category,
+ Severity: severity,
+ Fidelity: schema.FidelityObserved,
+ Message: message,
+ Origin: schema.OriginLocal,
+ Harness: schema.HarnessInfo{Name: Harness, CollectionMethod: schema.CollectionMethodPoll},
+ })
+ if record.TimestampMS > 0 {
+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(record.TimestampMS))
+ } else if m.ref.UpdatedAtUnixMS > 0 {
+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(m.ref.UpdatedAtUnixMS))
+ }
+ ev.Session = &schema.SessionInfo{ID: m.ref.ID, WorkingDirectory: m.ref.Directory}
+ if record.ModelID != "" {
+ ev.Model = asymptoteobserve.NormalizeModelName(record.ModelID)
+ }
+ return ev
+}
+
+func (m *mapper) emitSessionStarted() {
+ record := Record{Order: 0, TimestampMS: m.ref.UpdatedAtUnixMS}
+ ev := m.base(record, "session.started", "session", schema.SeverityInfo, "Cline session discovered")
+ ev.Raw = map[string]interface{}{"cline": map[string]interface{}{"source_path": m.ref.SourcePath, "source_kind": m.ref.Kind}}
+ if m.ref.RelatedTo != "" {
+ ev.Raw["cline"].(map[string]interface{})["related_to"] = m.ref.RelatedTo
+ }
+ m.append(record, "session.started", ev)
+}
+
+func (m *mapper) emitPrompt(record Record) {
+ text := strings.TrimSpace(record.Content)
+ if text == "" {
+ return
+ }
+ ev := m.base(record, "prompt.submitted", "prompt", schema.SeverityInfo, "Cline prompt submitted")
+ ev.Prompt = &schema.PromptInfo{Text: text}
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)
+ ev.GenAI = &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}}
+ ev.Raw = m.raw(record)
+ m.append(record, "prompt", ev)
+}
+
+func (m *mapper) emitAgentMessage(record Record) {
+ text := strings.TrimSpace(record.Content)
+ if text == "" {
+ return
+ }
+ ev := m.base(record, "agent.message", "session", schema.SeverityInfo, "Cline agent message")
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)
+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(text)}}
+ applyUsage(&ev, record.Tokens)
+ ev.Raw = m.raw(record)
+ m.append(record, "assistant", ev)
+}
+
+func (m *mapper) emitReasoning(record Record) {
+ text := strings.TrimSpace(record.Content)
+ if text == "" {
+ return
+ }
+ ev := m.base(record, "agent.reasoning", "reasoning", schema.SeverityInfo, "Cline agent reasoning")
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)
+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: []interface{}{map[string]interface{}{
+ "role": "assistant",
+ "parts": []interface{}{map[string]interface{}{
+ "type": "reasoning",
+ "content": text,
+ }},
+ }}}}
+ applyUsage(&ev, record.Tokens)
+ ev.Raw = m.raw(record)
+ m.append(record, "reasoning", ev)
+}
+
+func (m *mapper) emitToolCall(record Record) {
+ name := firstNonEmpty(record.ToolName, "unknown")
+ ev := m.base(record, "tool.invoked", "tool", schema.SeverityInfo, "Cline tool invoked")
+ ev.Tool = &schema.ToolInfo{Name: name}
+ applyToolCall(&ev, name, record)
+ applyUsage(&ev, record.Tokens)
+ ev.Raw = m.raw(record)
+ m.append(record, "tool.call", ev)
+}
+
+func (m *mapper) emitToolResult(record Record) {
+ name := firstNonEmpty(record.ToolName, "unknown")
+ action, category, severity, message := classifyTool(name, record)
+ ev := m.base(record, action, category, severity, message)
+ ev.Tool = &schema.ToolInfo{Name: name}
+ applyToolCall(&ev, name, record)
+ switch category {
+ case "command":
+ applyCommand(&ev, record)
+ case "file":
+ applyFile(&ev, name, record, m.ref.Directory)
+ case "mcp":
+ ev.MCP = &schema.MCPInfo{Tool: name}
+ }
+ if record.Status == "error" {
+ ev.Error = &schema.ErrorInfo{Type: "tool_error"}
+ }
+ ev.Raw = m.raw(record)
+ m.append(record, "tool.result", ev)
+}
+
+func classifyTool(name string, record Record) (action, category string, severity schema.Severity, message string) {
+ lower := strings.ToLower(strings.TrimSpace(name))
+ switch {
+ case lower == "list_files" || lower == "search_files" || lower == "list_code_definition_names":
+ return "file.read", "file", schema.SeverityInfo, "Cline file read"
+ case toolNameHasToken(lower, "mcp") || lower == "use_mcp_tool" || lower == "access_mcp_resource":
+ return "mcp.tool_invoked", "mcp", schema.SeverityInfo, "Cline MCP tool invoked"
+ case toolNameHasToken(lower, "command") || toolNameHasToken(lower, "commands") || toolNameHasToken(lower, "bash") || toolNameHasToken(lower, "shell") || toolNameHasToken(lower, "terminal"):
+ return "command.executed", "command", schema.SeverityInfo, "Cline command executed"
+ case toolNameHasToken(lower, "read"):
+ return "file.read", "file", schema.SeverityInfo, "Cline file read"
+ case toolNameHasToken(lower, "write") || toolNameHasToken(lower, "edit") || toolNameHasToken(lower, "replace") || toolNameHasToken(lower, "patch") || toolNameHasToken(lower, "create"):
+ return "file.modified", "file", schema.SeverityInfo, "Cline file modified"
+ case record.Status == "error":
+ return "tool.failed", "tool", schema.SeverityHigh, "Cline tool failed"
+ default:
+ return "tool.completed", "tool", schema.SeverityInfo, "Cline tool completed"
+ }
+}
+
+func applyToolCall(ev *schema.Event, name string, record Record) {
+ call := &schema.GenAIToolCallInfo{ID: record.CallID}
+ if len(record.Args) > 0 {
+ call.Arguments = record.Args
+ }
+ if record.Type == "tool_result" {
+ if record.Output != nil {
+ call.Result = record.Output
+ } else if record.OutputText != "" {
+ call.Result = record.OutputText
+ }
+ }
+ ev.GenAI = ensureGenAI(ev.GenAI)
+ ev.GenAI.Operation = &schema.GenAIOperationInfo{Name: "execute_tool"}
+ ev.GenAI.Tool = &schema.GenAIToolInfo{Name: name, Call: call}
+ if path := argString(record.Args, "path", "file_path", "filePath", "target_file", "targetFile"); path != "" {
+ ev.Tool.Path = path
+ }
+ if command := argString(record.Args, "command", "cmd"); command != "" {
+ ev.Tool.Command = command
+ }
+}
+
+func applyCommand(ev *schema.Event, record Record) {
+ command := ""
+ if ev.Tool != nil {
+ command = ev.Tool.Command
+ }
+ info := &schema.CommandInfo{Command: command}
+ if out := strings.TrimSpace(record.OutputText); out != "" {
+ info.Output = out
+ ev.Content = asymptoteobserve.RetainedContent(out, asymptoteobserve.DefaultStringLimit)
+ }
+ ev.Command = info
+}
+
+func applyFile(ev *schema.Event, name string, record Record, root string) {
+ pathValue := ""
+ if ev.Tool != nil {
+ pathValue = ev.Tool.Path
+ }
+ if pathValue == "" {
+ return
+ }
+ pathValue = clineWorkspacePath(pathValue, root)
+ operation := clineFileOperation(name)
+ if operation == "" {
+ return
+ }
+ ev.File = &schema.FileInfo{Path: pathValue, Operation: operation, Language: fileLanguage(pathValue)}
+ if ev.Tool != nil {
+ ev.Tool.Path = pathValue
+ }
+}
+
+func applyUsage(ev *schema.Event, usage *TokenUsage) {
+ if usage == nil {
+ return
+ }
+ info := &schema.GenAIUsageInfo{}
+ if usage.Input > 0 {
+ value := usage.Input
+ info.InputTokens = &value
+ }
+ if usage.Output > 0 {
+ value := usage.Output
+ info.OutputTokens = &value
+ }
+ if usage.CacheRead > 0 {
+ value := usage.CacheRead
+ info.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &value}
+ }
+ if usage.CacheWrite > 0 {
+ value := usage.CacheWrite
+ info.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &value}
+ }
+ if usage.Reasoning > 0 {
+ value := usage.Reasoning
+ info.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &value}
+ }
+ if usage.CostUSD > 0 {
+ value := usage.CostUSD
+ info.CostUSD = &value
+ }
+ ev.GenAI = ensureGenAI(ev.GenAI)
+ ev.GenAI.Usage = info
+}
+
+func (m *mapper) append(record Record, suffix string, ev schema.Event) {
+ ev.Event.ID = deterministicEventID(m.ref, record.Order, suffix)
+ m.out = append(m.out, MappedEvent{SourceOrder: record.Order, Event: ev})
+}
+
+func (m *mapper) raw(record Record) map[string]interface{} {
+ return map[string]interface{}{"cline": map[string]interface{}{
+ "source_path": m.ref.SourcePath,
+ "source_kind": m.ref.Kind,
+ "record": record.Raw,
+ }}
+}
+
+func deterministicEventID(ref TraceRef, order int, suffix string) string {
+ h := sha1.Sum([]byte(fmt.Sprintf("cline:%s:%s:%d:%s", ref.Kind, ref.ID, order, suffix)))
+ return hex.EncodeToString(h[:])
+}
+
+func ensureGenAI(info *schema.GenAIInfo) *schema.GenAIInfo {
+ if info != nil {
+ return info
+ }
+ return &schema.GenAIInfo{}
+}
+
+func argString(args map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ if value := stringValue(args[key]); value != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func outputString(value interface{}) string {
+ if text := stringValue(value); text != "" {
+ return text
+ }
+ data, err := json.Marshal(value)
+ if err != nil || len(data) == 0 || string(data) == "null" {
+ return ""
+ }
+ return string(data)
+}
+
+func toolNameHasToken(name, token string) bool {
+ parts := strings.FieldsFunc(strings.ToLower(name), func(r rune) bool {
+ return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9')
+ })
+ for _, part := range parts {
+ if part == token {
+ return true
+ }
+ }
+ return false
+}
+
+func clineFileOperation(name string) string {
+ lower := strings.ToLower(strings.TrimSpace(name))
+ switch lower {
+ case "list_files", "search_files", "list_code_definition_names":
+ return "read"
+ }
+ switch {
+ case toolNameHasToken(lower, "read") || toolNameHasToken(lower, "view") || toolNameHasToken(lower, "list"):
+ return "read"
+ case toolNameHasToken(lower, "write") || toolNameHasToken(lower, "create"):
+ return "create"
+ case toolNameHasToken(lower, "edit") || toolNameHasToken(lower, "replace") || toolNameHasToken(lower, "patch"):
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func clineWorkspacePath(value, root string) string {
+ value = strings.TrimSpace(value)
+ if value == "" || root == "" || isRootedPath(value) {
+ return value
+ }
+ separator := "/"
+ if strings.Contains(root, "\\") && !strings.Contains(root, "/") {
+ separator = "\\"
+ }
+ volume, rest := splitPathVolume(root)
+ joined := path.Join(strings.ReplaceAll(rest, "\\", "/"), strings.ReplaceAll(value, "\\", "/"))
+ if separator != "/" {
+ joined = strings.ReplaceAll(joined, "/", separator)
+ }
+ return volume + joined
+}
+
+func isRootedPath(value string) bool {
+ if value == "" {
+ return false
+ }
+ if value[0] == '/' || value[0] == '\\' {
+ return true
+ }
+ if len(value) >= 3 && value[1] == ':' && (value[2] == '\\' || value[2] == '/') {
+ letter := value[0] | 0x20
+ return letter >= 'a' && letter <= 'z'
+ }
+ return filepath.IsAbs(value)
+}
+
+func splitPathVolume(value string) (string, string) {
+ if len(value) >= 2 && value[1] == ':' {
+ return value[:2], value[2:]
+ }
+ return "", value
+}
diff --git a/cli/beacon/internal/clinesession/mapper_test.go b/cli/beacon/internal/clinesession/mapper_test.go
new file mode 100644
index 00000000..fabb7591
--- /dev/null
+++ b/cli/beacon/internal/clinesession/mapper_test.go
@@ -0,0 +1,203 @@
+package clinesession
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestStoreListsTaskHistoryAndMapsEvents(t *testing.T) {
+ root := t.TempDir()
+ clineDir := filepath.Join(root, ".cline")
+ taskDir := filepath.Join(clineDir, "data", "tasks", "task-1")
+ if err := os.MkdirAll(taskDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ writeJSON(t, filepath.Join(taskDir, "task_metadata.json"), map[string]interface{}{"cwd": "/repo/app"})
+ writeJSON(t, filepath.Join(taskDir, historyFileName), []interface{}{
+ map[string]interface{}{
+ "role": "user",
+ "timestamp": 1700000000000,
+ "content": "<task>Update src/main.go</task>",
+ "modelInfo": map[string]interface{}{"modelId": "claude-sonnet-4-5"},
+ },
+ map[string]interface{}{
+ "role": "assistant",
+ "timestamp": 1700000001000,
+ "modelInfo": map[string]interface{}{"modelId": "claude-sonnet-4-5"},
+ "content": []interface{}{
+ map[string]interface{}{"type": "thinking", "thinking": "Need to inspect the file."},
+ map[string]interface{}{"type": "tool_use", "id": "call-1", "name": "write_to_file", "input": map[string]interface{}{"path": "src/main.go", "content": "package main\n"}},
+ },
+ "metrics": map[string]interface{}{"inputTokens": 10, "outputTokens": 5, "cacheReadTokens": 2, "thoughtsTokenCount": 1},
+ },
+ map[string]interface{}{
+ "role": "user",
+ "timestamp": 1700000002000,
+ "content": []interface{}{map[string]interface{}{"type": "tool_result", "tool_use_id": "call-1", "content": "File written successfully"}},
+ },
+ })
+
+ store, err := NewStore(clineDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(refs) != 1 {
+ t.Fatalf("refs len = %d, want 1", len(refs))
+ }
+ ref := refs[0]
+ if ref.ID != "task-1" || ref.Kind != SourceHistory || ref.Directory != "/repo/app" {
+ t.Fatalf("unexpected ref: %+v", ref)
+ }
+ if ref.Title != "Update src/main.go" {
+ t.Fatalf("title = %q", ref.Title)
+ }
+ records, err := store.Read(ref)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mapped := MapTrace(ref, records, MapOptions{})
+ wantActions := []string{"session.started", "prompt.submitted", "agent.reasoning", "tool.invoked", "file.modified"}
+ if len(mapped) != len(wantActions) {
+ t.Fatalf("mapped len = %d, want %d: %#v", len(mapped), len(wantActions), mapped)
+ }
+ for i, want := range wantActions {
+ if got := mapped[i].Event.Event.Action; got != want {
+ t.Fatalf("event %d action = %q, want %q", i, got, want)
+ }
+ if mapped[i].Event.Harness.CollectionMethod != "poll" {
+ t.Fatalf("event %d collection method = %q", i, mapped[i].Event.Harness.CollectionMethod)
+ }
+ }
+ fileEvent := mapped[len(mapped)-1].Event
+ if fileEvent.File == nil || fileEvent.File.Path != "/repo/app/src/main.go" || fileEvent.File.Operation != "create" {
+ t.Fatalf("unexpected file event: %+v", fileEvent.File)
+ }
+ toolInvoke := mapped[3].Event
+ if toolInvoke.GenAI == nil || toolInvoke.GenAI.Usage == nil || toolInvoke.GenAI.Usage.InputTokens == nil || *toolInvoke.GenAI.Usage.InputTokens != 10 {
+ t.Fatalf("usage not applied to tool invoke: %+v", toolInvoke.GenAI)
+ }
+}
+
+func TestStoreListsSessionMessagesAndSubagents(t *testing.T) {
+ root := t.TempDir()
+ clineDir := filepath.Join(root, ".cline")
+ sessionDir := filepath.Join(clineDir, "data", "sessions", "lead-1")
+ if err := os.MkdirAll(sessionDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ writeJSON(t, filepath.Join(sessionDir, "lead-1.json"), map[string]interface{}{"task": "Lead task", "workspacePath": "/repo"})
+ writeJSON(t, filepath.Join(sessionDir, "lead-1.messages.json"), map[string]interface{}{"messages": []interface{}{
+ map[string]interface{}{"role": "user", "content": "<environment_details>noise</environment_details>"},
+ map[string]interface{}{"role": "user", "content": "Real prompt"},
+ }})
+ writeJSON(t, filepath.Join(sessionDir, "child-1.messages.json"), []interface{}{
+ map[string]interface{}{"role": "assistant", "content": []interface{}{map[string]interface{}{"type": "text", "text": "child answer"}}},
+ })
+
+ store, err := NewStore(clineDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(refs) != 2 {
+ t.Fatalf("refs len = %d, want 2: %+v", len(refs), refs)
+ }
+ var lead, child TraceRef
+ for _, ref := range refs {
+ switch ref.ID {
+ case "lead-1":
+ lead = ref
+ case "subagent:lead-1:child-1":
+ child = ref
+ }
+ }
+ if lead.ID == "" || lead.Directory != "/repo" {
+ t.Fatalf("lead ref missing or wrong: %+v", lead)
+ }
+ if child.RelatedTo != "lead-1" || child.RelationshipType != "subagent" {
+ t.Fatalf("child relationship wrong: %+v", child)
+ }
+ records, err := store.Read(lead)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mapped := MapTrace(lead, records, MapOptions{})
+ if len(mapped) != 2 {
+ t.Fatalf("lead mapped len = %d, want session + prompt", len(mapped))
+ }
+ if mapped[1].Event.Prompt == nil || mapped[1].Event.Prompt.Text != "Real prompt" {
+ t.Fatalf("unexpected prompt event: %+v", mapped[1].Event)
+ }
+}
+
+func TestStoreListsKanbanSessions(t *testing.T) {
+ root := t.TempDir()
+ workspaceDir := filepath.Join(root, ".cline", "kanban", "workspaces", "workspace-1")
+ if err := os.MkdirAll(workspaceDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ writeJSON(t, filepath.Join(workspaceDir, "board.json"), map[string]interface{}{"columns": []interface{}{
+ map[string]interface{}{"cards": []interface{}{map[string]interface{}{"id": "task-1", "prompt": "Build the dashboard", "createdAt": "2026-01-01T00:00:00Z"}}},
+ }})
+ writeJSON(t, filepath.Join(workspaceDir, "sessions.json"), map[string]interface{}{
+ "task-1": map[string]interface{}{
+ "workspacePath": "/repo/kanban",
+ "modelId": "claude-sonnet-4-5",
+ "updatedAt": "2026-01-01T00:01:00Z",
+ "latestHookActivity": map[string]interface{}{
+ "finalMessage": "Dashboard complete",
+ },
+ },
+ "__home_agent__:ignored": map[string]interface{}{"state": "running"},
+ })
+
+ store, err := NewStore(filepath.Join(root, ".cline"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ refs, err := store.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(refs) != 1 {
+ t.Fatalf("refs len = %d, want 1: %+v", len(refs), refs)
+ }
+ ref := refs[0]
+ if ref.ID != "kanban:workspace-1:task-1" || ref.Kind != SourceKanban || ref.Directory != "/repo/kanban" {
+ t.Fatalf("unexpected kanban ref: %+v", ref)
+ }
+ records, err := store.Read(ref)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mapped := MapTrace(ref, records, MapOptions{})
+ if len(mapped) != 3 {
+ t.Fatalf("mapped len = %d, want session + prompt + summary", len(mapped))
+ }
+ if mapped[1].Event.Prompt == nil || mapped[1].Event.Prompt.Text != "Build the dashboard" {
+ t.Fatalf("unexpected prompt: %+v", mapped[1].Event.Prompt)
+ }
+ if mapped[2].Event.Event.Action != "agent.message" || mapped[2].Event.Model != "claude-sonnet-4-5" {
+ t.Fatalf("unexpected summary event: %+v", mapped[2].Event)
+ }
+}
+
+func writeJSON(t *testing.T, path string, value interface{}) {
+ t.Helper()
+ data, err := json.MarshalIndent(value, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/cli/beacon/internal/clinesession/store.go b/cli/beacon/internal/clinesession/store.go
new file mode 100644
index 00000000..2ad3ae08
--- /dev/null
+++ b/cli/beacon/internal/clinesession/store.go
@@ -0,0 +1,618 @@
+package clinesession
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "net/url"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ historyFileName = "api_conversation_history.json"
+ maxTaskDirsScanned = 10000
+ maxHistoryFileBytes = 25 << 20
+ clineVSCodeExtension = "saoudrizwan.claude-dev"
+)
+
+type Store struct {
+ ClineDir string
+ TasksDirs []string
+ SessionsDir string
+ KanbanWorkspacesDir string
+}
+
+func NewStore(clineDir string) (*Store, error) {
+ if strings.TrimSpace(clineDir) == "" {
+ clineDir = DefaultClineDir()
+ }
+ if strings.TrimSpace(clineDir) == "" {
+ return nil, errors.New("Cline directory is empty")
+ }
+ clineDir = filepath.Clean(clineDir)
+ seen := map[string]bool{}
+ var taskDirs []string
+ add := func(path string) {
+ if strings.TrimSpace(path) == "" || seen[path] {
+ return
+ }
+ seen[path] = true
+ taskDirs = append(taskDirs, path)
+ }
+ add(filepath.Join(clineDir, "data", "tasks"))
+ add(filepath.Join(clineDir, "tasks"))
+ if vs := DefaultClineVSCodeStorageDir(); vs != "" {
+ add(filepath.Join(vs, "tasks"))
+ }
+ return &Store{
+ ClineDir: clineDir,
+ TasksDirs: taskDirs,
+ SessionsDir: filepath.Join(clineDir, "data", "sessions"),
+ KanbanWorkspacesDir: filepath.Join(clineDir, "kanban", "workspaces"),
+ }, nil
+}
+
+func DefaultClineDir() string {
+ home, err := os.UserHomeDir()
+ if err != nil || strings.TrimSpace(home) == "" {
+ return ""
+ }
+ return filepath.Join(home, ".cline")
+}
+
+func DefaultClineVSCodeStorageDir() string {
+ home, err := os.UserHomeDir()
+ if err != nil || strings.TrimSpace(home) == "" {
+ return ""
+ }
+ switch runtime.GOOS {
+ case "darwin":
+ return filepath.Join(home, "Library", "Application Support", "Code", "User", "globalStorage", clineVSCodeExtension)
+ case "windows":
+ base := strings.TrimSpace(os.Getenv("APPDATA"))
+ if base == "" {
+ base = filepath.Join(home, "AppData", "Roaming")
+ }
+ return filepath.Join(base, "Code", "User", "globalStorage", clineVSCodeExtension)
+ default:
+ base := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME"))
+ if base == "" {
+ base = filepath.Join(home, ".config")
+ }
+ return filepath.Join(base, "Code", "User", "globalStorage", clineVSCodeExtension)
+ }
+}
+
+func (s *Store) Exists() bool {
+ if dirExists(s.SessionsDir) || dirExists(s.KanbanWorkspacesDir) {
+ return true
+ }
+ for _, dir := range s.TasksDirs {
+ if dirExists(dir) {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *Store) List() ([]TraceRef, error) {
+ byID := map[string]TraceRef{}
+ s.collectSessionRefs(byID)
+ s.collectHistoryRefs(byID)
+ s.collectKanbanRefs(byID)
+ refs := make([]TraceRef, 0, len(byID))
+ for _, ref := range byID {
+ refs = append(refs, ref)
+ }
+ sort.SliceStable(refs, func(i, j int) bool {
+ if refs[i].UpdatedAtUnixMS != refs[j].UpdatedAtUnixMS {
+ return refs[i].UpdatedAtUnixMS < refs[j].UpdatedAtUnixMS
+ }
+ return refs[i].ID < refs[j].ID
+ })
+ return refs, nil
+}
+
+func (s *Store) Read(ref TraceRef) ([]Record, error) {
+ if ref.Kind == SourceKanban {
+ return s.readKanban(ref)
+ }
+ entries, err := s.ReadEntries(ref.SourcePath)
+ if err != nil {
+ return nil, err
+ }
+ return RecordsFromEntries(ref, entries), nil
+}
+
+func (s *Store) ReadEntries(path string) ([]Entry, error) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return nil, err
+ }
+ if info.Size() > maxHistoryFileBytes {
+ return nil, fmt.Errorf("Cline history %s is %d bytes, over the %d-byte limit", path, info.Size(), maxHistoryFileBytes)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var parsed interface{}
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ return nil, fmt.Errorf("parse Cline history %s: %w", path, err)
+ }
+ items := historyEntriesFromParsed(parsed)
+ entries := make([]Entry, 0, len(items))
+ for i, item := range items {
+ obj, ok := item.(map[string]interface{})
+ if !ok || obj == nil {
+ continue
+ }
+ entries = append(entries, parseEntry(obj, i+1))
+ }
+ return entries, nil
+}
+
+func (s *Store) collectHistoryRefs(out map[string]TraceRef) {
+ for _, root := range s.TasksDirs {
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ continue
+ }
+ count := 0
+ for _, entry := range entries {
+ if count >= maxTaskDirsScanned {
+ break
+ }
+ if !entry.IsDir() {
+ continue
+ }
+ count++
+ id := entry.Name()
+ if !validPathSegment(id) {
+ continue
+ }
+ traceDir := filepath.Join(root, id)
+ source := filepath.Join(traceDir, historyFileName)
+ ref, ok := s.buildHistoryRef(id, source, traceDir, SourceHistory, "")
+ if !ok {
+ continue
+ }
+ if prev, exists := out[ref.ID]; !exists || ref.UpdatedAtUnixMS > prev.UpdatedAtUnixMS {
+ out[ref.ID] = ref
+ }
+ }
+ }
+}
+
+func (s *Store) collectSessionRefs(out map[string]TraceRef) {
+ entries, err := os.ReadDir(s.SessionsDir)
+ if err != nil {
+ return
+ }
+ count := 0
+ for _, entry := range entries {
+ if count >= maxTaskDirsScanned {
+ break
+ }
+ if !entry.IsDir() || !validPathSegment(entry.Name()) {
+ continue
+ }
+ count++
+ leadID := entry.Name()
+ dir := filepath.Join(s.SessionsDir, leadID)
+ files, err := os.ReadDir(dir)
+ if err != nil {
+ continue
+ }
+ meta := readJSONRecord(filepath.Join(dir, leadID+".json"))
+ for _, file := range files {
+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".messages.json") {
+ continue
+ }
+ base := strings.TrimSuffix(file.Name(), ".messages.json")
+ if !validPathSegment(base) {
+ continue
+ }
+ source := filepath.Join(dir, file.Name())
+ id := leadID
+ relatedTo := ""
+ if base != leadID {
+ id = "subagent:" + leadID + ":" + base
+ relatedTo = leadID
+ }
+ ref, ok := s.buildHistoryRef(id, source, dir, SourceMessages, relatedTo)
+ if !ok {
+ continue
+ }
+ if title := normalizeTitleCandidate(stringValue(meta["task"])); title != "" && relatedTo == "" {
+ ref.Title = title
+ ref.Preview = title
+ }
+ if relatedTo != "" {
+ ref.RelationshipType = "subagent"
+ }
+ if dir := extractDirectoryFromRecord(meta); dir != "" {
+ ref.Directory = dir
+ }
+ if prev, exists := out[ref.ID]; !exists || ref.UpdatedAtUnixMS > prev.UpdatedAtUnixMS {
+ out[ref.ID] = ref
+ }
+ }
+ }
+}
+
+func (s *Store) collectKanbanRefs(out map[string]TraceRef) {
+ workspaces, err := os.ReadDir(s.KanbanWorkspacesDir)
+ if err != nil {
+ return
+ }
+ for _, workspace := range workspaces {
+ if !workspace.IsDir() || !validPathSegment(workspace.Name()) {
+ continue
+ }
+ workspaceDir := filepath.Join(s.KanbanWorkspacesDir, workspace.Name())
+ sessionsPath := filepath.Join(workspaceDir, "sessions.json")
+ sessions := readJSONRecord(sessionsPath)
+ if sessions == nil {
+ continue
+ }
+ board := readJSONRecord(filepath.Join(workspaceDir, "board.json"))
+ count := 0
+ for taskID, raw := range sessions {
+ if count >= maxTaskDirsScanned {
+ break
+ }
+ if !validPathSegment(taskID) || strings.HasPrefix(taskID, "__home_agent__:") {
+ continue
+ }
+ session, ok := raw.(map[string]interface{})
+ if !ok || session == nil {
+ continue
+ }
+ count++
+ card := findKanbanCard(board, taskID)
+ prompt := stringValue(card["prompt"])
+ title := normalizeTitleCandidate(prompt)
+ if title == "" {
+ title = "Task " + truncate(taskID, 12)
+ }
+ updated := parseTimestampMS(firstNonNil(session["updatedAt"], session["lastOutputAt"], session["startedAt"], card["updatedAt"], card["createdAt"]), 0)
+ if updated == 0 {
+ updated = newestPathMtimeMS(sessionsPath, filepath.Join(workspaceDir, "board.json"))
+ }
+ ref := TraceRef{
+ ID: "kanban:" + workspace.Name() + ":" + taskID,
+ Kind: SourceKanban,
+ SourcePath: sessionsPath,
+ Title: title,
+ Preview: firstNonEmpty(extractKanbanSummary(session), extractKanbanError(session), prompt, title),
+ Directory: firstNonEmpty(normalizeDirectory(stringValue(session["workspacePath"])), normalizeDirectory(stringValue(session["cwd"]))),
+ UpdatedAtUnixMS: updated,
+ }
+ if info, err := os.Stat(sessionsPath); err == nil {
+ ref.SizeBytes = info.Size()
+ }
+ if prev, exists := out[ref.ID]; !exists || ref.UpdatedAtUnixMS > prev.UpdatedAtUnixMS {
+ out[ref.ID] = ref
+ }
+ }
+ }
+}
+
+func (s *Store) readKanban(ref TraceRef) ([]Record, error) {
+ workspaceID, taskID, ok := parseKanbanID(ref.ID)
+ if !ok {
+ return nil, fmt.Errorf("invalid Cline kanban trace id %q", ref.ID)
+ }
+ workspaceDir := filepath.Join(s.KanbanWorkspacesDir, workspaceID)
+ sessions := readJSONRecord(filepath.Join(workspaceDir, "sessions.json"))
+ session, _ := sessions[taskID].(map[string]interface{})
+ if session == nil {
+ return nil, fmt.Errorf("Cline kanban task %s not found", taskID)
+ }
+ card := findKanbanCard(readJSONRecord(filepath.Join(workspaceDir, "board.json")), taskID)
+ created := parseTimestampMS(firstNonNil(session["startedAt"], card["createdAt"]), ref.UpdatedAtUnixMS)
+ updated := parseTimestampMS(firstNonNil(session["updatedAt"], session["lastOutputAt"], card["updatedAt"], card["createdAt"]), ref.UpdatedAtUnixMS)
+ model := firstNonEmpty(stringValue(session["modelId"]), stringValue(session["model"]))
+ order := 1
+ var records []Record
+ if prompt := stringValue(card["prompt"]); strings.TrimSpace(prompt) != "" {
+ records = append(records, Record{Order: order, Type: "user_message", TimestampMS: created, Content: prompt, ModelID: model, Raw: map[string]interface{}{"session": session, "card": card}})
+ order++
+ }
+ if summary := extractKanbanSummary(session); summary != "" {
+ records = append(records, Record{Order: order, Type: "agent_text", TimestampMS: updated, Content: summary, ModelID: model, Raw: map[string]interface{}{"session": session, "card": card}})
+ order++
+ }
+ if errText := extractKanbanError(session); errText != "" {
+ records = append(records, Record{Order: order, Type: "agent_text", TimestampMS: updated, Content: errText, ModelID: model, Raw: map[string]interface{}{"session": session, "card": card}})
+ }
+ return records, nil
+}
+
+func parseKanbanID(id string) (string, string, bool) {
+ if !strings.HasPrefix(id, "kanban:") {
+ return "", "", false
+ }
+ rest := strings.TrimPrefix(id, "kanban:")
+ idx := strings.Index(rest, ":")
+ if idx <= 0 || idx == len(rest)-1 {
+ return "", "", false
+ }
+ return rest[:idx], rest[idx+1:], true
+}
+
+func findKanbanCard(board map[string]interface{}, taskID string) map[string]interface{} {
+ columns, _ := board["columns"].([]interface{})
+ for _, rawColumn := range columns {
+ column, _ := rawColumn.(map[string]interface{})
+ cards, _ := column["cards"].([]interface{})
+ for _, rawCard := range cards {
+ card, _ := rawCard.(map[string]interface{})
+ if card != nil && stringValue(card["id"]) == taskID {
+ return card
+ }
+ }
+ }
+ return nil
+}
+
+func extractKanbanSummary(session map[string]interface{}) string {
+ activity, _ := session["latestHookActivity"].(map[string]interface{})
+ if text := firstNonEmpty(stringValue(activity["finalMessage"]), stringValue(activity["activityText"])); text != "" {
+ return text
+ }
+ state := strings.ReplaceAll(stringValue(session["state"]), "_", " ")
+ if state == "" {
+ return ""
+ }
+ parts := []string{strings.ToUpper(state[:1]) + state[1:]}
+ if reason := stringValue(session["reviewReason"]); reason != "" {
+ parts = append(parts, "("+reason+")")
+ }
+ if agent := stringValue(session["agentId"]); agent != "" {
+ parts = append(parts, "via "+agent)
+ }
+ return strings.Join(parts, " ")
+}
+
+func extractKanbanError(session map[string]interface{}) string {
+ if text := stringValue(session["warningMessage"]); text != "" {
+ return text
+ }
+ state := strings.ToLower(stringValue(session["state"]))
+ reason := strings.ToLower(stringValue(session["reviewReason"]))
+ if state == "failed" || reason == "error" {
+ return "Session failed."
+ }
+ if state == "interrupted" || reason == "interrupted" {
+ return "Session interrupted."
+ }
+ return ""
+}
+
+func newestPathMtimeMS(paths ...string) int64 {
+ var latest int64
+ for _, path := range paths {
+ if info, err := os.Stat(path); err == nil && info.ModTime().UnixMilli() > latest {
+ latest = info.ModTime().UnixMilli()
+ }
+ }
+ return latest
+}
+
+func (s *Store) buildHistoryRef(id, source, traceDir, kind, relatedTo string) (TraceRef, bool) {
+ info, err := os.Stat(source)
+ if err != nil || info.IsDir() {
+ return TraceRef{}, false
+ }
+ entries, err := s.ReadEntries(source)
+ if err != nil || len(entries) == 0 {
+ return TraceRef{}, false
+ }
+ title := extractTitle(entries, id)
+ ref := TraceRef{
+ ID: id,
+ Kind: kind,
+ SourcePath: source,
+ Title: title,
+ Preview: title,
+ Directory: resolveTaskDirectory(traceDir, entries),
+ UpdatedAtUnixMS: resolveTraceTimestamp(entries, source),
+ SizeBytes: info.Size(),
+ RelatedTo: relatedTo,
+ }
+ if ref.UpdatedAtUnixMS == 0 {
+ ref.UpdatedAtUnixMS = info.ModTime().UnixMilli()
+ }
+ return ref, true
+}
+
+func historyEntriesFromParsed(parsed interface{}) []interface{} {
+ if items, ok := parsed.([]interface{}); ok {
+ return items
+ }
+ obj, _ := parsed.(map[string]interface{})
+ if obj == nil {
+ return nil
+ }
+ for _, key := range []string{"messages", "history", "entries"} {
+ if items, ok := obj[key].([]interface{}); ok {
+ return items
+ }
+ }
+ return nil
+}
+
+func extractTitle(entries []Entry, fallback string) string {
+ var first string
+ for _, entry := range entries {
+ if strings.ToLower(strings.TrimSpace(entry.Role)) != "user" {
+ continue
+ }
+ text := extractVisibleText("user", firstNonEmpty(extractText(entry.Content), entry.Text, entry.Message))
+ if text == "" {
+ continue
+ }
+ title := normalizeTitleCandidate(text)
+ if title == "" {
+ continue
+ }
+ if first == "" {
+ first = title
+ }
+ if !isLowSignalTitle(title) {
+ return title
+ }
+ }
+ if first != "" {
+ return first
+ }
+ return "Task " + truncate(fallback, 12)
+}
+
+func normalizeTitleCandidate(text string) string {
+ text = strings.Join(strings.Fields(text), " ")
+ text = strings.TrimSpace(text)
+ if text == "" {
+ return ""
+ }
+ return truncate(text, 80)
+}
+
+func isLowSignalTitle(text string) bool {
+ value := strings.ToLower(strings.TrimSpace(text))
+ if value == "" {
+ return true
+ }
+ low := map[string]bool{"hi": true, "hey": true, "hello": true, "yo": true, "thanks": true, "thank you": true, "ok": true, "okay": true, "continue": true, "please continue": true, "keep going": true, "resume": true, "retry": true}
+ return low[value]
+}
+
+func resolveTraceTimestamp(entries []Entry, source string) int64 {
+ var latest int64
+ for _, entry := range entries {
+ if ts := parseTimestampMS(entry.Timestamp, 0); ts > latest {
+ latest = ts
+ }
+ }
+ if latest > 0 {
+ return latest
+ }
+ if info, err := os.Stat(source); err == nil {
+ return info.ModTime().UnixMilli()
+ }
+ return time.Now().UnixMilli()
+}
+
+func resolveTaskDirectory(traceDir string, entries []Entry) string {
+ for _, name := range []string{"task_metadata.json", "metadata.json", "task.json"} {
+ if dir := extractDirectoryFromRecord(readJSONRecord(filepath.Join(traceDir, name))); dir != "" {
+ return dir
+ }
+ }
+ for _, entry := range entries {
+ if dir := extractDirectoryFromRecord(entry.Raw); dir != "" {
+ return dir
+ }
+ if dir := extractWorkingDirectoryFromText(firstNonEmpty(extractText(entry.Content), entry.Text, entry.Message)); dir != "" {
+ return dir
+ }
+ }
+ return ""
+}
+
+func extractDirectoryFromRecord(record map[string]interface{}) string {
+ if record == nil {
+ return ""
+ }
+ candidates := []map[string]interface{}{record}
+ for _, key := range []string{"metadata", "environment", "workspace"} {
+ if nested, ok := record[key].(map[string]interface{}); ok {
+ candidates = append(candidates, nested)
+ }
+ }
+ for _, candidate := range candidates {
+ for _, key := range []string{"cwd", "currentWorkingDirectory", "workingDirectory", "workspacePath", "workspaceRoot", "workspace_root", "projectPath", "projectDir", "root"} {
+ if dir := normalizeDirectory(stringValue(candidate[key])); dir != "" {
+ return dir
+ }
+ }
+ if dir := extractWorkingDirectoryFromText(firstNonEmpty(extractText(candidate["content"]), stringValue(candidate["text"]), stringValue(candidate["message"]))); dir != "" {
+ return dir
+ }
+ }
+ return ""
+}
+
+func extractWorkingDirectoryFromText(text string) string {
+ if text == "" {
+ return ""
+ }
+ marker := "# Current Working Directory ("
+ if idx := strings.Index(text, marker); idx >= 0 {
+ rest := text[idx+len(marker):]
+ if end := strings.Index(rest, ")"); end >= 0 {
+ return normalizeDirectory(rest[:end])
+ }
+ }
+ lower := strings.ToLower(text)
+ needle := "current working directory is now "
+ if idx := strings.Index(lower, needle); idx >= 0 {
+ rest := strings.TrimSpace(text[idx+len(needle):])
+ rest = strings.Trim(rest, "'\"` ")
+ if end := strings.IndexAny(rest, "\n\r"); end >= 0 {
+ rest = rest[:end]
+ }
+ return normalizeDirectory(rest)
+ }
+ return ""
+}
+
+func normalizeDirectory(value string) string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return ""
+ }
+ if strings.HasPrefix(value, "file://") {
+ if parsed, err := url.Parse(value); err == nil && parsed.Scheme == "file" {
+ return parsed.Path
+ }
+ return ""
+ }
+ return value
+}
+
+func readJSONRecord(path string) map[string]interface{} {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil
+ }
+ var out map[string]interface{}
+ if err := json.Unmarshal(data, &out); err != nil {
+ return nil
+ }
+ return out
+}
+
+func dirExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.IsDir()
+}
+
+func validPathSegment(value string) bool {
+ return value != "" && value != "." && value != ".." && !strings.ContainsAny(value, `/\\`)
+}
+
+func fileExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && !info.IsDir()
+}
+
+func readDirNames(path string) ([]fs.DirEntry, error) { return os.ReadDir(path) }
diff --git a/cli/beacon/internal/clinesession/types.go b/cli/beacon/internal/clinesession/types.go
new file mode 100644
index 00000000..6f683a01
--- /dev/null
+++ b/cli/beacon/internal/clinesession/types.go
@@ -0,0 +1,98 @@
+// Package clinesession reads Cline's local session store and turns committed history into Beacon
+// endpoint telemetry.
+//
+// This is intentionally separate from the live Cline plugin integration. The plugin observes Cline
+// while a task is running; this package polls files Cline already wrote under ~/.cline and the VS
+// Code extension's global storage. Every event emitted here is marked harness.collection_method=poll.
+package clinesession
+
+import "encoding/json"
+
+const Harness = "cline"
+
+const (
+ SourceHistory = "history"
+ SourceMessages = "messages"
+ SourceKanban = "kanban"
+)
+
+type TraceRef struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ SourcePath string `json:"source_path"`
+ Title string `json:"title,omitempty"`
+ Preview string `json:"preview,omitempty"`
+ Directory string `json:"directory,omitempty"`
+ UpdatedAtUnixMS int64 `json:"updated_at_ms,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+ RelatedTo string `json:"related_to,omitempty"`
+ RelationshipType string `json:"relationship_type,omitempty"`
+}
+
+type Entry struct {
+ Order int
+ Role string
+ Content interface{}
+ Text string
+ Message string
+ ID string
+ Model string
+ ModelID string
+ ModelInfo map[string]interface{}
+ Metrics map[string]interface{}
+ Usage map[string]interface{}
+ Timestamp interface{}
+ Raw map[string]interface{}
+}
+
+type Record struct {
+ Order int
+ Type string
+ TimestampMS int64
+ Content string
+ ModelID string
+ ToolName string
+ CallID string
+ Args map[string]interface{}
+ Output interface{}
+ OutputText string
+ Status string
+ Tokens *TokenUsage
+ Raw map[string]interface{}
+}
+
+type TokenUsage struct {
+ Input int64
+ Output int64
+ CacheRead int64
+ CacheWrite int64
+ Reasoning int64
+ CostUSD float64
+}
+
+func parseEntry(data map[string]interface{}, order int) Entry {
+ entry := Entry{Order: order, Raw: data}
+ entry.Role = stringValue(data["role"])
+ entry.Content = data["content"]
+ entry.Text = stringValue(data["text"])
+ entry.Message = stringValue(data["message"])
+ entry.ID = firstNonEmpty(stringValue(data["id"]), stringValue(data["uuid"]), stringValue(data["messageId"]))
+ entry.Model = stringValue(data["model"])
+ entry.ModelID = firstNonEmpty(stringValue(data["modelId"]), stringValue(data["model_id"]))
+ entry.ModelInfo, _ = data["modelInfo"].(map[string]interface{})
+ if entry.ModelInfo == nil {
+ entry.ModelInfo, _ = data["model_info"].(map[string]interface{})
+ }
+ entry.Metrics, _ = data["metrics"].(map[string]interface{})
+ entry.Usage, _ = data["usage"].(map[string]interface{})
+ entry.Timestamp = firstNonNil(data["ts"], data["timestamp"], data["time"])
+ return entry
+}
+
+func recordFromJSON(data json.RawMessage, order int) (Entry, bool) {
+ var obj map[string]interface{}
+ if err := json.Unmarshal(data, &obj); err != nil || obj == nil {
+ return Entry{}, false
+ }
+ return parseEntry(obj, order), true
+}
diff --git a/docs/runtimes/cline.mdx b/docs/runtimes/cline.mdx
index 817d658f..fd323496 100644
--- a/docs/runtimes/cline.mdx
+++ b/docs/runtimes/cline.mdx
@@ -18,7 +18,7 @@ Before enabling Cline telemetry, make sure:
- Asymptote's Cline plugin is installed with `beacon endpoint hooks install --harness cline`.
- Cline is restarted after plugin install or removal so new sessions load the updated plugin. In the IDE hosts this means reloading the window.
-## Collection path
+## Collection paths
Asymptote installs an owned Cline plugin at `~/.cline/plugins/beacon.ts` for user-level hooks or `./.cline/plugins/beacon.ts` for project-level hooks. Cline auto-discovers plugin files in those directories, so no plugin registry command is required. That is also why the install works for the VS Code and JetBrains hosts, neither of which ships a `cline` executable.
@@ -26,12 +26,22 @@ The plugin forwards `beforeRun`, `beforeTool`, `afterTool`, and `afterRun` hook
The integration is plugin-based. Cline's own OpenTelemetry export is neither configured nor required by Beacon, and Cline's hosted prompt-storage feature is not used.
+Beacon can also recover Cline activity from Cline's committed local session stores:
+
+```bash title="Sync historical Cline sessions"
+beacon endpoint cline sync
+```
+
+The sync path reads `~/.cline/data/tasks`, `~/.cline/tasks`, Cline's VS Code global-storage task directory, `~/.cline/data/sessions`, and `~/.cline/kanban/workspaces`. It is local and offline, emits events with `harness.collection_method=poll`, and is useful for historical sessions or sessions that ran before the Beacon plugin was installed. Use `--print` to inspect mapped events without writing the runtime log or advancing the cursor.
+
## Discovery and status
Asymptote detects Cline through the `~/.cline` directory, treating a `cline` executable on `PATH` as an additional signal rather than the deciding one. A binary check alone would report "not detected" for the IDE hosts, which are the majority of installs.
Use `beacon endpoint hooks status --harness cline` to inspect Cline plugin status. Status reports installed only when the plugin references the hook binary that is actually present, so a plugin left behind by a removed or relocated install is reported as not installed rather than as working telemetry.
+Use `beacon endpoint cline status` to inspect Cline session stores and how much of each discovered trace Beacon has already synced.
+
## Install or configuration support
`beacon endpoint install` prepares shared endpoint config and runtime log paths. Install Cline hooks separately:
@@ -53,6 +63,7 @@ beacon endpoint hooks install --harness cline
| Model and usage | Model and provider (recorded as `model` and `gen_ai.provider.name`), token counts, cache reads, and runtime-reported cost, recorded once per task |
| Approval telemetry | Not supported. See [Known gaps](#known-gaps) |
| Local JSONL and dashboard | Supported |
+| Historical session sync | Supported through `beacon endpoint cline sync`; marked as poll collection |
| MDM deployment | Supported for the endpoint agent. Cline plugins are installed separately in the logged-in user's context |
Cline addresses files relative to the workspace root. Beacon resolves those paths against the workspace before writing them, so a Cline file event is comparable with the same file seen through another runtime and matches threat rules written against absolute paths. A path that is already absolute is left alone, and a relative path with no resolvable workspace root stays relative rather than being joined to a guessed root.
@@ -63,6 +74,8 @@ Cancels and failures reach Beacon two ways: the file-based hooks name them in th
Token usage is recorded at task end only. Beacon's token rollups sum `gen_ai.usage` across events, so reporting the same tokens at a per-model-call boundary would double every Cline task's totals. Cost is recorded only as Cline reports it. Beacon never derives cost from a local price table.
+The session sync path reads what Cline has already committed to disk. It can recover prompts, assistant messages, agent reasoning, tool calls/results, command/file/MCP-shaped tool activity, model ids, and token counts where the stored history carries them. It cannot hold or deny tool calls, and it does not imply that Beacon observed the event at runtime.
+
## Data handling
Cline prompts, tool arguments and results, commands, command output, paths, and diffs are retained in local or customer-controlled logs. Beacon applies local secret redaction and per-string limits before writing. Each content-bearing event includes a hash and byte count for the original value. Events that exceed the 64 KiB limit drop raw and retained content while preserving stable metadata and set `field_truncated`.