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
add factory session sync
Justin D'Souza3a9923fce5c6
diff --git a/cli/beacon/cmd/endpoint_factory.go b/cli/beacon/cmd/endpoint_factory.gonew file mode 100644index 00000000..4c232828--- /dev/null+++ b/cli/beacon/cmd/endpoint_factory.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/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/factorysession"+ "github.com/spf13/cobra"+)++var endpointFactoryCmd = &cobra.Command{+ Use: "factory",+ Short: "Collect telemetry from Factory Droid sessions",+ Long: `Collect endpoint telemetry from Factory Droid's local session store.++Factory already supports live OTLP and hook telemetry. This command adds an+after-the-fact local reader for records Factory commits under ~/.factory/sessions.+Every event is marked harness.collection_method=poll: Beacon sees committed+session records rather than observing or controlling the agent as it works.++Reading is local and offline. Run 'sync' on a schedule, or with --watch, to keep+the runtime log current.`,+}++var endpointFactorySyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Factory session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointFactorySync,+}++var endpointFactoryStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show Factory sessions on this machine and how much has been collected",+ SilenceUsage: true,+ RunE: runEndpointFactoryStatus,+}++var endpointFactoryOpts struct {+ sessionsDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointFactoryCmd)+ endpointFactoryCmd.AddCommand(endpointFactorySyncCmd)+ endpointFactoryCmd.AddCommand(endpointFactoryStatusCmd)++ for _, c := range []*cobra.Command{endpointFactorySyncCmd, endpointFactoryStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointFactoryOpts.sessionsDir, "sessions-dir", "", "Factory session directory (default ~/.factory/sessions)")+ f.StringVar(&endpointFactoryOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/factory.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 := endpointFactorySyncCmd.Flags()+ sync.StringVar(&endpointFactoryOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointFactoryOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointFactoryOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointFactoryOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointFactorySync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := factorysession.CollectOptions{+ SessionsDir: endpointFactoryOpts.sessionsDir,+ Print: endpointFactoryOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointFactoryOpts.print,+ UserMode: userMode,+ }+ if !endpointFactoryOpts.print {+ opts.StatePath = resolveFactoryStatePath(endpointFactoryOpts.statePath, userMode)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointFactoryOpts.logPath).EffectiveLogPath+ }+ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointFactoryOpts.watch && !endpointFactoryOpts.print {+ return watchFactory(ctx, cmd, opts)+ }+ summary, err := factorysession.CollectOnce(opts)+ reportFactorySweep(cmd, summary)+ return err+}++func watchFactory(ctx context.Context, cmd *cobra.Command, opts factorysession.CollectOptions) error {+ interval := endpointFactoryOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := factorysession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "Factory sync error: %v\n", err)+ }+ reportFactorySweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportFactorySweep(cmd *cobra.Command, summary factorysession.Summary) {+ if endpointFactoryOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Factory sync: %d sessions, %d changed, %d events, %d errors\n",+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)+ if summary.MalformedLines > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in Factory session logs\n", summary.MalformedLines)+ }+ if summary.PartialSessions > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d session(s) had a partly written record; it will be read on the next sweep\n", summary.PartialSessions)+ }+}++type factorySessionStatus struct {+ SessionID string `json:"session_id"`+ Workspace string `json:"workspace,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+ CollectedLine int `json:"collected_line"`+ Lines int `json:"lines"`+ Collected bool `json:"collected"`+ SizeBytes int64 `json:"size_bytes"`+ Model string `json:"model,omitempty"`+}++type factoryStatusReport struct {+ SessionsDir string `json:"sessions_dir"`+ Present bool `json:"present"`+ StatePath string `json:"state_path,omitempty"`+ Sessions []factorySessionStatus `json:"sessions"`+}++func runEndpointFactoryStatus(cmd *cobra.Command, args []string) error {+ store, err := factorysession.NewStore(endpointFactoryOpts.sessionsDir)+ if err != nil {+ return err+ }+ statePath := resolveFactoryStatePath(endpointFactoryOpts.statePath, endpointUserMode())+ state, err := factorysession.LoadState(statePath)+ if err != nil {+ return err+ }+ refs, err := store.List()+ if err != nil {+ return err+ }+ report := factoryStatusReport{+ SessionsDir: store.Dir,+ Present: store.Exists(),+ StatePath: statePath,+ Sessions: make([]factorySessionStatus, 0, len(refs)),+ }+ for _, ref := range refs {+ records, stats, _ := store.Read(ref)+ _ = records+ status := factorySessionStatus{+ SessionID: ref.ID,+ Workspace: strings.TrimSpace(ref.CWD),+ Lines: stats.Lines,+ SizeBytes: ref.SizeBytes,+ Model: ref.Model,+ }+ if ref.ModTimeUnixMS > 0 {+ status.UpdatedAt = time.UnixMilli(ref.ModTimeUnixMS).UTC().Format(time.RFC3339)+ }+ if cursor := state.Sessions[ref.ID]; cursor != nil {+ status.CollectedLine = cursor.LastLine+ status.Collected = cursor.SourcePath == ref.Path &&+ cursor.LastLine >= stats.Lines &&+ cursor.ModTimeUnixMS == ref.ModTimeUnixMS &&+ cursor.SizeBytes == ref.SizeBytes &&+ cursor.SettingsUnixMS == ref.SettingsUnixMS+ }+ report.Sessions = append(report.Sessions, status)+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)+ }+ out := cmd.OutOrStdout()+ if !report.Present {+ fmt.Fprintf(out, "Factory sessions: none (%s does not exist)\n", report.SessionsDir)+ return nil+ }+ fmt.Fprintf(out, "Factory sessions: %d in %s\n", len(report.Sessions), report.SessionsDir)+ for _, session := range report.Sessions {+ state := "pending"+ if session.Collected {+ state = "collected"+ }+ fmt.Fprintf(out, " %s %s lines %d/%d %s\n",+ session.SessionID, state, session.CollectedLine, session.Lines, session.Workspace)+ }+ return nil+}++func resolveFactoryStatePath(override string, userMode bool) string {+ if strings.TrimSpace(override) != "" {+ return override+ }+ if !userMode {+ if dir := filepath.Dir(lifecycle.ResolveRuntimeLog(false, "").EffectiveLogPath); dir != "" && dir != "." {+ return filepath.Join(dir, "factory-state.json")+ }+ }+ return factorysession.DefaultStatePath()+}diff --git a/cli/beacon/internal/factorysession/collect.go b/cli/beacon/internal/factorysession/collect.gonew file mode 100644index 00000000..47fa4fdd--- /dev/null+++ b/cli/beacon/internal/factorysession/collect.go@@ -0,0 +1,233 @@+package factorysession++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 {+ SourcePath string `json:"source_path,omitempty"`+ LastLine int `json:"last_line"`+ Started bool `json:"started"`+ ModTimeUnixMS int64 `json:"mtime_ms,omitempty"`+ SizeBytes int64 `json:"size_bytes,omitempty"`+ SettingsUnixMS int64 `json:"settings_mtime_ms,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Sessions map[string]*Cursor `json:"sessions"`+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Sessions: map[string]*Cursor{}}+ if 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 Factory collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Sessions == nil {+ return state, nil+ }+ state.Sessions = stored.Sessions+ return state, nil+}++func (s *State) Save(path string) error {+ if 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(sessionID string) *Cursor {+ if s.Sessions == nil {+ s.Sessions = map[string]*Cursor{}+ }+ cursor := s.Sessions[sessionID]+ if cursor == nil {+ cursor = &Cursor{}+ s.Sessions[sessionID] = 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", "factory.json")+}++type CollectOptions struct {+ SessionsDir string+ StatePath string+ Write bool+ LogPath string+ UserMode bool+ Print bool+ Out io.Writer+}++type Summary struct {+ Sessions int `json:"sessions"`+ SessionsChanged int `json:"sessions_changed"`+ EventsEmitted int `json:"events_emitted"`+ Errors int `json:"errors"`+ MalformedLines int `json:"malformed_lines"`+ PartialSessions int `json:"partial_sessions"`+}++func CollectOnce(opts CollectOptions) (summary Summary, err error) {+ store, err := NewStore(opts.SessionsDir)+ if err != nil {+ return summary, err+ }+ refs, err := store.List()+ if err != nil {+ return summary, err+ }+ summary.Sessions = len(refs)+ if len(refs) == 0 {+ return summary, nil+ }+ 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 Factory collector state: %w", saveErr)+ }+ }()++ var errs []error+ for _, ref := range refs {+ changed, collectErr := collectSession(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("Factory session %s: %w", ref.ID, collectErr))+ continue+ }+ if changed {+ summary.SessionsChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {+ cursor := state.cursor(ref.ID)+ if cursor.SourcePath != "" && cursor.SourcePath != ref.Path {+ cursor.LastLine = 0+ cursor.Started = false+ cursor.SettingsUnixMS = 0+ }+ if cursor.LastLine > 0 &&+ cursor.ModTimeUnixMS == ref.ModTimeUnixMS &&+ cursor.SizeBytes == ref.SizeBytes &&+ cursor.SettingsUnixMS == ref.SettingsUnixMS {+ return false, nil+ }+ records, stats, err := store.Read(ref)+ summary.MalformedLines += stats.Malformed+ if stats.Partial {+ summary.PartialSessions+++ }+ if err != nil {+ return false, err+ }+ emitSettingsUsage := ref.Settings != nil && ref.SettingsUnixMS > 0 && ref.SettingsUnixMS != cursor.SettingsUnixMS+ mapped := MapSession(ref, records, MapOptions{+ MinLine: cursor.LastLine,+ SkipSessionStarted: cursor.Started,+ EmitSettingsUsage: emitSettingsUsage,+ })+ for i, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ advanceCursorPartial(cursor, ref, mapped, i)+ return true, err+ }+ summary.EventsEmitted+++ if item.Event.Event.Action == "session.started" {+ cursor.Started = true+ }+ }+ advanceCursor(cursor, ref, stats)+ return len(mapped) > 0 || stats.Lines != cursor.LastLine || emitSettingsUsage, nil+}++func advanceCursor(cursor *Cursor, ref SessionRef, stats ReadStats) {+ cursor.SourcePath = ref.Path+ cursor.LastLine = stats.Lines+ cursor.ModTimeUnixMS = ref.ModTimeUnixMS+ cursor.SizeBytes = ref.SizeBytes+ cursor.SettingsUnixMS = ref.SettingsUnixMS+}++func advanceCursorPartial(cursor *Cursor, ref SessionRef, mapped []MappedEvent, failedIdx int) {+ cursor.SourcePath = ref.Path+ for i := 0; i < failedIdx; i++ {+ if mapped[i].SourceLine > cursor.LastLine {+ cursor.LastLine = mapped[i].SourceLine+ }+ if mapped[i].Event.Event.Action == "session.started" {+ cursor.Started = true+ }+ }+ cursor.ModTimeUnixMS = ref.ModTimeUnixMS+ cursor.SizeBytes = ref.SizeBytes+}++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/factorysession/collect_test.go b/cli/beacon/internal/factorysession/collect_test.gonew file mode 100644index 00000000..715a9b91--- /dev/null+++ b/cli/beacon/internal/factorysession/collect_test.go@@ -0,0 +1,81 @@+package factorysession++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestCollectOnceReadsFactorySessionsIncrementally(t *testing.T) {+ root := t.TempDir()+ project := filepath.Join(root, "-repo")+ if err := os.MkdirAll(project, 0o755); err != nil {+ t.Fatal(err)+ }+ sessionPath := filepath.Join(project, "session-1.jsonl")+ writeFile(t, sessionPath,+ `{"type":"session_start","id":"session-1","title":"hi","cwd":"/repo"}`+"\n"++ `{"type":"message","id":"u1","timestamp":"2026-05-16T22:11:04.611Z","message":{"role":"user","content":[{"type":"text","text":"hello"}]}}`+"\n")+ writeFile(t, filepath.Join(project, "session-1.settings.json"), `{"model":"claude-opus-4-7","tokenUsage":{"inputTokens":1,"outputTokens":2}}`)++ statePath := filepath.Join(t.TempDir(), "factory-state.json")+ var out bytes.Buffer+ summary, err := CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, Print: true, Out: &out})+ if err != nil {+ t.Fatal(err)+ }+ if summary.Sessions != 1 || summary.EventsEmitted != 3 {+ t.Fatalf("summary = %+v, want one session and three events", summary)+ }+ text := out.String()+ for _, want := range []string{`"session.started"`, `"prompt.submitted"`, `"token.usage"`} {+ if !strings.Contains(text, want) {+ t.Fatalf("output missing %s:\n%s", want, text)+ }+ }++ out.Reset()+ summary, err = CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, Print: true, Out: &out})+ if err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 0 || out.Len() != 0 {+ t.Fatalf("second sweep emitted summary=%+v output=%s, want no events", summary, out.String())+ }++ appendFile(t, sessionPath, `{"type":"message","id":"a1","timestamp":"2026-05-16T22:11:05.611Z","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}`+"\n")+ now := time.Now()+ if err := os.Chtimes(sessionPath, now, now); err != nil {+ t.Fatal(err)+ }+ out.Reset()+ summary, err = CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, Print: true, Out: &out})+ if err != nil {+ t.Fatal(err)+ }+ if summary.EventsEmitted != 1 || !strings.Contains(out.String(), `"agent.message"`) {+ t.Fatalf("third sweep summary=%+v output=%s, want new assistant event", summary, out.String())+ }+}++func writeFile(t *testing.T, path, text string) {+ t.Helper()+ if err := os.WriteFile(path, []byte(text), 0o600); err != nil {+ t.Fatal(err)+ }+}++func appendFile(t *testing.T, path, text string) {+ t.Helper()+ file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ if _, err := file.WriteString(text); err != nil {+ t.Fatal(err)+ }+}diff --git a/cli/beacon/internal/factorysession/mapper.go b/cli/beacon/internal/factorysession/mapper.gonew file mode 100644index 00000000..9683f469--- /dev/null+++ b/cli/beacon/internal/factorysession/mapper.go@@ -0,0 +1,402 @@+package factorysession++import (+ "encoding/json"+ "fmt"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++type MapOptions struct {+ MinLine int+ SkipSessionStarted bool+ EmitSettingsUsage bool+}++func MapSession(ref SessionRef, records []Record, opts MapOptions) []MappedEvent {+ m := &mapper{+ ref: ref,+ opts: opts,+ model: asymptoteobserve.NormalizeModelName(ref.Model),+ pendingTool: map[string]string{},+ }+ for i := range records {+ m.consume(&records[i])+ }+ if opts.EmitSettingsUsage && ref.Settings != nil {+ m.emitSettingsUsage(len(records) + 1)+ }+ return m.out+}++type mapper struct {+ ref SessionRef+ opts MapOptions+ out []MappedEvent+ model string+ pendingTool map[string]string+ order uint64+}++func (m *mapper) consume(record *Record) {+ emit := record.Line > m.opts.MinLine+ switch record.Type {+ case RecordSessionStart:+ if emit && !m.opts.SkipSessionStarted {+ ev := m.base(record, "session.started", "session", schema.SeverityInfo, "Factory Droid session started")+ m.append(record, "session.started", ev)+ }+ case RecordTodoState:+ return+ case RecordCompactionState:+ if emit {+ ev := m.base(record, "session.compacted", "session", schema.SeverityInfo, "Factory Droid context compacted")+ data := map[string]any{}+ if record.SummaryText != "" {+ data["summary"] = record.SummaryText+ }+ if record.SummaryTokens != nil {+ data["summary_tokens"] = *record.SummaryTokens+ }+ if record.AnchorMessage != nil && record.AnchorMessage.ID != "" {+ data["retained_from_id"] = record.AnchorMessage.ID+ }+ if len(data) > 0 {+ ev.Raw = map[string]any{"factory": data}+ }+ m.append(record, "session.compacted", ev)+ }+ case RecordMessage:+ if record.Message == nil {+ return+ }+ if record.Message.Model != "" {+ m.model = asymptoteobserve.NormalizeModelName(record.Message.Model)+ }+ if record.Message.Visibility == "user_only" {+ return+ }+ if record.Message.Visibility == "llm_only" {+ if emit {+ for _, text := range messageTexts(record.Message) {+ ev := m.base(record, "error.observed", "error", schema.SeverityLow, "Factory Droid hidden message observed")+ ev.Error = &schema.ErrorInfo{Type: "llm_only_message"}+ ev.Content = asymptoteobserve.RetainedContent(text, 0)+ ev.Raw = map[string]any{"factory_error_message": text}+ m.append(record, "llm_only.error", ev)+ }+ }+ return+ }+ if emit {+ m.emitMessage(record)+ } else {+ m.rememberToolCalls(record.Message)+ }+ }+}++func (m *mapper) emitMessage(record *Record) {+ msg := record.Message+ switch msg.Role {+ case RoleUser:+ for i, text := range messageTexts(msg) {+ ev := m.base(record, "prompt.submitted", "prompt", schema.SeverityInfo, "Factory Droid prompt submitted")+ ev.Prompt = &schema.PromptInfo{Text: text}+ ev.Content = asymptoteobserve.RetainedContent(text, 0)+ ev.GenAI = &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}}+ m.append(record, fmt.Sprintf("prompt.%d", i), ev)+ }+ case RoleAssistant:+ blocks := messageBlocks(msg)+ for i, block := range blocks {+ switch normalizedBlockType(block.Type) {+ case BlockThinking:+ text := firstNonEmpty(block.Thinking, block.Text, rawString(block.Content))+ if text == "" {+ continue+ }+ ev := m.base(record, "agent.reasoning", "agent", schema.SeverityInfo, "Factory Droid reasoning observed")+ ev.Content = asymptoteobserve.RetainedContent(text, 0)+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.ReasoningOutputMessages(text)}}+ m.append(record, fmt.Sprintf("reasoning.%d", i), ev)+ case BlockToolUse:+ callID := firstNonEmpty(block.ID, fmt.Sprintf("%s:tool:%d", record.ID, i))+ name := firstNonEmpty(block.Name, "unknown")+ args := parseObject(block.Input)+ m.pendingTool[callID] = name+ ev := m.base(record, "tool.invoked", "tool", schema.SeverityInfo, "Factory Droid tool invoked")+ ev.Tool = &schema.ToolInfo{Name: name}+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{+ Name: name,+ Call: &schema.GenAIToolCallInfo{ID: callID, Arguments: args},+ }}+ ev.Raw = map[string]any{"factory_tool_input": args}+ m.append(record, fmt.Sprintf("tool.%s.invoked", callID), ev)+ case BlockToolResult:+ callID := firstNonEmpty(block.ToolUseID, block.ID, fmt.Sprintf("%s:tool:%d", record.ID, i))+ name := firstNonEmpty(m.pendingTool[callID], block.Name, "unknown")+ output := rawString(block.Content)+ ev := m.base(record, "tool.completed", "tool", schema.SeverityInfo, "Factory Droid tool completed")+ ev.Tool = &schema.ToolInfo{Name: name}+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{+ Name: name,+ Call: &schema.GenAIToolCallInfo{ID: callID, Result: output},+ }}+ if output != "" {+ ev.Content = asymptoteobserve.RetainedContent(output, 0)+ }+ if block.IsError {+ ev.Severity = schema.SeverityHigh+ ev.Event.Action = "tool.failed"+ ev.Message = "Factory Droid tool failed"+ }+ m.append(record, fmt.Sprintf("tool.%s.result", callID), ev)+ default:+ text := firstNonEmpty(block.Text, rawString(block.Content))+ if text == "" {+ continue+ }+ ev := m.base(record, "agent.message", "agent", schema.SeverityInfo, "Factory Droid assistant message")+ ev.Content = asymptoteobserve.RetainedContent(text, 0)+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(text)}}+ m.append(record, fmt.Sprintf("assistant.%d", i), ev)+ }+ }+ case RoleTool:+ for i, text := range messageTexts(msg) {+ ev := m.base(record, "tool.completed", "tool", schema.SeverityInfo, "Factory Droid tool result")+ ev.Content = asymptoteobserve.RetainedContent(text, 0)+ m.append(record, fmt.Sprintf("tool-message.%d", i), ev)+ }+ }+}++func (m *mapper) rememberToolCalls(msg *Message) {+ for i, block := range messageBlocks(msg) {+ if normalizedBlockType(block.Type) != BlockToolUse {+ continue+ }+ callID := firstNonEmpty(block.ID, fmt.Sprintf("skipped:tool:%d", i))+ m.pendingTool[callID] = firstNonEmpty(block.Name, "unknown")+ }+}++func (m *mapper) emitSettingsUsage(line int) {+ usage := m.ref.Settings.TokenUsage+ if usage == nil {+ usage = m.ref.Settings.InclusiveTokenUsage+ }+ if usage == nil {+ return+ }+ record := &Record{Line: line, Type: "settings", Timestamp: unixMilliToRFC3339(m.ref.SettingsUnixMS)}+ ev := m.base(record, "token.usage", "metric", schema.SeverityInfo, "Factory Droid token usage")+ ev.GenAI = &schema.GenAIInfo{Usage: usageInfo(usage)}+ raw := map[string]any{"source": "factory_settings"}+ if m.ref.Settings.AssistantActiveTimeMs > 0 {+ raw["assistant_active_time_ms"] = m.ref.Settings.AssistantActiveTimeMs+ }+ if usage.FactoryCredits > 0 {+ raw["factory_credits"] = usage.FactoryCredits+ }+ ev.Raw = raw+ m.append(record, "settings.usage", ev)+}++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 ts := parseTime(record.Timestamp); !ts.IsZero() {+ ev.Timestamp = schema.FormatTimestamp(ts)+ }+ ev.Session = &schema.SessionInfo{ID: m.ref.ID, WorkingDirectory: m.ref.CWD}+ if m.model != "" {+ ev.Model = m.model+ }+ m.order+++ ev.Sequence = m.order+ return ev+}++func (m *mapper) append(record *Record, suffix string, ev schema.Event) {+ if ev.Raw == nil {+ ev.Raw = map[string]any{}+ }+ ev.Raw["source"] = "factory_session"+ ev.Raw["source_path"] = m.ref.Path+ ev.Raw["source_line"] = record.Line+ if record.ID != "" {+ ev.Raw["source_record_id"] = record.ID+ }+ m.out = append(m.out, MappedEvent{+ SourceLine: record.Line,+ DedupID: fmt.Sprintf("%s:%d:%s", m.ref.ID, record.Line, suffix),+ Event: ev,+ })+}++func messageTexts(msg *Message) []string {+ blocks := messageBlocks(msg)+ var out []string+ for _, block := range blocks {+ if normalizedBlockType(block.Type) != BlockText {+ continue+ }+ text := firstNonEmpty(block.Text, rawString(block.Content))+ if strings.TrimSpace(text) != "" {+ out = append(out, stripUserQueryTags(text))+ }+ }+ if len(out) == 0 {+ if text := rawString(msg.Content); strings.TrimSpace(text) != "" {+ out = append(out, stripUserQueryTags(text))+ }+ }+ return out+}++func messageBlocks(msg *Message) []Block {+ if len(msg.Content) == 0 {+ return nil+ }+ if msg.Content[0] == '"' {+ var text string+ if json.Unmarshal(msg.Content, &text) == nil {+ return []Block{{Type: BlockText, Text: text}}+ }+ }+ var blocks []Block+ if json.Unmarshal(msg.Content, &blocks) == nil {+ return blocks+ }+ return nil+}++func normalizedBlockType(value string) string {+ value = strings.TrimSpace(strings.ToLower(value))+ if value == "" {+ return BlockText+ }+ return value+}++func parseObject(raw json.RawMessage) any {+ if len(raw) == 0 {+ return map[string]any{}+ }+ var v any+ if err := json.Unmarshal(raw, &v); err != nil {+ return map[string]any{"raw": string(raw)}+ }+ if v == nil {+ return map[string]any{}+ }+ return v+}++func rawString(raw json.RawMessage) string {+ if len(raw) == 0 {+ return ""+ }+ var text string+ if json.Unmarshal(raw, &text) == nil {+ return text+ }+ var parts []Block+ if json.Unmarshal(raw, &parts) == nil {+ var b strings.Builder+ for _, part := range parts {+ if normalizedBlockType(part.Type) != BlockText {+ continue+ }+ if part.Text != "" {+ if b.Len() > 0 {+ b.WriteByte('\n')+ }+ b.WriteString(part.Text)+ }+ }+ return b.String()+ }+ var v any+ if json.Unmarshal(raw, &v) == nil {+ data, _ := json.Marshal(v)+ return string(data)+ }+ return string(raw)+}++func usageInfo(usage *TokenUsage) *schema.GenAIUsageInfo {+ info := &schema.GenAIUsageInfo{}+ if usage.InputTokens > 0 {+ info.InputTokens = int64Ptr(usage.InputTokens)+ }+ if usage.OutputTokens > 0 {+ info.OutputTokens = int64Ptr(usage.OutputTokens)+ }+ if usage.CacheCreationTokens > 0 {+ info.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(usage.CacheCreationTokens)}+ }+ if usage.CacheReadTokens > 0 {+ info.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(usage.CacheReadTokens)}+ }+ if usage.ThinkingTokens > 0 {+ info.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(usage.ThinkingTokens)}+ }+ return info+}++func parseTime(value string) time.Time {+ if strings.TrimSpace(value) == "" {+ return time.Time{}+ }+ if ts, err := time.Parse(time.RFC3339Nano, value); err == nil {+ return ts.UTC()+ }+ if ts, err := time.Parse(time.RFC3339, value); err == nil {+ return ts.UTC()+ }+ return time.Time{}+}++func unixMilliToRFC3339(ms int64) string {+ if ms <= 0 {+ return ""+ }+ return time.UnixMilli(ms).UTC().Format(time.RFC3339Nano)+}++func stripUserQueryTags(text string) string {+ text = strings.TrimSpace(text)+ start := strings.Index(text, "<user_query>")+ end := strings.Index(text, "</user_query>")+ if start >= 0 && end > start {+ return strings.TrimSpace(text[start+len("<user_query>") : end])+ }+ return text+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return strings.TrimSpace(value)+ }+ }+ return ""+}++func int64Ptr(v int64) *int64 { return &v }diff --git a/cli/beacon/internal/factorysession/mapper_test.go b/cli/beacon/internal/factorysession/mapper_test.gonew file mode 100644index 00000000..1f6193c3--- /dev/null+++ b/cli/beacon/internal/factorysession/mapper_test.go@@ -0,0 +1,93 @@+package factorysession++import (+ "encoding/json"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func TestMapSessionFactoryRecords(t *testing.T) {+ ref := SessionRef{+ ID: "session-1",+ Path: "/tmp/session-1.jsonl",+ CWD: "/repo",+ Model: "claude-opus-4-7",+ Settings: &Settings{TokenUsage: &TokenUsage{+ InputTokens: 10,+ OutputTokens: 20,+ CacheCreationTokens: 30,+ CacheReadTokens: 40,+ ThinkingTokens: 5,+ FactoryCredits: 12.5,+ }},+ SettingsUnixMS: 1770000001000,+ }+ records := []Record{+ mustRecord(t, 1, `{"type":"session_start","id":"session-1","title":"hello","cwd":"/repo"}`),+ mustRecord(t, 2, `{"type":"message","id":"u1","timestamp":"2026-05-16T22:11:04.611Z","message":{"role":"user","content":[{"type":"text","text":"<user_query>\nship it\n</user_query>"}]}}`),+ mustRecord(t, 3, `{"type":"message","id":"a1","timestamp":"2026-05-16T22:11:05.611Z","message":{"role":"assistant","model":"claude-opus-4-7","content":[{"type":"thinking","thinking":"checking"},{"type":"text","text":"done"},{"type":"tool_use","id":"call-1","name":"Bash","input":{"command":"go test ./..."}},{"type":"tool_result","tool_use_id":"call-1","content":"ok"}]}}`),+ mustRecord(t, 4, `{"type":"compaction_state","id":"c1","timestamp":"2026-05-16T22:11:06.611Z","summaryText":"older work","summaryTokens":123,"anchorMessage":{"id":"u1"}}`),+ }++ mapped := MapSession(ref, records, MapOptions{EmitSettingsUsage: true})+ actions := make([]string, 0, len(mapped))+ for _, item := range mapped {+ actions = append(actions, item.Event.Event.Action)+ if item.Event.Harness.Name != Harness {+ t.Fatalf("harness = %q, want %q", item.Event.Harness.Name, Harness)+ }+ if item.Event.Harness.CollectionMethod != "poll" {+ t.Fatalf("collection_method = %q, want poll", item.Event.Harness.CollectionMethod)+ }+ }+ want := []string{"session.started", "prompt.submitted", "agent.reasoning", "agent.message", "tool.invoked", "tool.completed", "session.compacted", "token.usage"}+ if !equalStrings(actions, want) {+ t.Fatalf("actions = %#v, want %#v", actions, want)+ }+ if got := findAction(t, mapped, "prompt.submitted").Prompt.Text; got != "ship it" {+ t.Fatalf("prompt = %q, want stripped user_query text", got)+ }+ tool := findAction(t, mapped, "tool.invoked")+ if tool.Tool == nil || tool.Tool.Name != "Bash" {+ t.Fatalf("tool = %#v, want Bash", tool.Tool)+ }+ usage := findAction(t, mapped, "token.usage")+ if usage.GenAI == nil || usage.GenAI.Usage == nil || usage.GenAI.Usage.InputTokens == nil || *usage.GenAI.Usage.InputTokens != 10 {+ t.Fatalf("usage = %#v, want input tokens", usage.GenAI)+ }+}++func mustRecord(t *testing.T, line int, text string) Record {+ t.Helper()+ var record Record+ if err := json.Unmarshal([]byte(text), &record); err != nil {+ t.Fatal(err)+ }+ record.Line = line+ record.Raw = []byte(text)+ return record+}++func findAction(t *testing.T, mapped []MappedEvent, action string) *schema.Event {+ t.Helper()+ for i := range mapped {+ if mapped[i].Event.Event.Action == action {+ return &mapped[i].Event+ }+ }+ t.Fatalf("action %q not found", action)+ return nil+}++func equalStrings(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}diff --git a/cli/beacon/internal/factorysession/store.go b/cli/beacon/internal/factorysession/store.gonew file mode 100644index 00000000..6b82fe96--- /dev/null+++ b/cli/beacon/internal/factorysession/store.go@@ -0,0 +1,237 @@+package factorysession++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++const (+ MaxLineBytes = 4 << 20+ MaxSettingsBytes = 1 << 20+)++type Store struct {+ Dir string+}++type SessionRef struct {+ ID string+ ProjectDirName string+ Path string+ SettingsPath string+ CWD string+ Title string+ Model string+ Settings *Settings+ ModTimeUnixMS int64+ SettingsUnixMS int64+ SizeBytes int64+}++type ReadStats struct {+ Lines int+ Malformed int+ Partial bool+}++func DefaultSessionsDir() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", fmt.Errorf("resolve home directory: %w", err)+ }+ if strings.TrimSpace(home) == "" {+ return "", errors.New("home directory is empty")+ }+ return filepath.Join(home, ".factory", "sessions"), nil+}++func NewStore(dir string) (*Store, error) {+ if strings.TrimSpace(dir) != "" {+ return &Store{Dir: dir}, nil+ }+ def, err := DefaultSessionsDir()+ if err != nil {+ return nil, err+ }+ return &Store{Dir: def}, nil+}++func (s *Store) Exists() bool {+ info, err := os.Stat(s.Dir)+ return err == nil && info.IsDir()+}++func (s *Store) List() ([]SessionRef, error) {+ projects, err := os.ReadDir(s.Dir)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return nil, fmt.Errorf("read Factory sessions directory: %w", err)+ }+ var refs []SessionRef+ for _, project := range projects {+ if !project.IsDir() {+ continue+ }+ projectDir := filepath.Join(s.Dir, project.Name())+ files, err := os.ReadDir(projectDir)+ if err != nil {+ continue+ }+ for _, file := range files {+ if file.IsDir() || !strings.HasSuffix(file.Name(), ".jsonl") {+ continue+ }+ id := strings.TrimSuffix(file.Name(), ".jsonl")+ if err := validateSessionID(id); err != nil {+ continue+ }+ path := filepath.Join(projectDir, file.Name())+ info, err := os.Stat(path)+ if err != nil || info.IsDir() {+ continue+ }+ ref := SessionRef{+ ID: id,+ ProjectDirName: project.Name(),+ Path: path,+ SettingsPath: filepath.Join(projectDir, id+".settings.json"),+ CWD: decodeProjectDirName(project.Name()),+ ModTimeUnixMS: info.ModTime().UnixMilli(),+ SizeBytes: info.Size(),+ }+ if header, err := ReadHeader(path); err == nil && header != nil {+ if header.CWD != "" {+ ref.CWD = header.CWD+ }+ ref.Title = header.Title+ }+ if settings, mtime, err := ReadSettings(ref.SettingsPath); err == nil {+ ref.Settings = settings+ ref.SettingsUnixMS = mtime+ ref.Model = settings.Model+ }+ refs = append(refs, ref)+ }+ }+ sort.SliceStable(refs, func(i, j int) bool {+ if refs[i].ModTimeUnixMS != refs[j].ModTimeUnixMS {+ return refs[i].ModTimeUnixMS < refs[j].ModTimeUnixMS+ }+ return refs[i].ID < refs[j].ID+ })+ return refs, nil+}++func ReadHeader(path string) (*Record, error) {+ file, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer file.Close()+ reader := bufio.NewReaderSize(file, 64*1024)+ line, err := reader.ReadBytes('\n')+ if err != nil && !errors.Is(err, io.EOF) {+ return nil, err+ }+ line = []byte(strings.TrimSpace(string(line)))+ if len(line) == 0 {+ return nil, nil+ }+ var record Record+ if err := json.Unmarshal(line, &record); err != nil {+ return nil, err+ }+ if record.Type != RecordSessionStart {+ return nil, nil+ }+ return &record, nil+}++func ReadSettings(path string) (*Settings, int64, error) {+ info, err := os.Stat(path)+ if err != nil {+ return nil, 0, err+ }+ if info.Size() > MaxSettingsBytes {+ return nil, 0, fmt.Errorf("Factory settings %s is %d bytes, over the %d-byte limit", path, info.Size(), MaxSettingsBytes)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, 0, err+ }+ var raw map[string]any+ if err := json.Unmarshal(data, &raw); err != nil {+ return nil, 0, err+ }+ var settings Settings+ if err := json.Unmarshal(data, &settings); err != nil {+ return nil, 0, err+ }+ settings.Raw = raw+ return &settings, info.ModTime().UnixMilli(), nil+}++func (s *Store) Read(ref SessionRef) ([]Record, ReadStats, error) {+ file, err := os.Open(ref.Path)+ if err != nil {+ return nil, ReadStats{}, err+ }+ defer file.Close()+ scanner := bufio.NewScanner(file)+ scanner.Buffer(make([]byte, 0, 64*1024), MaxLineBytes)+ var records []Record+ stats := ReadStats{}+ for scanner.Scan() {+ stats.Lines+++ text := strings.TrimSpace(scanner.Text())+ if text == "" {+ continue+ }+ var record Record+ if err := json.Unmarshal([]byte(text), &record); err != nil {+ stats.Malformed+++ continue+ }+ record.Line = stats.Lines+ record.Raw = json.RawMessage(append([]byte(nil), text...))+ records = append(records, record)+ }+ if err := scanner.Err(); err != nil {+ stats.Partial = true+ return records, stats, nil+ }+ return records, stats, nil+}++func validateSessionID(id string) error {+ if id == "" || id == "." || id == ".." || len(id) > 255 {+ return fmt.Errorf("invalid Factory session id %q", id)+ }+ for i := 0; i < len(id); i++ {+ c := id[i]+ switch {+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':+ case c == '-' || c == '_':+ default:+ return fmt.Errorf("invalid Factory session id %q", id)+ }+ }+ return nil+}++func decodeProjectDirName(name string) string {+ if strings.HasPrefix(name, "-") {+ return "/" + strings.ReplaceAll(strings.TrimPrefix(name, "-"), "-", "/")+ }+ return name+}diff --git a/cli/beacon/internal/factorysession/types.go b/cli/beacon/internal/factorysession/types.gonew file mode 100644index 00000000..5f38d105--- /dev/null+++ b/cli/beacon/internal/factorysession/types.go@@ -0,0 +1,101 @@+// Package factorysession reads Factory Droid's local session store and maps it to Beacon events.+//+// Factory already has live Beacon support through OTLP plus optional hooks. This package covers+// the other source Factory keeps on disk:+//+// ~/.factory/sessions/<encoded-working-directory>/<session-id>.jsonl+// ~/.factory/sessions/<encoded-working-directory>/<session-id>.settings.json+//+// Reading that store is a poll collection path: Beacon sees committed records after the fact, so+// every event emitted here carries harness.collection_method=poll.+package factorysession++import (+ "encoding/json"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++const Harness = "factory"++const (+ RecordSessionStart = "session_start"+ RecordMessage = "message"+ RecordTodoState = "todo_state"+ RecordCompactionState = "compaction_state"+)++const (+ RoleUser = "user"+ RoleAssistant = "assistant"+ RoleTool = "tool"+)++const (+ BlockText = "text"+ BlockThinking = "thinking"+ BlockToolUse = "tool_use"+ BlockToolResult = "tool_result"+)++type Record struct {+ Line int `json:"-"`+ Type string `json:"type"`+ ID string `json:"id"`+ Timestamp string `json:"timestamp"`+ Title string `json:"title"`+ CWD string `json:"cwd"`+ Message *Message `json:"message"`+ Raw json.RawMessage `json:"-"`++ SummaryText string `json:"summaryText"`+ SummaryTokens *int64 `json:"summaryTokens"`+ AnchorMessage *struct {+ ID string `json:"id"`+ } `json:"anchorMessage"`+}++type Message struct {+ Role string `json:"role"`+ Visibility string `json:"visibility"`+ Model string `json:"model"`+ Content json.RawMessage `json:"content"`+ Thinking string `json:"thinking"`+}++type Block struct {+ Type string `json:"type"`+ ID string `json:"id"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ Name string `json:"name"`+ Input json.RawMessage `json:"input"`+ Content json.RawMessage `json:"content"`+ ToolUseID string `json:"tool_use_id"`+ IsError bool `json:"is_error"`+}++type Settings struct {+ Model string `json:"model"`+ ProviderLock string `json:"providerLock"`+ AssistantActiveTimeMs int64 `json:"assistantActiveTimeMs"`+ TokenUsage *TokenUsage `json:"tokenUsage"`+ InclusiveTokenUsage *TokenUsage `json:"inclusiveTokenUsage"`+ ChildInclusiveTokenUsage map[string]any `json:"childInclusiveTokenUsageBySessionId"`+ Raw map[string]any `json:"-"`+}++type TokenUsage struct {+ InputTokens int64 `json:"inputTokens"`+ OutputTokens int64 `json:"outputTokens"`+ CacheCreationTokens int64 `json:"cacheCreationTokens"`+ CacheReadTokens int64 `json:"cacheReadTokens"`+ ThinkingTokens int64 `json:"thinkingTokens"`+ FactoryCredits float64 `json:"factoryCredits"`+}++type MappedEvent struct {+ SourceLine int+ DedupID string+ Event schema.Event+}diff --git a/docs/runtimes/factory-droid.mdx b/docs/runtimes/factory-droid.mdxindex b5be4aeb..29047c89 100644--- a/docs/runtimes/factory-droid.mdx+++ b/docs/runtimes/factory-droid.mdx@@ -5,7 +5,7 @@ description: "Asymptote support details for Factory Droid endpoint telemetry"## Runtime overview-Asymptote supports Factory Droid through an OTLP HTTP launch environment plus optional hook telemetry.+Asymptote supports Factory Droid through an OTLP HTTP launch environment, optional hook telemetry, and a local session-store sync for historical sessions.## Prerequisites@@ -15,11 +15,12 @@ Before enabling Factory Droid telemetry, make sure:- `beacon endpoint install` has run so the local collector, shared endpoint config, and runtime log paths exist.- Droid's launch environment sets `OTEL_TELEMETRY_ENDPOINT=http://127.0.0.1:4318` through MDM or another customer-owned policy.- Optional hook telemetry is installed with `beacon endpoint hooks install --harness factory`.+- Historical session telemetry can be synced from Factory's local session store with `beacon endpoint factory sync`.- Factory Droid is restarted after launch-environment or hook changes so new sessions use the updated settings.## Collection path-Factory Droid can send OTLP HTTP telemetry to Asymptote's local collector. Factory hooks can also invoke Asymptote's hook adapter for richer runtime events where Factory exposes hook payloads.+Factory Droid can send OTLP HTTP telemetry to Asymptote's local collector. Factory hooks can also invoke Asymptote's hook adapter for richer runtime events where Factory exposes hook payloads. Beacon can also read committed Factory session records from `~/.factory/sessions` and convert them into endpoint events marked `harness.collection_method=poll`.## Discovery and status@@ -27,6 +28,8 @@ Asymptote detects Factory Droid through the `droid` executable and validates `OTUse `beacon endpoint discover`, `beacon endpoint status`, or `beacon endpoint hooks status --harness factory` to inspect Factory Droid support.+Use `beacon endpoint factory status` to inspect local Factory sessions and how much Beacon has synced.+## Install or configuration support`beacon endpoint install` prepares the collector, shared endpoint config, and runtime log paths. Factory Droid's launch environment is managed by MDM or customer policy.@@ -39,12 +42,21 @@ beacon endpoint hooks install --harness factory`--harness droid` is also accepted for Factory Droid hook installs.+Sync Factory's local session store separately:++```bash title="Sync Factory session telemetry"+beacon endpoint factory sync+```++For scheduled collection, run `beacon endpoint factory sync --watch`, or run one-shot `sync` from your scheduler. `--print` maps events without writing the runtime log or advancing the cursor.+## Telemetry coverage| Area | Support ||------|---------|| Prompt telemetry | Supported through `UserPromptSubmit` hooks |-| Command, tool, and file telemetry | Supported for session, write/edit/create tool use, stop, session-end, and available OTLP telemetry |+| Command, tool, and file telemetry | Supported for session, write/edit/create hook payloads, committed session tool calls/results, stop, session-end, and available OTLP telemetry |+| Historical sessions | Supported through `beacon endpoint factory sync`, which reads `~/.factory/sessions` locally and offline || Local JSONL and dashboard | Supported || MDM deployment | Supported for the endpoint agent. Factory launch environment and user/project hooks are managed in the user's Droid context |diff --git a/docs/security/data-inventory.mdx b/docs/security/data-inventory.mdxindex 34622735..ea0124fa 100644--- a/docs/security/data-inventory.mdx+++ b/docs/security/data-inventory.mdx@@ -21,7 +21,7 @@ Beacon writes normalized endpoint events only when supported runtimes provide te| Qwen Code | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, permission request/approval, subagent, stop, session-end, command, and file telemetry; the verbatim hook payload is retained under `raw.qwen` || Devin CLI | Native hooks | Session, prompt, pre-tool, post-tool, permission request, stop, session-end, approval, and file telemetry || Devin Desktop | Cascade/Windsurf hooks | Prompt, command, MCP tool, file read, and file write telemetry where Desktop exposes Cascade hook payloads |-| Factory Droid | OTLP HTTP plus optional hooks | Session, prompt, write/edit/create tool use, stop, session-end, and available OTLP telemetry |+| Factory Droid | OTLP HTTP plus optional hooks plus local session-store sync | Session, prompt, assistant messages, reasoning, tool calls/results, write/edit/create hook payloads, token usage, stop, session-end, and available OTLP telemetry || Cursor | Native hooks | Prompt, tool, shell command, MCP-like, approval, and file edit telemetry || Claude Cowork | Admin-configured OTLP | Prompt and assistant response content; approvals; command, tool, file, and MCP activity; session lifecycle; model and token usage; runtime-reported cost; source user identifier and cloud origin when emitted through Cowork OTLP || OpenClaw Gateway | Managed plugin, plus gateway-configured OTLP/HTTP | Prompts (the inbound chat message, with the sender and the chat channel), tool inputs and results, commands with exit code and output, file activity and diffs, MCP calls, agent response text, token usage, session and subagent lifecycle, and compaction; the verbatim hook envelope is retained under `raw.openclaw`. Gateway traces and metrics come separately from OpenClaw's own diagnostics export |