The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Harden the OpenCode collector: read-only URI, exit codes, dedup tests
Claudeb835bc51e2fa
diff --git a/cli/beacon/cmd/endpoint_opencode_test.go b/cli/beacon/cmd/endpoint_opencode_test.gonew file mode 100644index 00000000..15579f8c--- /dev/null+++ b/cli/beacon/cmd/endpoint_opencode_test.go@@ -0,0 +1,48 @@+package cmd++import (+ "path/filepath"+ "strings"+ "testing"+)++// The cursor is what keeps a scheduled sweep from re-appending every OpenCode session's whole+// history, so it has to land where the next sweep on this platform will look for it. A hardcoded+// /var/lib path is only the Linux spelling: on macOS and Windows it names a directory nothing+// reads, and progress is silently lost on every run.+func TestOpenCodeStatePathFollowsThePlatformEndpointRoots(t *testing.T) {+ if got := resolveOpenCodeStatePath("/explicit/path.json", true); got != "/explicit/path.json" {+ t.Errorf("an explicit --state was overridden: %q", got)+ }+ if got := resolveOpenCodeStatePath("/explicit/path.json", false); got != "/explicit/path.json" {+ t.Errorf("an explicit --state was overridden in system mode: %q", got)+ }++ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ user := resolveOpenCodeStatePath("", true)+ if want := filepath.Join(home, ".beacon", "endpoint", "state", "opencode-sessions.json"); user != want {+ t.Errorf("user cursor = %q, want %q", user, want)+ }++ system := resolveOpenCodeStatePath("", false)+ if !filepath.IsAbs(system) {+ t.Errorf("system cursor = %q, which is not somewhere a sweep can reliably write", system)+ }+ if filepath.Base(system) != "opencode-sessions.json" {+ t.Errorf("system cursor = %q, want the opencode cursor file", system)+ }+ if strings.HasPrefix(system, home) {+ t.Errorf("a system sweep put its cursor in the operator's home: %q", system)+ }+ if system == user {+ t.Errorf("system and user sweeps share one cursor at %q", system)+ }+ // The pre-fix path. It is the Linux endpoint root and nothing else, so on macOS and Windows it+ // pointed at a directory no later sweep reads.+ if system == filepath.Join("/var", "lib", "beacon", "endpoint", "state", "opencode-sessions.json") {+ t.Errorf("system cursor is still the hardcoded Linux path: %q", system)+ }+}diff --git a/cli/beacon/go.mod b/cli/beacon/go.modindex b222e590..075a5f4a 100644--- a/cli/beacon/go.mod+++ b/cli/beacon/go.mod@@ -9,6 +9,7 @@ require (golang.org/x/sys v0.47.0golang.org/x/term v0.33.0gopkg.in/yaml.v3 v3.0.1+ modernc.org/sqlite v1.59.0)replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../pkg/asymptoteobserve@@ -35,5 +36,4 @@ require (modernc.org/libc v1.75.7 // indirectmodernc.org/mathutil v1.7.1 // indirectmodernc.org/memory v1.12.1 // indirect- modernc.org/sqlite v1.59.0 // indirect)diff --git a/cli/beacon/go.sum b/cli/beacon/go.sumindex fe4e32db..b2a330e0 100644--- a/cli/beacon/go.sum+++ b/cli/beacon/go.sum@@ -10,8 +10,12 @@ github.com/google/cel-go v0.30.0 h1:ll54AkzKunWkBn9wSoiUXbFZXYZTkdJGNXTBXUoolGo=github.com/google/cel-go v0.30.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=@@ -32,14 +36,18 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=-golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=-golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=+golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=+golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=+golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 h1:YcyjlL1PRr2Q17/I0dPk2JmYS5CDXfcdb2Z3YRioEbw=google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7/go.mod h1:OCdP9MfskevB/rbYvHTsXTtKC+3bHWajPdoKgjcYkfo=google.golang.org/genproto/googleapis/rpc v0.0.0-20240826202546-f6391c0de4c7 h1:2035KHhUv+EpyB+hWgJnaWKJOdX1E95w2S8Rr4uWKTs=@@ -50,11 +58,31 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=+modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=+modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=+modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=+modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=+modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=modernc.org/libc v1.75.7 h1:o3DTP9/0p9pKmY2WCKQaySW6wIiZhNM7wc2lUoyhfew=modernc.org/libc v1.75.7/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=diff --git a/cli/beacon/internal/opencodesession/collect.go b/cli/beacon/internal/opencodesession/collect.goindex 7e0a0200..f5250095 100644--- a/cli/beacon/internal/opencodesession/collect.go+++ b/cli/beacon/internal/opencodesession/collect.go@@ -151,8 +151,23 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {return summary, nil}+// collectTrace writes whatever this trace still owes the runtime log.+//+// What Beacon has already seen is tracked by event id rather than by how far it read, because+// OpenCode's store is not an append-only file. A tool part is rewritten in place when the call+// returns, and a record's position is recomputed on every read -- a part that only becomes mappable+// later, such as an assistant text part still streaming in, renumbers every record after it. A+// high-water mark over those positions both skips the completion of a tool call, which is the event+// carrying its output, exit code and diff, and re-emits whatever the renumbering shifted.+//+// Event ids are derived from the record's own identity (see mapper.append), so the same action maps+// to the same id on every sweep and the set below is all the collector needs to tell a new action+// from one already written.func collectTrace(store *Store, ref TraceRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {cursor := state.cursor(ref)+ // Only a trace whose store timestamp moved backwards is skipped outright. An unchanged+ // timestamp is not evidence that nothing changed: OpenCode finishing a tool call rewrites the+ // part without necessarily touching the session's time_updated.if ref.UpdatedAtUnixMS > 0 && ref.UpdatedAtUnixMS < cursor.UpdatedAtMS {return false, nil}@@ -161,36 +176,35 @@ func collectTrace(store *Store, ref TraceRef, state *State, opts CollectOptions,return false, err}mapped := MapTrace(ref, records, MapOptions{})- if len(mapped) == 0 {- cursor.UpdatedAtMS = ref.UpdatedAtUnixMS- return false, nil- }if cursor.Emitted == nil {cursor.Emitted = make(map[string]bool, len(mapped))}changed := false+ live := make(map[string]bool, len(mapped))for _, item := range mapped {- eid := item.Event.Event.ID- if cursor.Emitted[eid] {+ id := item.Event.Event.ID+ live[id] = true+ if cursor.Emitted[id] {continue}if err := emit(item.Event, opts); err != nil {+ // The ids already written stay recorded, so a retry resumes rather than doubling the+ // log. The trace's timestamp is left alone so the next sweep comes back for the rest.return changed, err}- cursor.Emitted[eid] = true+ cursor.Emitted[id] = trueif item.SourceOrder > cursor.LastOrder {cursor.LastOrder = item.SourceOrder}summary.EventsEmitted++changed = true}- current := make(map[string]bool, len(mapped))- for _, item := range mapped {- current[item.Event.Event.ID] = true- }- for eid := range cursor.Emitted {- if !current[eid] {- delete(cursor.Emitted, eid)+ // Ids the trace no longer produces are dropped, so the cursor stays proportional to the session+ // OpenCode is actually holding rather than to everything it has ever held. Compaction, which+ // removes messages outright, is the case that makes this matter.+ for id := range cursor.Emitted {+ if !live[id] {+ delete(cursor.Emitted, id)}}cursor.UpdatedAtMS = ref.UpdatedAtUnixMSdiff --git a/cli/beacon/internal/opencodesession/collect_test.go b/cli/beacon/internal/opencodesession/collect_test.gonew file mode 100644index 00000000..f2c8ee4e--- /dev/null+++ b/cli/beacon/internal/opencodesession/collect_test.go@@ -0,0 +1,151 @@+package opencodesession++import (+ "bufio"+ "database/sql"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ _ "modernc.org/sqlite"+)++// TestCollectOnceEmitsAToolCompletionAfterTheSessionTimestampStops exercises the shape --watch+// actually sees: OpenCode writes a tool part while the call is running, then rewrites that same row+// when it returns. The part keeps its position, and the session's time_updated does not move, so a+// collector that trusted either one alone would report the call as permanently in flight and never+// write its output, exit code, or completion.+func TestCollectOnceEmitsAToolCompletionAfterTheSessionTimestampStops(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "opencode.db")+ db := newOpenCodeDB(t, dbPath)+ insertJSON(t, db, `INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)`, "msg_1", "ses_1", int64(1770000000200), map[string]interface{}{+ "id": "msg_1", "role": "assistant", "time": map[string]interface{}{"created": int64(1770000000200)},+ })+ insertJSON(t, db, `INSERT INTO part (id, message_id, session_id, time_created, data) VALUES (?, ?, ?, ?, ?)`, "part_1", "msg_1", "ses_1", int64(1770000000300), map[string]interface{}{+ "id": "part_1", "type": "tool", "tool": "bash", "callID": "call_1",+ "state": map[string]interface{}{"status": "running", "input": map[string]interface{}{"command": "go test ./..."}},+ })++ logPath := filepath.Join(dir, "runtime.jsonl")+ statePath := filepath.Join(dir, "state.json")+ opts := CollectOptions{DataDir: dir, StatePath: statePath, LogPath: logPath, Write: true}++ summary, err := CollectOnce(opts)+ if err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 1 {+ t.Fatalf("first sweep emitted %d events, want the invocation", summary.EventsEmitted)+ }+ if actions := loggedActions(t, logPath); len(actions) != 1 || actions[0] != "tool.invoked" {+ t.Fatalf("first sweep wrote %v", actions)+ }+ state := mustLoadState(t, statePath)+ if cursor := state.Traces["sqlite:ses_1"]; cursor == nil || len(cursor.Emitted) != 1 {+ t.Fatalf("cursor did not record what it wrote: %+v", cursor)+ }++ // A second sweep with nothing changed must not re-emit the invocation.+ if summary, err = CollectOnce(opts); err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 0 {+ t.Fatalf("an unchanged sweep emitted %d events", summary.EventsEmitted)+ }++ // The call returns. Only the part row is rewritten: session.time_updated stays where it was.+ updateJSON(t, db, `UPDATE part SET data = ? WHERE id = ?`, map[string]interface{}{+ "id": "part_1", "type": "tool", "tool": "bash", "callID": "call_1",+ "state": map[string]interface{}{+ "status": "completed",+ "input": map[string]interface{}{"command": "go test ./..."},+ "output": map[string]interface{}{"output": "ok", "metadata": map[string]interface{}{"exit": 0}},+ },+ }, "part_1")++ if summary, err = CollectOnce(opts); err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 1 {+ t.Fatalf("the completion sweep emitted %d events, want 1", summary.EventsEmitted)+ }+ actions := loggedActions(t, logPath)+ if len(actions) != 2 || actions[1] != "command.executed" {+ t.Fatalf("log = %v, want the invocation then the completion", actions)+ }+ // The invocation's id is no longer produced by the trace, so the cursor tracks the completion+ // alone rather than growing a second entry for every call that finishes.+ state = mustLoadState(t, statePath)+ if cursor := state.Traces["sqlite:ses_1"]; cursor == nil || len(cursor.Emitted) != 1 {+ t.Fatalf("cursor = %+v, want only the completion recorded", cursor)+ }++ // With nothing left in flight the settled trace is quiet again.+ if summary, err = CollectOnce(opts); err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 0 {+ t.Fatalf("a settled sweep emitted %d events", summary.EventsEmitted)+ }+}++func newOpenCodeDB(t *testing.T, path string) *sql.DB {+ t.Helper()+ db, err := sql.Open("sqlite", path)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { db.Close() })+ mustExec(t, db, `CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT, directory TEXT, time_created INTEGER, time_updated INTEGER)`)+ mustExec(t, db, `CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT)`)+ mustExec(t, db, `CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT)`)+ mustExec(t, db, `INSERT INTO session (id, title, directory, time_created, time_updated) VALUES ('ses_1', 'Fix tests', '/repo', 1770000000000, 1770000000200)`)+ return db+}++func updateJSON(t *testing.T, db *sql.DB, query string, payload interface{}, args ...interface{}) {+ t.Helper()+ data, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }+ mustExec(t, db, query, append([]interface{}{string(data)}, args...)...)+}++func mustLoadState(t *testing.T, path string) *State {+ t.Helper()+ state, err := LoadState(path)+ if err != nil {+ t.Fatal(err)+ }+ return state+}++func loggedActions(t *testing.T, path string) []string {+ t.Helper()+ file, err := os.Open(path)+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ var actions []string+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)+ for scanner.Scan() {+ var line struct {+ Event struct {+ Action string `json:"action"`+ } `json:"event"`+ }+ if err := json.Unmarshal(scanner.Bytes(), &line); err != nil {+ t.Fatalf("log line is not an event: %v", err)+ }+ actions = append(actions, line.Event.Action)+ }+ if err := scanner.Err(); err != nil {+ t.Fatal(err)+ }+ return actions+}diff --git a/cli/beacon/internal/opencodesession/helpers.go b/cli/beacon/internal/opencodesession/helpers.goindex 743a150e..a3fe7d02 100644--- a/cli/beacon/internal/opencodesession/helpers.go+++ b/cli/beacon/internal/opencodesession/helpers.go@@ -5,6 +5,7 @@ import ("encoding/hex""encoding/json""fmt"+ "math""strconv""strings")@@ -58,6 +59,46 @@ func intFromAny(value interface{}) int64 {}}+// exitCodeFromAny narrows a runtime-reported exit status to the int the event schema carries.+//+// The value arrives as untyped JSON, so it is neither known to be a number nor known to fit an int:+// OpenCode's tool metadata reuses these keys for string statuses too, and a 32-bit build cannot hold+// every int64. Both of those would otherwise land in the log as a real exit code -- a truncated one,+// or a 0 that reads as success for a tool that failed -- so anything that is not an exit code a+// process could actually report is returned as absent instead.+func exitCodeFromAny(value interface{}) (int, bool) {+ var code int64+ switch v := value.(type) {+ case int:+ code = int64(v)+ case int64:+ code = v+ case float64:+ if v != math.Trunc(v) {+ return 0, false+ }+ code = int64(v)+ case json.Number:+ parsed, err := strconv.ParseInt(v.String(), 10, 32)+ if err != nil {+ return 0, false+ }+ return int(parsed), true+ case string:+ parsed, err := strconv.ParseInt(strings.TrimSpace(v), 10, 32)+ if err != nil {+ return 0, false+ }+ return int(parsed), true+ default:+ return 0, false+ }+ if code < math.MinInt32 || code > math.MaxInt32 {+ return 0, false+ }+ return int(code), true+}+func floatFromAny(value interface{}) float64 {switch v := value.(type) {case float64:@@ -97,15 +138,6 @@ func firstMapValue(m map[string]interface{}, keys ...string) interface{} {return nil}-func hasAnyKey(m map[string]interface{}, keys ...string) bool {- for _, key := range keys {- if _, ok := m[key]; ok {- return true- }- }- return false-}-func tokenUsageFromAny(value interface{}) TokenUsage {m := mapFromAny(value)cache := mapFromAny(m["cache"])diff --git a/cli/beacon/internal/opencodesession/mapper.go b/cli/beacon/internal/opencodesession/mapper.goindex 007838d3..d5c674b9 100644--- a/cli/beacon/internal/opencodesession/mapper.go+++ b/cli/beacon/internal/opencodesession/mapper.go@@ -22,9 +22,10 @@ type MappedEvent struct {Event schema.Event}-type MapOptions struct {- MinOrder int-}+// MapOptions is deliberately empty: a trace is mapped whole on every read and the collector decides+// what is new by event id. Filtering here by how far the last sweep read would reintroduce exactly+// what that dedup exists to avoid -- see collectTrace.+type MapOptions struct{}func MapTrace(ref TraceRef, records []Record, opts MapOptions) []MappedEvent {m := &mapper{ref: ref, opts: opts}@@ -41,9 +42,6 @@ type mapper struct {}func (m *mapper) consume(record Record) {- if record.Order <= m.opts.MinOrder {- return- }switch record.Type {case "user_message":m.emitPrompt(record)@@ -261,9 +259,8 @@ func applyCommand(ev *schema.Event, record Record) {}if metadata := mapFromAny(record.Output); len(metadata) > 0 {if inner := mapFromAny(metadata["metadata"]); len(inner) > 0 {- if code := intFromAny(firstMapValue(inner, "exit", "exit_code", "exitCode", "status")); code != 0 || hasAnyKey(inner, "exit", "exit_code", "exitCode", "status") {- v := int(code)- info.ExitCode = &v+ if code, ok := exitCodeFromAny(firstMapValue(inner, "exit", "exit_code", "exitCode", "status")); ok {+ info.ExitCode = &code}}}@@ -326,6 +323,12 @@ func classifyFileOperation(name string) string {}}+// append names the event by the record's own identity rather than by where the record happened to+// sit in this read. Order is recomputed on every sweep and is only assigned to records that map, so+// a part that becomes mappable later -- an assistant text part still streaming in, say -- renumbers+// every record after it. With the position in the id, that renumbering renamed events the log had+// already seen, and the collector's dedup could neither recognise them nor place the completion of+// a tool call beside its invocation.func (m *mapper) append(record Record, suffix string, ev schema.Event) {dedupID := fmt.Sprintf("%s:%s:%s:%s", m.ref.Kind, m.ref.ID, record.NativeID, suffix)ev.Event.ID = opencodeEventID(dedupID)diff --git a/cli/beacon/internal/opencodesession/mapper_test.go b/cli/beacon/internal/opencodesession/mapper_test.goindex 8cc8f1d5..85249df5 100644--- a/cli/beacon/internal/opencodesession/mapper_test.go+++ b/cli/beacon/internal/opencodesession/mapper_test.go@@ -38,17 +38,72 @@ func TestMapTraceMarksPollProvenanceAndClassifiesCommand(t *testing.T) {}}-func TestMapTraceHonorsMinOrder(t *testing.T) {+func TestMapTraceGivesAToolCallAndItsCompletionDifferentIdentities(t *testing.T) {ref := TraceRef{ID: "ses_1", Kind: SourceSQLite}- records := []Record{- {Order: 1, NativeID: "one", Type: "user_message", Content: "first"},- {Order: 2, NativeID: "two", Type: "user_message", Content: "second"},+ pending := Record{Order: 1, NativeID: "msg:part", Type: "tool_call", ToolName: "bash", CallID: "call_1", Args: map[string]interface{}{"command": "go test ./..."}, Status: "running"}+ invoked := MapTrace(ref, []Record{pending}, MapOptions{})+ if len(invoked) != 1 || invoked[0].Event.Event.Action != "tool.invoked" {+ t.Fatalf("invocation = %+v", invoked)+ }++ // OpenCode rewrites the same part when the call returns. The completion is what carries the+ // output, exit code and diff, so it has to reach the log as its own event rather than being+ // mistaken for the invocation Beacon already wrote.+ done := pending+ done.Type = "tool_result"+ done.Status = "completed"+ done.Output = map[string]interface{}{"output": "ok", "metadata": map[string]interface{}{"exit": 0}}+ finished := MapTrace(ref, []Record{done}, MapOptions{})+ if len(finished) != 1 {+ t.Fatalf("completion = %+v", finished)+ }+ if finished[0].Event.Event.Action != "command.executed" {+ t.Fatalf("action = %q, want command.executed", finished[0].Event.Event.Action)}- mapped := MapTrace(ref, records, MapOptions{MinOrder: 1})- if len(mapped) != 1 {- t.Fatalf("mapped = %d, want 1", len(mapped))+ if finished[0].Event.Command == nil || finished[0].Event.Command.ExitCode == nil || *finished[0].Event.Command.ExitCode != 0 {+ t.Fatalf("command = %+v", finished[0].Event.Command)}- if mapped[0].SourceOrder != 2 {- t.Fatalf("source order = %d, want 2", mapped[0].SourceOrder)+ if finished[0].Event.Event.ID == invoked[0].Event.Event.ID {+ t.Fatalf("invocation and completion share event id %q", finished[0].Event.Event.ID)+ }+}++func TestMapTraceEventIDSurvivesAShiftedPosition(t *testing.T) {+ ref := TraceRef{ID: "ses_1", Kind: SourceSQLite}+ record := Record{NativeID: "msg:part", Type: "user_message", Content: "run tests"}++ first := record+ first.Order = 1+ shifted := record+ shifted.Order = 7++ before := MapTrace(ref, []Record{first}, MapOptions{})+ after := MapTrace(ref, []Record{shifted}, MapOptions{})+ if len(before) != 1 || len(after) != 1 {+ t.Fatalf("mapped = %d, %d, want 1 each", len(before), len(after))+ }+ if before[0].Event.Event.ID != after[0].Event.Event.ID {+ t.Fatalf("event id moved with position: %q vs %q", before[0].Event.Event.ID, after[0].Event.Event.ID)+ }+}++func TestApplyCommandRejectsAnExitCodeThatIsNotOne(t *testing.T) {+ ref := TraceRef{ID: "ses_1", Kind: SourceSQLite}+ for name, metadata := range map[string]map[string]interface{}{+ "string status": {"status": "completed"},+ "out of range": {"exit": float64(int64(1) << 40)},+ } {+ t.Run(name, func(t *testing.T) {+ records := []Record{{Order: 1, NativeID: "msg:part", Type: "tool_result", ToolName: "bash", Status: "completed",+ Args: map[string]interface{}{"command": "go test ./..."},+ Output: map[string]interface{}{"output": "ok", "metadata": metadata}}}+ mapped := MapTrace(ref, records, MapOptions{})+ if len(mapped) != 1 {+ t.Fatalf("mapped = %d, want 1", len(mapped))+ }+ if command := mapped[0].Event.Command; command == nil || command.ExitCode != nil {+ t.Fatalf("exit code = %+v, want none", command)+ }+ })}}diff --git a/cli/beacon/internal/opencodesession/store.go b/cli/beacon/internal/opencodesession/store.goindex 57186f3a..943c1260 100644--- a/cli/beacon/internal/opencodesession/store.go+++ b/cli/beacon/internal/opencodesession/store.go@@ -634,16 +634,49 @@ func legacyProjectDirectory(path string) string {}func openSQLiteReadOnly(path string) (*sql.DB, error) {- uriPath := filepath.ToSlash(path)- if !strings.HasPrefix(uriPath, "/") {- uriPath = "/" + uriPath- }- u := url.URL{Scheme: "file", Path: uriPath}+ return sql.Open("sqlite", sqliteFileURI(path))+}++// sqliteFileURI renders an OS path as the file: URI the driver needs to honour mode=ro.+//+// The URI form is not optional: modernc.org/sqlite only forwards query parameters to SQLite when+// the DSN starts with "file:", and it opens every database with READWRITE|CREATE flags, so mode=ro+// is the one thing keeping a read of OpenCode's store from writing to it.+//+// Handing url.URL a raw OS path does not produce that URI on Windows. A path like+// C:\Users\me\opencode.db has no leading slash, so URL.String emits "file://C:%5CUsers%5C..." and+// SQLite reads "C:" as the URI's authority -- every list and read then fails, and OpenCode sync+// collects nothing. The path is made absolute, switched to forward slashes, and split into the host+// and path a file: URI actually has.+func sqliteFileURI(path string) string {+ abs := path+ if resolved, err := filepath.Abs(path); err == nil {+ abs = resolved+ }+ u := fileURL(filepath.ToSlash(abs))q := u.Query()q.Set("mode", "ro")q.Set("_pragma", "query_only(1)")u.RawQuery = q.Encode()- return sql.Open("sqlite", u.String())+ return u.String()+}++// fileURL splits an already slash-separated path into the host and path of a file: URL.+//+// A UNC path (\\server\share\opencode.db, slashed to //server/share/opencode.db) names a host, and+// is the one case where a file: URI has one. Everything else is a plain local path and gets the+// leading slash that keeps a Windows drive letter inside the path instead of in the authority.+func fileURL(slashed string) url.URL {+ if rest, ok := strings.CutPrefix(slashed, "//"); ok {+ host, remainder, _ := strings.Cut(rest, "/")+ if host != "" {+ return url.URL{Scheme: "file", Host: host, Path: "/" + remainder}+ }+ }+ if !strings.HasPrefix(slashed, "/") {+ slashed = "/" + slashed+ }+ return url.URL{Scheme: "file", Path: slashed}}func sqliteTableExists(db *sql.DB, table string) bool {diff --git a/cli/beacon/internal/opencodesession/store_test.go b/cli/beacon/internal/opencodesession/store_test.goindex f7ad52a1..6826af36 100644--- a/cli/beacon/internal/opencodesession/store_test.go+++ b/cli/beacon/internal/opencodesession/store_test.go@@ -3,7 +3,10 @@ package opencodesessionimport ("database/sql""encoding/json"+ "net/url"+ "os""path/filepath"+ "strings""testing"_ "modernc.org/sqlite"@@ -104,3 +107,56 @@ func insertJSON(t *testing.T, db *sql.DB, query string, args ...interface{}) {args[last] = string(data)mustExec(t, db, query, args...)}++func TestFileURLKeepsAWindowsDriveLetterOutOfTheAuthority(t *testing.T) {+ // The inputs are already slash-separated, which is what filepath.ToSlash hands fileURL, so the+ // Windows shapes are exercised on every platform rather than only on the Windows runner.+ for _, tc := range []struct {+ name, slashed, want string+ }{+ {"windows drive", "C:/Users/me/AppData/Roaming/opencode/opencode.db", "file:///C:/Users/me/AppData/Roaming/opencode/opencode.db"},+ {"posix", "/home/me/.config/opencode/opencode.db", "file:///home/me/.config/opencode/opencode.db"},+ {"unc share", "//server/share/opencode/opencode.db", "file://server/share/opencode/opencode.db"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ u := fileURL(tc.slashed)+ if got := u.String(); got != tc.want {+ t.Fatalf("fileURL(%q) = %q, want %q", tc.slashed, got, tc.want)+ }+ })+ }+}++func TestSQLiteFileURIAsksForReadOnly(t *testing.T) {+ uri := sqliteFileURI(filepath.Join(t.TempDir(), "opencode.db"))+ if !strings.HasPrefix(uri, "file:///") {+ // Without the file: prefix modernc.org/sqlite drops the query, and the driver's own flags+ // would open the store READWRITE|CREATE.+ t.Fatalf("uri = %q, want a file:// URI", uri)+ }+ parsed, err := url.Parse(uri)+ if err != nil {+ t.Fatal(err)+ }+ if parsed.Host != "" {+ t.Fatalf("uri host = %q, want none", parsed.Host)+ }+ if mode := parsed.Query().Get("mode"); mode != "ro" {+ t.Fatalf("mode = %q, want ro", mode)+ }+}++func TestOpenSQLiteReadOnlyDoesNotCreateTheDatabase(t *testing.T) {+ missing := filepath.Join(t.TempDir(), "opencode.db")+ db, err := openSQLiteReadOnly(missing)+ if err != nil {+ t.Fatal(err)+ }+ defer db.Close()+ if err := db.Ping(); err == nil {+ t.Fatal("ping on a missing database succeeded; mode=ro is not reaching sqlite")+ }+ if _, err := os.Stat(missing); !os.IsNotExist(err) {+ t.Fatalf("read-only open created %s", missing)+ }+}diff --git a/docs/cli/endpoint-opencode.mdx b/docs/cli/endpoint-opencode.mdxindex af9e00f3..6c92f82e 100644--- a/docs/cli/endpoint-opencode.mdx+++ b/docs/cli/endpoint-opencode.mdx@@ -31,7 +31,7 @@ Both subcommands accept:| Flag | Description ||------|-------------|| `--data-dir <path>` | OpenCode data directory or `opencode.db` path. Defaults to `~/.config/opencode` |-| `--state <path>` | Collector cursor file. Defaults to `~/.beacon/endpoint/state/opencode-sessions.json` |+| `--state <path>` | Collector cursor file. Defaults to `~/.beacon/endpoint/state/opencode-sessions.json`, or a file beside the system runtime log with `--system` || `--json` | Print the result as JSON || `--user` | Use per-user endpoint paths. Enabled by default || `--system` | Use system endpoint paths |@@ -63,6 +63,8 @@ beacon endpoint opencode sync --watch --interval 5mNothing sweeps on its own. Run `sync` under whatever scheduler the platform already uses, or leave `--watch` running in the user context that owns OpenCode's data directory.+A tool call that OpenCode has started but not finished is written twice: once as the invocation, and again with its output, exit code, and diff when it returns. Beacon emits both. The invocation arrives as `tool.invoked` on the sweep that first sees it, and the completion arrives on a later sweep as `command.executed`, `file.modified`, or whichever action the finished call turns out to be. OpenCode rewrites the record in place for the second one, so the cursor tracks the events it has already written by id rather than how far it read: a repeated sweep over an unchanged session writes nothing, and one over a session whose call has since returned writes only the completion.+## Status```bash title="Show OpenCode sessions and collection progress"