From d43037bf827f7b436a1f81970aa4d64384c038b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Sun, 25 Jan 2026 00:16:01 +0000 Subject: [PATCH] fix: filter upstream commits, fix ahead/behind, and remove duplicate types (#91) --- apps/backend/CODE_REVIEW_ISSUES.md | 52 --- .../internal/agent/lifecycle/event_types.go | 83 +++- .../internal/agent/lifecycle/events.go | 124 ++--- .../internal/agent/lifecycle/manager.go | 7 + .../internal/agent/lifecycle/streams.go | 6 + .../internal/agentctl/client/client.go | 6 + .../internal/agentctl/server/api/git.go | 1 - .../server/process/workspace_tracker.go | 316 ++++++++++++- .../server/process/workspace_tracker_test.go | 298 ++++++++++++ .../internal/agentctl/types/streams/git.go | 13 + apps/backend/internal/agentctl/types/types.go | 14 + apps/backend/internal/events/types.go | 52 +-- .../websocket/session_notifications.go | 4 +- .../internal/orchestrator/event_handlers.go | 297 +++++++++--- apps/backend/internal/orchestrator/service.go | 3 +- .../internal/orchestrator/watcher/watcher.go | 131 +----- .../task/handlers/process_handlers_test.go | 3 + .../internal/task/repository/interface.go | 1 + .../task/repository/sqlite/git_snapshots.go | 5 + apps/backend/pkg/websocket/actions.go | 8 +- .../session-runtime/session-runtime-slice.ts | 5 + .../lib/state/slices/session-runtime/types.ts | 1 + apps/web/lib/state/store.ts | 1 + apps/web/lib/types/backend.ts | 66 +-- apps/web/lib/types/git-events.ts | 91 ++++ apps/web/lib/ws/handlers/git-status.ts | 120 +++-- docs/manual-git-commit-sync-analysis.md | 438 ++++++++++++++++++ 27 files changed, 1706 insertions(+), 440 deletions(-) delete mode 100644 apps/backend/CODE_REVIEW_ISSUES.md create mode 100644 apps/backend/internal/agentctl/server/process/workspace_tracker_test.go create mode 100644 apps/web/lib/types/git-events.ts create mode 100644 docs/manual-git-commit-sync-analysis.md diff --git a/apps/backend/CODE_REVIEW_ISSUES.md b/apps/backend/CODE_REVIEW_ISSUES.md deleted file mode 100644 index 014ea2ceb2..0000000000 --- a/apps/backend/CODE_REVIEW_ISSUES.md +++ /dev/null @@ -1,52 +0,0 @@ -# Backend Code Review Issues - -Generated: 2026-01-11 - -## High Priority - -### 1. Security TODOs -- [ ] `internal/gateway/websocket/handler.go:20` - TODO: In production, validate origin -- [ ] `internal/gateway/websocket/handler.go:46` - TODO: Implement proper JWT validation - -### 2. Deprecated API -- [ ] `internal/agent/docker/client.go:300-301` - `inspect.NetworkSettings.IPAddress` is deprecated (removed in Docker v29). Use `NetworkSettings.Networks` instead. - -## Medium Priority - -### 3. Unused Functions -- [ ] `internal/agent/lifecycle/manager.go:641` - `updateInstanceComplete` is unused -- [ ] `internal/agent/streaming/reader.go:232` - `marshalMessage` is unused -- [ ] `internal/task/repository/sqlite.go:617` - `scanTasks` is unused - -### 4. Unused Field / Race Condition -- [ ] `internal/gateway/websocket/client.go:36` - `mu sync.RWMutex` field is unused. Either use it to protect `subscriptions` or remove it. - -### 5. Outdated Comment -- [ ] `internal/agent/agentctl/acp.go:108` - Comment references `needs_input` which was removed. Update to: `// The StopReason indicates why the agent stopped (e.g., "end_turn")` - -## Low Priority - -### 6. Unused Test Helpers -- [ ] `internal/agent/lifecycle/manager_test.go:130` - `testManager` type unused -- [ ] `internal/agent/lifecycle/manager_test.go:135` - `newTestManager` function unused - -### 7. Code Style (staticcheck S1000) -- [ ] `internal/agentctl/api/acp.go:215` - Use `for range ch` instead of `for { select {} }` -- [ ] `internal/agentctl/api/acp.go:336` - Use `for range ch` instead of `for { select {} }` - -### 8. Hardcoded Sleep -- [ ] `internal/agent/lifecycle/manager.go:253` - `time.Sleep(500 * time.Millisecond)` - Consider proper ready-check mechanism - -### 9. Ignored Error -- [ ] `internal/task/repository/sqlite.go:626` - `_ = json.Unmarshal(...)` ignores error - -## Questions / Review Needed - -### 10. InputRequestHandler Redundancy -Files: `internal/orchestrator/service.go` (lines 44-45, 71, 387-389, 507-512), `cmd/kandev/main.go` (lines 305-363) - -The `InputRequestHandler` and `handleInputRequired` functionality still exists using `input_required` message type. Is this still needed given the new comment-based conversation flow? - -### 11. Other TODOs -- [ ] `internal/gateway/websocket/hub.go:127` - TODO: Add topic-based routing for task-specific notifications - diff --git a/apps/backend/internal/agent/lifecycle/event_types.go b/apps/backend/internal/agent/lifecycle/event_types.go index 0f146140dc..425499de6b 100644 --- a/apps/backend/internal/agent/lifecycle/event_types.go +++ b/apps/backend/internal/agent/lifecycle/event_types.go @@ -64,11 +64,44 @@ type AgentStreamEventPayload struct { Data *AgentStreamEventData `json:"data"` } -// GitStatusEventPayload is the payload for git status updates. -type GitStatusEventPayload struct { - TaskID string `json:"task_id"` - SessionID string `json:"session_id"` - AgentID string `json:"agent_id"` +// GitEventType discriminates the type of git event +type GitEventType string + +const ( + GitEventTypeStatusUpdate GitEventType = "status_update" + GitEventTypeCommitCreated GitEventType = "commit_created" + GitEventTypeCommitsReset GitEventType = "commits_reset" + GitEventTypeSnapshotCreated GitEventType = "snapshot_created" +) + +// GitEventPayload is a unified payload for all git-related WebSocket events. +// Uses discriminated union pattern with Type field. +type GitEventPayload struct { + Type GitEventType `json:"type"` + TaskID string `json:"task_id,omitempty"` + SessionID string `json:"session_id"` + AgentID string `json:"agent_id,omitempty"` + Timestamp string `json:"timestamp"` + + // For status_update + Status *GitStatusData `json:"status,omitempty"` + + // For commit_created + Commit *GitCommitData `json:"commit,omitempty"` + + // For commits_reset + Reset *GitResetData `json:"reset,omitempty"` + + // For snapshot_created + Snapshot *GitSnapshotData `json:"snapshot,omitempty"` +} + +// GetSessionID returns the session ID for this event (used by event routing). +func (p GitEventPayload) GetSessionID() string { + return p.SessionID +} + +type GitStatusData struct { Branch string `json:"branch"` RemoteBranch string `json:"remote_branch,omitempty"` HeadCommit string `json:"head_commit,omitempty"` @@ -80,34 +113,42 @@ type GitStatusEventPayload struct { Renamed []string `json:"renamed"` Ahead int `json:"ahead"` Behind int `json:"behind"` - Files interface{} `json:"files,omitempty"` // map[string]FileInfo from agentctl - Timestamp string `json:"timestamp"` + Files interface{} `json:"files,omitempty"` } -// GetSessionID returns the session ID for this event (used by event routing). -func (p GitStatusEventPayload) GetSessionID() string { - return p.SessionID -} - -// GitCommitEventPayload is the payload for git commit events. -type GitCommitEventPayload struct { - TaskID string `json:"task_id"` - SessionID string `json:"session_id"` - AgentID string `json:"agent_id"` +type GitCommitData struct { + ID string `json:"id,omitempty"` CommitSHA string `json:"commit_sha"` ParentSHA string `json:"parent_sha"` - Message string `json:"message"` + Message string `json:"commit_message"` AuthorName string `json:"author_name"` AuthorEmail string `json:"author_email"` FilesChanged int `json:"files_changed"` Insertions int `json:"insertions"` Deletions int `json:"deletions"` CommittedAt string `json:"committed_at"` + CreatedAt string `json:"created_at,omitempty"` } -// GetSessionID returns the session ID for this event (used by event routing). -func (p GitCommitEventPayload) GetSessionID() string { - return p.SessionID +type GitResetData struct { + PreviousHead string `json:"previous_head"` + CurrentHead string `json:"current_head"` + DeletedCount int `json:"deleted_count"` +} + +type GitSnapshotData struct { + ID string `json:"id"` + SessionID string `json:"session_id"` + SnapshotType string `json:"snapshot_type"` + Branch string `json:"branch"` + RemoteBranch string `json:"remote_branch"` + HeadCommit string `json:"head_commit"` + BaseCommit string `json:"base_commit"` + Ahead int `json:"ahead"` + Behind int `json:"behind"` + Files interface{} `json:"files,omitempty"` + TriggeredBy string `json:"triggered_by"` + CreatedAt string `json:"created_at"` } // FileChangeEventPayload is the payload for file change notifications. diff --git a/apps/backend/internal/agent/lifecycle/events.go b/apps/backend/internal/agent/lifecycle/events.go index 57af6f3d5e..59d80ad1a5 100644 --- a/apps/backend/internal/agent/lifecycle/events.go +++ b/apps/backend/internal/agent/lifecycle/events.go @@ -170,77 +170,87 @@ func (p *EventPublisher) PublishAgentStreamEventPayload(payload *AgentStreamEven } } -// PublishGitStatus publishes a git status update to the event bus. -func (p *EventPublisher) PublishGitStatus(execution *AgentExecution, update *agentctl.GitStatusUpdate) { +// PublishGitEvent publishes a unified git event to the event bus. +func (p *EventPublisher) PublishGitEvent(payload *GitEventPayload) { if p.eventBus == nil { return } - sessionID := execution.SessionID - - payload := GitStatusEventPayload{ - TaskID: execution.TaskID, - SessionID: sessionID, - AgentID: execution.ID, - Branch: update.Branch, - RemoteBranch: update.RemoteBranch, - Modified: update.Modified, - Added: update.Added, - Deleted: update.Deleted, - Untracked: update.Untracked, - Renamed: update.Renamed, - Ahead: update.Ahead, - Behind: update.Behind, - Files: update.Files, - Timestamp: update.Timestamp.Format(time.RFC3339Nano), + if payload.Timestamp == "" { + payload.Timestamp = time.Now().Format(time.RFC3339Nano) } - event := bus.NewEvent(events.GitStatusUpdated, "agent-manager", payload) - subject := events.BuildGitStatusSubject(sessionID) + event := bus.NewEvent(events.GitEvent, "lifecycle", payload) + subject := events.BuildGitEventSubject(payload.SessionID) if err := p.eventBus.Publish(context.Background(), subject, event); err != nil { - p.logger.Error("failed to publish git status event", - zap.String("instance_id", execution.ID), - zap.String("task_id", execution.TaskID), - zap.String("session_id", sessionID), + p.logger.Error("failed to publish git event", + zap.String("session_id", payload.SessionID), + zap.String("type", string(payload.Type)), zap.Error(err)) } } -// PublishGitCommit publishes a git commit event to the event bus. +// PublishGitStatus publishes a git status update event. +func (p *EventPublisher) PublishGitStatus(execution *AgentExecution, update *agentctl.GitStatusUpdate) { + p.PublishGitEvent(&GitEventPayload{ + Type: GitEventTypeStatusUpdate, + TaskID: execution.TaskID, + SessionID: execution.SessionID, + AgentID: execution.ID, + Timestamp: update.Timestamp.Format(time.RFC3339Nano), + Status: &GitStatusData{ + Branch: update.Branch, + RemoteBranch: update.RemoteBranch, + HeadCommit: update.HeadCommit, + BaseCommit: update.BaseCommit, + Modified: update.Modified, + Added: update.Added, + Deleted: update.Deleted, + Untracked: update.Untracked, + Renamed: update.Renamed, + Ahead: update.Ahead, + Behind: update.Behind, + Files: update.Files, + }, + }) +} + +// PublishGitCommit publishes a git commit created event. func (p *EventPublisher) PublishGitCommit(execution *AgentExecution, commit *agentctl.GitCommitNotification) { - if p.eventBus == nil { - return - } + p.PublishGitEvent(&GitEventPayload{ + Type: GitEventTypeCommitCreated, + TaskID: execution.TaskID, + SessionID: execution.SessionID, + AgentID: execution.ID, + Timestamp: time.Now().Format(time.RFC3339Nano), + Commit: &GitCommitData{ + CommitSHA: commit.CommitSHA, + ParentSHA: commit.ParentSHA, + Message: commit.Message, + AuthorName: commit.AuthorName, + AuthorEmail: commit.AuthorEmail, + FilesChanged: commit.FilesChanged, + Insertions: commit.Insertions, + Deletions: commit.Deletions, + CommittedAt: commit.CommittedAt.Format(time.RFC3339), + }, + }) +} - sessionID := execution.SessionID - - payload := GitCommitEventPayload{ - TaskID: execution.TaskID, - SessionID: sessionID, - AgentID: execution.ID, - CommitSHA: commit.CommitSHA, - ParentSHA: commit.ParentSHA, - Message: commit.Message, - AuthorName: commit.AuthorName, - AuthorEmail: commit.AuthorEmail, - FilesChanged: commit.FilesChanged, - Insertions: commit.Insertions, - Deletions: commit.Deletions, - CommittedAt: commit.CommittedAt.Format(time.RFC3339Nano), - } - - event := bus.NewEvent(events.GitCommitCreated, "agent-manager", payload) - subject := events.BuildGitCommitSubject(sessionID) - - if err := p.eventBus.Publish(context.Background(), subject, event); err != nil { - p.logger.Error("failed to publish git commit event", - zap.String("instance_id", execution.ID), - zap.String("task_id", execution.TaskID), - zap.String("session_id", sessionID), - zap.String("commit_sha", commit.CommitSHA), - zap.Error(err)) - } +// PublishGitReset publishes a git reset event (HEAD moved backward). +func (p *EventPublisher) PublishGitReset(execution *AgentExecution, reset *agentctl.GitResetNotification) { + p.PublishGitEvent(&GitEventPayload{ + Type: GitEventTypeCommitsReset, + TaskID: execution.TaskID, + SessionID: execution.SessionID, + AgentID: execution.ID, + Timestamp: reset.Timestamp.Format(time.RFC3339Nano), + Reset: &GitResetData{ + PreviousHead: reset.PreviousHead, + CurrentHead: reset.CurrentHead, + }, + }) } // PublishFileChange publishes a file change notification to the event bus. diff --git a/apps/backend/internal/agent/lifecycle/manager.go b/apps/backend/internal/agent/lifecycle/manager.go index 61557ad2a3..fcf4c87f07 100644 --- a/apps/backend/internal/agent/lifecycle/manager.go +++ b/apps/backend/internal/agent/lifecycle/manager.go @@ -118,6 +118,7 @@ func NewManager( OnAgentEvent: mgr.handleAgentEvent, OnGitStatus: mgr.handleGitStatusUpdate, OnGitCommit: mgr.handleGitCommitCreated, + OnGitReset: mgr.handleGitResetDetected, OnFileChange: mgr.handleFileChangeNotification, OnShellOutput: mgr.handleShellOutput, OnShellExit: mgr.handleShellExit, @@ -1120,6 +1121,12 @@ func (m *Manager) handleGitCommitCreated(execution *AgentExecution, commit *agen m.eventPublisher.PublishGitCommit(execution, commit) } +// handleGitResetDetected processes git reset events from the workspace tracker +func (m *Manager) handleGitResetDetected(execution *AgentExecution, reset *agentctl.GitResetNotification) { + // Publish reset event to event bus for orchestrator handling (commit sync) + m.eventPublisher.PublishGitReset(execution, reset) +} + // handleFileChangeNotification processes file change notifications from the workspace tracker func (m *Manager) handleFileChangeNotification(execution *AgentExecution, notification *agentctl.FileChangeNotification) { m.eventPublisher.PublishFileChange(execution, notification) diff --git a/apps/backend/internal/agent/lifecycle/streams.go b/apps/backend/internal/agent/lifecycle/streams.go index 7f4e61a9e2..2ab831c73d 100644 --- a/apps/backend/internal/agent/lifecycle/streams.go +++ b/apps/backend/internal/agent/lifecycle/streams.go @@ -15,6 +15,7 @@ type StreamCallbacks struct { OnAgentEvent func(execution *AgentExecution, event agentctl.AgentEvent) OnGitStatus func(execution *AgentExecution, update *agentctl.GitStatusUpdate) OnGitCommit func(execution *AgentExecution, commit *agentctl.GitCommitNotification) + OnGitReset func(execution *AgentExecution, reset *agentctl.GitResetNotification) OnFileChange func(execution *AgentExecution, notification *agentctl.FileChangeNotification) OnShellOutput func(execution *AgentExecution, data string) OnShellExit func(execution *AgentExecution, code int) @@ -126,6 +127,11 @@ func (sm *StreamManager) connectWorkspaceStream(execution *AgentExecution) { sm.callbacks.OnGitCommit(execution, commit) } }, + OnGitReset: func(reset *agentctl.GitResetNotification) { + if sm.callbacks.OnGitReset != nil { + sm.callbacks.OnGitReset(execution, reset) + } + }, OnFileChange: func(notification *agentctl.FileChangeNotification) { if sm.callbacks.OnFileChange != nil { sm.callbacks.OnFileChange(execution, notification) diff --git a/apps/backend/internal/agentctl/client/client.go b/apps/backend/internal/agentctl/client/client.go index ba3642c4c2..84d532534f 100644 --- a/apps/backend/internal/agentctl/client/client.go +++ b/apps/backend/internal/agentctl/client/client.go @@ -255,6 +255,7 @@ func (c *Client) BaseURL() string { type ( GitStatusUpdate = types.GitStatusUpdate GitCommitNotification = types.GitCommitNotification + GitResetNotification = types.GitResetNotification FileInfo = types.FileInfo FileListUpdate = types.FileListUpdate FileEntry = types.FileEntry @@ -567,6 +568,7 @@ type WorkspaceStreamCallbacks struct { OnShellExit func(code int) OnGitStatus func(update *GitStatusUpdate) OnGitCommit func(notification *GitCommitNotification) + OnGitReset func(notification *GitResetNotification) OnFileChange func(notification *FileChangeNotification) OnFileList func(update *FileListUpdate) OnProcessOutput func(output *types.ProcessOutput) @@ -647,6 +649,10 @@ func (c *Client) StreamWorkspace(ctx context.Context, callbacks WorkspaceStreamC if callbacks.OnGitCommit != nil && msg.GitCommit != nil { callbacks.OnGitCommit(msg.GitCommit) } + case types.WorkspaceMessageTypeGitReset: + if callbacks.OnGitReset != nil && msg.GitReset != nil { + callbacks.OnGitReset(msg.GitReset) + } case types.WorkspaceMessageTypeFileChange: if callbacks.OnFileChange != nil && msg.FileChange != nil { callbacks.OnFileChange(msg.FileChange) diff --git a/apps/backend/internal/agentctl/server/api/git.go b/apps/backend/internal/agentctl/server/api/git.go index b58e8a1789..f830cc6eb4 100644 --- a/apps/backend/internal/agentctl/server/api/git.go +++ b/apps/backend/internal/agentctl/server/api/git.go @@ -332,4 +332,3 @@ func (s *Server) handleGitError(c *gin.Context, operation string, err error) { Error: err.Error(), }) } - diff --git a/apps/backend/internal/agentctl/server/process/workspace_tracker.go b/apps/backend/internal/agentctl/server/process/workspace_tracker.go index 4d56b59f23..0ad9cd8e81 100644 --- a/apps/backend/internal/agentctl/server/process/workspace_tracker.go +++ b/apps/backend/internal/agentctl/server/process/workspace_tracker.go @@ -19,6 +19,9 @@ import ( "go.uber.org/zap" ) +// DefaultGitPollInterval is the default interval for polling git status +const DefaultGitPollInterval = 3 * time.Second + // WorkspaceTracker monitors workspace changes and provides real-time updates type WorkspaceTracker struct { workDir string @@ -29,6 +32,10 @@ type WorkspaceTracker struct { currentFiles types.FileListUpdate mu sync.RWMutex + // Cached git state for detecting manual operations + cachedHeadSHA string + gitStateMu sync.RWMutex + // Unified workspace stream subscribers workspaceStreamSubscribers map[types.WorkspaceStreamSubscriber]struct{} workspaceSubMu sync.RWMutex @@ -39,6 +46,9 @@ type WorkspaceTracker struct { // Debounce channel for filesystem change events fsChangeTrigger chan struct{} + // Git polling interval + gitPollInterval time.Duration + // Control stopCh chan struct{} wg sync.WaitGroup @@ -59,6 +69,7 @@ func NewWorkspaceTracker(workDir string, log *logger.Logger) *WorkspaceTracker { workspaceStreamSubscribers: make(map[types.WorkspaceStreamSubscriber]struct{}), watcher: watcher, fsChangeTrigger: make(chan struct{}, 1), // Buffered to avoid blocking + gitPollInterval: DefaultGitPollInterval, stopCh: make(chan struct{}), } } @@ -77,6 +88,10 @@ func (wt *WorkspaceTracker) Start(ctx context.Context) { wt.wg.Add(1) go wt.monitorLoop(ctx) + // Start git polling for detecting manual git operations + wt.wg.Add(1) + go wt.pollGitChanges(ctx) + // Start filesystem watcher if available if wt.watcher != nil { wt.wg.Add(1) @@ -166,6 +181,261 @@ func (wt *WorkspaceTracker) monitorLoop(ctx context.Context) { } } +// pollGitChanges periodically checks for git changes (commits, branch switches) +// This catches manual git operations done via shell that file watching might miss +func (wt *WorkspaceTracker) pollGitChanges(ctx context.Context) { + defer wt.wg.Done() + + ticker := time.NewTicker(wt.gitPollInterval) + defer ticker.Stop() + + // Initialize cached HEAD SHA + wt.gitStateMu.Lock() + wt.cachedHeadSHA = wt.getHeadSHA(ctx) + wt.gitStateMu.Unlock() + + wt.logger.Info("git polling started", + zap.Duration("interval", wt.gitPollInterval), + zap.String("initial_head", wt.cachedHeadSHA)) + + for { + select { + case <-ctx.Done(): + return + case <-wt.stopCh: + return + case <-ticker.C: + wt.checkGitChanges(ctx) + } + } +} + +// getHeadSHA returns the current HEAD commit SHA +func (wt *WorkspaceTracker) getHeadSHA(ctx context.Context) string { + cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD") + cmd.Dir = wt.workDir + out, err := cmd.Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + +// checkGitChanges checks if HEAD has changed and processes new commits +func (wt *WorkspaceTracker) checkGitChanges(ctx context.Context) { + currentHead := wt.getHeadSHA(ctx) + if currentHead == "" { + return + } + + wt.gitStateMu.RLock() + previousHead := wt.cachedHeadSHA + wt.gitStateMu.RUnlock() + + if currentHead == previousHead { + return // No change + } + + wt.logger.Info("git HEAD changed, syncing", + zap.String("previous", previousHead), + zap.String("current", currentHead)) + + // Update cached HEAD + wt.gitStateMu.Lock() + wt.cachedHeadSHA = currentHead + wt.gitStateMu.Unlock() + + // Check if HEAD moved backward (reset, rebase, etc.) + // This happens when currentHead is an ancestor of previousHead + if previousHead != "" { + if wt.isAncestor(ctx, currentHead, previousHead) { + // HEAD moved backward - emit reset notification + wt.logger.Info("detected git reset (HEAD moved backward)", + zap.String("previous", previousHead), + zap.String("current", currentHead)) + wt.notifyWorkspaceStreamGitReset(&types.GitResetNotification{ + Timestamp: time.Now(), + PreviousHead: previousHead, + CurrentHead: currentHead, + }) + } else { + // HEAD moved forward - get new commits + commits := wt.getCommitsSince(ctx, previousHead) + + // Filter out commits that are already on remote branches. + // This prevents recording upstream commits as session commits when + // the user pulls/rebases onto a remote branch (e.g., git reset --hard main). + localCommits := wt.filterLocalCommits(ctx, commits) + + for _, commit := range localCommits { + wt.notifyWorkspaceStreamGitCommit(commit) + } + if len(localCommits) > 0 { + wt.logger.Info("detected new commits via polling", + zap.Int("count", len(localCommits))) + } + } + } + + // Update and broadcast git status + wt.updateGitStatus(ctx) +} + +// isAncestor checks if commit1 is an ancestor of commit2 +func (wt *WorkspaceTracker) isAncestor(ctx context.Context, commit1, commit2 string) bool { + cmd := exec.CommandContext(ctx, "git", "merge-base", "--is-ancestor", commit1, commit2) + cmd.Dir = wt.workDir + err := cmd.Run() + // Exit code 0 means commit1 IS an ancestor of commit2 + // Exit code 1 means commit1 is NOT an ancestor of commit2 + return err == nil +} + +// isOnRemote checks if a commit is reachable from any remote tracking branch. +// This is used to filter out upstream commits that came from a pull/fetch, +// as opposed to commits made locally in the session. +func (wt *WorkspaceTracker) isOnRemote(ctx context.Context, commitSHA string) bool { + // Use git branch -r --contains to check if commit is on any remote branch + cmd := exec.CommandContext(ctx, "git", "branch", "-r", "--contains", commitSHA) + cmd.Dir = wt.workDir + out, err := cmd.Output() + if err != nil { + // If the command fails, assume it's not on remote (safer default) + return false + } + // If output is non-empty, commit is reachable from at least one remote branch + return strings.TrimSpace(string(out)) != "" +} + +// filterLocalCommits filters out commits that are already on remote branches. +// This ensures we only report commits made locally in the session, not upstream commits +// that came from pulling/rebasing onto a remote branch. +func (wt *WorkspaceTracker) filterLocalCommits(ctx context.Context, commits []*types.GitCommitNotification) []*types.GitCommitNotification { + if len(commits) == 0 { + return commits + } + + localCommits := make([]*types.GitCommitNotification, 0, len(commits)) + for _, commit := range commits { + if !wt.isOnRemote(ctx, commit.CommitSHA) { + localCommits = append(localCommits, commit) + } else { + wt.logger.Debug("skipping upstream commit (already on remote)", + zap.String("sha", commit.CommitSHA), + zap.String("message", commit.Message)) + } + } + + if skipped := len(commits) - len(localCommits); skipped > 0 { + wt.logger.Info("filtered upstream commits", + zap.Int("total", len(commits)), + zap.Int("skipped", skipped), + zap.Int("local", len(localCommits))) + } + + return localCommits +} + +// getCommitsSince returns commits from baseCommit (exclusive) to HEAD (inclusive) +func (wt *WorkspaceTracker) getCommitsSince(ctx context.Context, baseCommit string) []*types.GitCommitNotification { + // Get list of commits with metadata + // Format: SHA|ParentSHA|AuthorName|AuthorEmail|Subject|AuthorDateISO + cmd := exec.CommandContext(ctx, "git", "log", + "--format=%H|%P|%an|%ae|%s|%aI", + baseCommit+"..HEAD") + cmd.Dir = wt.workDir + out, err := cmd.Output() + if err != nil { + wt.logger.Debug("failed to get commits since base", + zap.String("base", baseCommit), + zap.Error(err)) + return nil + } + + output := strings.TrimSpace(string(out)) + if output == "" { + return nil + } + + lines := strings.Split(output, "\n") + commits := make([]*types.GitCommitNotification, 0, len(lines)) + + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + + parts := strings.SplitN(line, "|", 6) + if len(parts) < 6 { + continue + } + + sha := parts[0] + parentSHA := parts[1] + // Handle multiple parents (merge commits) - just take the first + if idx := strings.Index(parentSHA, " "); idx > 0 { + parentSHA = parentSHA[:idx] + } + + committedAt, err := time.Parse(time.RFC3339, parts[5]) + if err != nil { + committedAt = time.Now().UTC() + } + + // Get stats for this commit + filesChanged, insertions, deletions := wt.getCommitStats(ctx, sha) + + commits = append(commits, &types.GitCommitNotification{ + Timestamp: time.Now(), + CommitSHA: sha, + ParentSHA: parentSHA, + AuthorName: parts[2], + AuthorEmail: parts[3], + Message: parts[4], + FilesChanged: filesChanged, + Insertions: insertions, + Deletions: deletions, + CommittedAt: committedAt, + }) + } + + return commits +} + +// getCommitStats returns the number of files changed, insertions, and deletions for a commit +func (wt *WorkspaceTracker) getCommitStats(ctx context.Context, sha string) (filesChanged, insertions, deletions int) { + cmd := exec.CommandContext(ctx, "git", "show", "--stat", "--format=", sha) + cmd.Dir = wt.workDir + out, err := cmd.Output() + if err != nil { + return 0, 0, 0 + } + + // Parse the last line which contains summary like "3 files changed, 10 insertions(+), 5 deletions(-)" + lines := strings.Split(strings.TrimSpace(string(out)), "\n") + if len(lines) == 0 { + return 0, 0, 0 + } + + summary := lines[len(lines)-1] + // Simple parsing - look for numbers before keywords + parts := strings.Fields(summary) + for i, part := range parts { + if strings.Contains(part, "file") && i > 0 { + _, _ = fmt.Sscanf(parts[i-1], "%d", &filesChanged) + } + if strings.Contains(part, "insertion") && i > 0 { + _, _ = fmt.Sscanf(parts[i-1], "%d", &insertions) + } + if strings.Contains(part, "deletion") && i > 0 { + _, _ = fmt.Sscanf(parts[i-1], "%d", &deletions) + } + } + + return filesChanged, insertions, deletions +} + // updateGitStatus updates the git status func (wt *WorkspaceTracker) updateGitStatus(ctx context.Context) { status, err := wt.getGitStatus(ctx) @@ -235,8 +505,25 @@ func (wt *WorkspaceTracker) getGitStatus(ctx context.Context) (types.GitStatusUp } // Get ahead/behind counts - if update.RemoteBranch != "" { - countCmd := exec.CommandContext(ctx, "git", "rev-list", "--left-right", "--count", update.Branch+"..."+update.RemoteBranch) + // Use remote branch if available, otherwise fall back to origin/main or origin/master + // This handles worktree branches that don't have an upstream tracking branch set + compareRef := update.RemoteBranch + if compareRef == "" { + // Try origin/main first, then origin/master + checkCmd := exec.CommandContext(ctx, "git", "rev-parse", "--verify", "origin/main") + checkCmd.Dir = wt.workDir + if err := checkCmd.Run(); err == nil { + compareRef = "origin/main" + } else { + checkCmd2 := exec.CommandContext(ctx, "git", "rev-parse", "--verify", "origin/master") + checkCmd2.Dir = wt.workDir + if err := checkCmd2.Run(); err == nil { + compareRef = "origin/master" + } + } + } + if compareRef != "" { + countCmd := exec.CommandContext(ctx, "git", "rev-list", "--left-right", "--count", update.Branch+"..."+compareRef) countCmd.Dir = wt.workDir if countOut, err := countCmd.Output(); err == nil { parts := strings.Fields(string(countOut)) @@ -601,11 +888,34 @@ func (wt *WorkspaceTracker) notifyWorkspaceStreamGitCommit(commit *types.GitComm } } -// NotifyGitCommit notifies all subscribers about a new git commit +// NotifyGitCommit notifies all subscribers about a new git commit. +// It also updates the cached HEAD SHA to prevent polling from re-detecting the same commit. func (wt *WorkspaceTracker) NotifyGitCommit(commit *types.GitCommitNotification) { + // Update cached HEAD to the new commit SHA so polling doesn't re-detect it + if commit.CommitSHA != "" { + wt.gitStateMu.Lock() + wt.cachedHeadSHA = commit.CommitSHA + wt.gitStateMu.Unlock() + } + wt.notifyWorkspaceStreamGitCommit(commit) } +// notifyWorkspaceStreamGitReset sends git reset notification to all workspace stream subscribers +func (wt *WorkspaceTracker) notifyWorkspaceStreamGitReset(reset *types.GitResetNotification) { + wt.workspaceSubMu.RLock() + defer wt.workspaceSubMu.RUnlock() + + msg := types.NewWorkspaceGitReset(reset) + for sub := range wt.workspaceStreamSubscribers { + select { + case sub <- msg: + default: + // Subscriber is slow, skip + } + } +} + // notifyWorkspaceStreamFileChange sends file change notification to all workspace stream subscribers func (wt *WorkspaceTracker) notifyWorkspaceStreamFileChange(notification types.FileChangeNotification) { wt.workspaceSubMu.RLock() diff --git a/apps/backend/internal/agentctl/server/process/workspace_tracker_test.go b/apps/backend/internal/agentctl/server/process/workspace_tracker_test.go new file mode 100644 index 0000000000..89cf345f61 --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/workspace_tracker_test.go @@ -0,0 +1,298 @@ +package process + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/kandev/kandev/internal/agentctl/types/streams" +) + +// setupTestRepo creates a git repository with a remote for testing. +// Returns the repo path and a cleanup function. +func setupTestRepo(t *testing.T) (string, func()) { + t.Helper() + + // Create temp directory for the "remote" bare repo + remoteDir, err := os.MkdirTemp("", "test-remote-*") + if err != nil { + t.Fatalf("failed to create remote dir: %v", err) + } + + // Create temp directory for the local repo + localDir, err := os.MkdirTemp("", "test-local-*") + if err != nil { + _ = os.RemoveAll(remoteDir) + t.Fatalf("failed to create local dir: %v", err) + } + + cleanup := func() { + _ = os.RemoveAll(remoteDir) + _ = os.RemoveAll(localDir) + } + + // Initialize bare remote repo + runGit(t, remoteDir, "init", "--bare") + + // Initialize local repo + runGit(t, localDir, "init") + runGit(t, localDir, "config", "user.email", "test@test.com") + runGit(t, localDir, "config", "user.name", "Test User") + + // Create initial commit + writeFile(t, localDir, "README.md", "# Test Repo") + runGit(t, localDir, "add", ".") + runGit(t, localDir, "commit", "-m", "Initial commit") + + // Add remote and push + runGit(t, localDir, "remote", "add", "origin", remoteDir) + runGit(t, localDir, "push", "-u", "origin", "master") + + return localDir, cleanup +} + +func runGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v failed: %v\nOutput: %s", args, err, out) + } + return string(out) +} + +func writeFile(t *testing.T, dir, name, content string) { + t.Helper() + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + t.Fatalf("failed to write file %s: %v", name, err) + } +} + +func TestIsOnRemote(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + wt := NewWorkspaceTracker(repoDir, log) + ctx := context.Background() + + // Get the initial commit SHA (which is on origin/master) + initialSHA := runGit(t, repoDir, "rev-parse", "HEAD") + initialSHA = initialSHA[:len(initialSHA)-1] // trim newline + + // Test: initial commit should be on remote + if !wt.isOnRemote(ctx, initialSHA) { + t.Errorf("expected initial commit %s to be on remote", initialSHA) + } + + // Create a local commit (not pushed) + writeFile(t, repoDir, "local.txt", "local content") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "Local commit") + + localSHA := runGit(t, repoDir, "rev-parse", "HEAD") + localSHA = localSHA[:len(localSHA)-1] + + // Test: local commit should NOT be on remote + if wt.isOnRemote(ctx, localSHA) { + t.Errorf("expected local commit %s to NOT be on remote", localSHA) + } + + // Push the local commit + runGit(t, repoDir, "push") + + // Test: after push, commit should be on remote + if !wt.isOnRemote(ctx, localSHA) { + t.Errorf("expected pushed commit %s to be on remote", localSHA) + } +} + +func TestFilterLocalCommits(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + wt := NewWorkspaceTracker(repoDir, log) + ctx := context.Background() + + // Get initial commit SHA + initialSHA := runGit(t, repoDir, "rev-parse", "HEAD") + initialSHA = initialSHA[:len(initialSHA)-1] + + // Create two local commits + writeFile(t, repoDir, "file1.txt", "content1") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "Local commit 1") + local1SHA := runGit(t, repoDir, "rev-parse", "HEAD") + local1SHA = local1SHA[:len(local1SHA)-1] + + writeFile(t, repoDir, "file2.txt", "content2") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "Local commit 2") + local2SHA := runGit(t, repoDir, "rev-parse", "HEAD") + local2SHA = local2SHA[:len(local2SHA)-1] + + // Create test commits slice with mix of remote and local commits + commits := []*streams.GitCommitNotification{ + {CommitSHA: initialSHA, Message: "Initial commit", Timestamp: time.Now()}, + {CommitSHA: local1SHA, Message: "Local commit 1", Timestamp: time.Now()}, + {CommitSHA: local2SHA, Message: "Local commit 2", Timestamp: time.Now()}, + } + + // Filter commits + filtered := wt.filterLocalCommits(ctx, commits) + + // Should only have the 2 local commits, not the initial (remote) commit + if len(filtered) != 2 { + t.Errorf("expected 2 local commits, got %d", len(filtered)) + } + + for _, c := range filtered { + if c.CommitSHA == initialSHA { + t.Errorf("initial commit should have been filtered out") + } + } +} + +func TestGetGitStatus_AheadBehindWithoutUpstream(t *testing.T) { + repoDir, cleanup := setupTestRepo(t) + defer cleanup() + + log := newTestLogger(t) + wt := NewWorkspaceTracker(repoDir, log) + ctx := context.Background() + + // Create a new branch without setting upstream + runGit(t, repoDir, "checkout", "-b", "feature-branch") + + // Make a local commit + writeFile(t, repoDir, "feature.txt", "feature content") + runGit(t, repoDir, "add", ".") + runGit(t, repoDir, "commit", "-m", "Feature commit") + + // Get git status - should still calculate ahead/behind against origin/master + status, err := wt.getGitStatus(ctx) + if err != nil { + t.Fatalf("failed to get git status: %v", err) + } + + // Should be 1 ahead of origin/master + if status.Ahead != 1 { + t.Errorf("expected ahead=1, got %d", status.Ahead) + } + + // Should be 0 behind + if status.Behind != 0 { + t.Errorf("expected behind=0, got %d", status.Behind) + } + + // Branch should be feature-branch + if status.Branch != "feature-branch" { + t.Errorf("expected branch=feature-branch, got %s", status.Branch) + } +} + +// TestFilterLocalCommits_PullAndResetScenario tests the exact scenario where: +// 1. Session starts at commit X +// 2. Upstream (origin/master) gets new commits +// 3. User does git fetch && git reset --hard origin/master +// 4. The upstream commits should be filtered out +func TestFilterLocalCommits_PullAndResetScenario(t *testing.T) { + // Create temp directories + remoteDir, err := os.MkdirTemp("", "test-remote-*") + if err != nil { + t.Fatalf("failed to create remote dir: %v", err) + } + defer func() { _ = os.RemoveAll(remoteDir) }() + + localDir, err := os.MkdirTemp("", "test-local-*") + if err != nil { + t.Fatalf("failed to create local dir: %v", err) + } + defer func() { _ = os.RemoveAll(localDir) }() + + // Another clone to simulate upstream changes + upstreamClone, err := os.MkdirTemp("", "test-upstream-*") + if err != nil { + t.Fatalf("failed to create upstream clone dir: %v", err) + } + defer func() { _ = os.RemoveAll(upstreamClone) }() + + // Initialize bare remote repo + runGit(t, remoteDir, "init", "--bare") + + // Initialize local repo (the "session" repo) + runGit(t, localDir, "init") + runGit(t, localDir, "config", "user.email", "test@test.com") + runGit(t, localDir, "config", "user.name", "Test User") + writeFile(t, localDir, "README.md", "# Test Repo") + runGit(t, localDir, "add", ".") + runGit(t, localDir, "commit", "-m", "Initial commit (X)") + runGit(t, localDir, "remote", "add", "origin", remoteDir) + runGit(t, localDir, "push", "-u", "origin", "master") + + // Record the starting point (commit X) + startingSHA := runGit(t, localDir, "rev-parse", "HEAD") + startingSHA = startingSHA[:len(startingSHA)-1] + + // Clone to upstream clone and make commits there (simulating main evolving) + runGit(t, upstreamClone, "clone", remoteDir, ".") + runGit(t, upstreamClone, "config", "user.email", "upstream@test.com") + runGit(t, upstreamClone, "config", "user.name", "Upstream User") + + // Make upstream commits Y and Z + writeFile(t, upstreamClone, "upstream1.txt", "upstream content 1") + runGit(t, upstreamClone, "add", ".") + runGit(t, upstreamClone, "commit", "-m", "Upstream commit Y") + // Note: We don't need to capture Y's SHA, just Z's for verification + + writeFile(t, upstreamClone, "upstream2.txt", "upstream content 2") + runGit(t, upstreamClone, "add", ".") + runGit(t, upstreamClone, "commit", "-m", "Upstream commit Z") + upstreamZ := runGit(t, upstreamClone, "rev-parse", "HEAD") + upstreamZ = upstreamZ[:len(upstreamZ)-1] + + // Push upstream commits + runGit(t, upstreamClone, "push") + + // Now in the local repo (session), fetch and reset to origin/master + runGit(t, localDir, "fetch", "origin") + runGit(t, localDir, "reset", "--hard", "origin/master") + + // Verify HEAD is now at Z + currentHead := runGit(t, localDir, "rev-parse", "HEAD") + currentHead = currentHead[:len(currentHead)-1] + if currentHead != upstreamZ { + t.Fatalf("expected HEAD to be at %s, got %s", upstreamZ, currentHead) + } + + // Create workspace tracker and test filtering + log := newTestLogger(t) + wt := NewWorkspaceTracker(localDir, log) + ctx := context.Background() + + // Simulate what checkGitChanges would do: get commits since starting point + commits := wt.getCommitsSince(ctx, startingSHA) + + // Should have 2 commits (Y and Z) + if len(commits) != 2 { + t.Fatalf("expected 2 commits since starting point, got %d", len(commits)) + } + + // Filter local commits - should filter out ALL of them since they're on remote + filtered := wt.filterLocalCommits(ctx, commits) + + // Should have 0 commits after filtering (all are upstream commits) + if len(filtered) != 0 { + t.Errorf("expected 0 local commits after filtering upstream, got %d", len(filtered)) + for _, c := range filtered { + t.Errorf(" unexpected commit: %s - %s", c.CommitSHA[:8], c.Message) + } + } +} + diff --git a/apps/backend/internal/agentctl/types/streams/git.go b/apps/backend/internal/agentctl/types/streams/git.go index f6646e6baa..a89a89732b 100644 --- a/apps/backend/internal/agentctl/types/streams/git.go +++ b/apps/backend/internal/agentctl/types/streams/git.go @@ -104,3 +104,16 @@ type GitCommitNotification struct { // CommittedAt is when the commit was made. CommittedAt time.Time `json:"committed_at"` } + +// GitResetNotification is sent when HEAD moves backward (e.g., git reset, rebase). +// This signals that commits may have been removed and the backend should sync. +type GitResetNotification struct { + // Timestamp is when this notification was created. + Timestamp time.Time `json:"timestamp"` + + // PreviousHead is the SHA HEAD was pointing to before the reset. + PreviousHead string `json:"previous_head"` + + // CurrentHead is the SHA HEAD is now pointing to. + CurrentHead string `json:"current_head"` +} diff --git a/apps/backend/internal/agentctl/types/types.go b/apps/backend/internal/agentctl/types/types.go index 79b2c61230..f2f4a0da3e 100644 --- a/apps/backend/internal/agentctl/types/types.go +++ b/apps/backend/internal/agentctl/types/types.go @@ -27,6 +27,7 @@ type ( // Git stream types GitStatusUpdate = streams.GitStatusUpdate GitCommitNotification = streams.GitCommitNotification + GitResetNotification = streams.GitResetNotification FileInfo = streams.FileInfo // File stream types @@ -155,6 +156,7 @@ const ( WorkspaceMessageTypeProcessOutput WorkspaceMessageType = "process_output" WorkspaceMessageTypeProcessStatus WorkspaceMessageType = "process_status" WorkspaceMessageTypeGitCommit WorkspaceMessageType = "git_commit" + WorkspaceMessageTypeGitReset WorkspaceMessageType = "git_reset" ) // WorkspaceStreamMessage is the unified message format for the workspace stream. @@ -188,6 +190,9 @@ type WorkspaceStreamMessage struct { // Git commit fields (for git_commit) GitCommit *GitCommitNotification `json:"git_commit,omitempty"` + // Git reset fields (for git_reset) + GitReset *GitResetNotification `json:"git_reset,omitempty"` + // Error fields (for error) Error string `json:"error,omitempty"` } @@ -228,6 +233,15 @@ func NewWorkspaceGitCommit(commit *GitCommitNotification) WorkspaceStreamMessage } } +// NewWorkspaceGitReset creates a git reset notification message +func NewWorkspaceGitReset(reset *GitResetNotification) WorkspaceStreamMessage { + return WorkspaceStreamMessage{ + Type: WorkspaceMessageTypeGitReset, + Timestamp: timeNowUnixMilli(), + GitReset: reset, + } +} + // NewWorkspaceFileChange creates a file change message func NewWorkspaceFileChange(notification *FileChangeNotification) WorkspaceStreamMessage { return WorkspaceStreamMessage{ diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 5ed1d93606..ac37e53539 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -106,11 +106,9 @@ const ( // Event types for workspace/git status const ( - GitStatusUpdated = "git.status.updated" // Git status changed in workspace + GitEvent = "git.event" // Internal git events (agentctl -> orchestrator) + GitWSEvent = "git.ws" // WebSocket git events (orchestrator -> frontend) FileChangeNotified = "file.change.notified" // File changed in workspace - GitCommitCreated = "git.commit.created" // New commit created in workspace - GitSnapshotCreated = "git.snapshot.created" // New git snapshot created - GitCommitRecorded = "git.commit.recorded" // New session commit recorded to database ) // Event types for shell I/O @@ -180,44 +178,25 @@ func BuildAgentStreamWildcardSubject() string { return AgentStream + ".*" } -// BuildGitStatusSubject creates a git status subject for a specific session -func BuildGitStatusSubject(sessionID string) string { - return GitStatusUpdated + "." + sessionID +// BuildGitEventSubject creates a git event subject for a specific session +func BuildGitEventSubject(sessionID string) string { + return GitEvent + "." + sessionID } -// BuildGitStatusWildcardSubject creates a wildcard subscription for all git status updates -func BuildGitStatusWildcardSubject() string { - return GitStatusUpdated + ".*" +// BuildGitEventWildcardSubject creates a wildcard subscription for all internal git events +func BuildGitEventWildcardSubject() string { + return GitEvent + ".*" } -// BuildGitCommitSubject returns the event subject for git commit events for a session. -func BuildGitCommitSubject(sessionID string) string { - return GitCommitCreated + "." + sessionID +// BuildGitWSEventSubject creates a git WebSocket event subject for a specific session +// These events are sent from orchestrator to frontend via WebSocket gateway +func BuildGitWSEventSubject(sessionID string) string { + return GitWSEvent + "." + sessionID } -// BuildGitCommitWildcardSubject creates a wildcard subscription for all git commit events -func BuildGitCommitWildcardSubject() string { - return GitCommitCreated + ".*" -} - -// BuildGitSnapshotSubject creates a git snapshot subject for a specific session -func BuildGitSnapshotSubject(sessionID string) string { - return GitSnapshotCreated + "." + sessionID -} - -// BuildGitSnapshotWildcardSubject creates a wildcard subscription for all git snapshot events -func BuildGitSnapshotWildcardSubject() string { - return GitSnapshotCreated + ".*" -} - -// BuildGitCommitRecordedSubject creates a git commit recorded subject for a specific session -func BuildGitCommitRecordedSubject(sessionID string) string { - return GitCommitRecorded + "." + sessionID -} - -// BuildGitCommitRecordedWildcardSubject creates a wildcard subscription for all git commit recorded events -func BuildGitCommitRecordedWildcardSubject() string { - return GitCommitRecorded + ".*" +// BuildGitWSEventWildcardSubject creates a wildcard subscription for all git WebSocket events +func BuildGitWSEventWildcardSubject() string { + return GitWSEvent + ".*" } // BuildFileChangeSubject creates a file change subject for a specific session @@ -249,3 +228,4 @@ func BuildContextWindowSubject(sessionID string) string { func BuildContextWindowWildcardSubject() string { return ContextWindowUpdated + ".*" } + diff --git a/apps/backend/internal/gateway/websocket/session_notifications.go b/apps/backend/internal/gateway/websocket/session_notifications.go index e3c2dd904f..96addc64d9 100644 --- a/apps/backend/internal/gateway/websocket/session_notifications.go +++ b/apps/backend/internal/gateway/websocket/session_notifications.go @@ -40,9 +40,7 @@ func RegisterSessionStreamNotifications(ctx context.Context, eventBus bus.EventB return b } - b.subscribe(eventBus, events.BuildGitStatusWildcardSubject(), ws.ActionSessionGitStatus) - b.subscribe(eventBus, events.BuildGitSnapshotWildcardSubject(), ws.ActionSessionGitSnapshot) - b.subscribe(eventBus, events.BuildGitCommitRecordedWildcardSubject(), ws.ActionSessionGitCommit) + b.subscribe(eventBus, events.BuildGitWSEventWildcardSubject(), ws.ActionSessionGitEvent) // Use debounced subscription for file changes to batch high-frequency events b.subscribeFileChanges(eventBus, events.BuildFileChangeWildcardSubject(), ws.ActionWorkspaceFileChanges) b.subscribe(eventBus, events.BuildShellOutputWildcardSubject(), ws.ActionSessionShellOutput) diff --git a/apps/backend/internal/orchestrator/event_handlers.go b/apps/backend/internal/orchestrator/event_handlers.go index 2b22442904..bd293d876e 100644 --- a/apps/backend/internal/orchestrator/event_handlers.go +++ b/apps/backend/internal/orchestrator/event_handlers.go @@ -444,74 +444,136 @@ func (s *Service) setSessionRunning(ctx context.Context, taskID, sessionID strin } } -// handleGitStatusUpdated handles git status updates by creating git snapshots -func (s *Service) handleGitStatusUpdated(ctx context.Context, data watcher.GitStatusData) { - s.logger.Debug("handling git status update", +// handleGitEvent handles unified git events and dispatches to appropriate handler +func (s *Service) handleGitEvent(ctx context.Context, data watcher.GitEventData) { + s.logger.Debug("handling git event", + zap.String("type", string(data.Type)), zap.String("task_id", data.TaskID), - zap.String("branch", data.Branch)) + zap.String("session_id", data.SessionID)) - if data.TaskSessionID == "" { - s.logger.Debug("missing session_id for git status update", + if data.SessionID == "" { + s.logger.Debug("missing session_id for git event", + zap.String("task_id", data.TaskID), + zap.String("type", string(data.Type))) + return + } + + switch data.Type { + case lifecycle.GitEventTypeStatusUpdate: + s.handleGitStatusUpdate(ctx, data) + case lifecycle.GitEventTypeCommitCreated: + s.handleGitCommitCreated(ctx, data) + case lifecycle.GitEventTypeCommitsReset: + s.handleGitCommitsReset(ctx, data) + case lifecycle.GitEventTypeSnapshotCreated: + // Snapshot events are published from orchestrator, no need to handle here + s.logger.Debug("received snapshot_created event, no action needed", + zap.String("session_id", data.SessionID)) + default: + s.logger.Warn("unknown git event type", + zap.String("type", string(data.Type)), + zap.String("session_id", data.SessionID)) + } +} + +// handleGitStatusUpdate handles git status updates by creating git snapshots +func (s *Service) handleGitStatusUpdate(ctx context.Context, data watcher.GitEventData) { + if data.Status == nil { + s.logger.Debug("missing status data for git status update", zap.String("task_id", data.TaskID)) return } + // Forward status_update event to WebSocket subject for frontend + // Since data is already lifecycle.GitEventPayload, we can forward it directly + if s.eventBus != nil { + event := bus.NewEvent(events.GitWSEvent, "orchestrator", &data) + _ = s.eventBus.Publish(ctx, events.BuildGitWSEventSubject(data.SessionID), event) + } + + // Convert Files from interface{} to map[string]interface{} + var files map[string]interface{} + if data.Status.Files != nil { + if f, ok := data.Status.Files.(map[string]interface{}); ok { + files = f + } + } + // Create git snapshot instead of storing in session metadata snapshot := &models.GitSnapshot{ - SessionID: data.TaskSessionID, + SessionID: data.SessionID, SnapshotType: models.SnapshotTypeStatusUpdate, - Branch: data.Branch, - RemoteBranch: data.RemoteBranch, - HeadCommit: data.HeadCommit, - BaseCommit: data.BaseCommit, - Ahead: data.Ahead, - Behind: data.Behind, - Files: data.Files, + Branch: data.Status.Branch, + RemoteBranch: data.Status.RemoteBranch, + HeadCommit: data.Status.HeadCommit, + BaseCommit: data.Status.BaseCommit, + Ahead: data.Status.Ahead, + Behind: data.Status.Behind, + Files: files, TriggeredBy: "git_status_event", Metadata: map[string]interface{}{ - "modified": data.Modified, - "added": data.Added, - "deleted": data.Deleted, - "untracked": data.Untracked, - "renamed": data.Renamed, + "modified": data.Status.Modified, + "added": data.Status.Added, + "deleted": data.Status.Deleted, + "untracked": data.Status.Untracked, + "renamed": data.Status.Renamed, "timestamp": data.Timestamp, }, } + sessionID := data.SessionID + taskID := data.TaskID + // Persist snapshot to database asynchronously, but skip if duplicate of latest go func() { bgCtx := context.Background() // Check if this is a duplicate of the latest snapshot - latest, err := s.repo.GetLatestGitSnapshot(bgCtx, data.TaskSessionID) + latest, err := s.repo.GetLatestGitSnapshot(bgCtx, sessionID) if err == nil && latest != nil { // Compare key fields to detect duplicates if s.isSnapshotDuplicate(latest, snapshot) { s.logger.Debug("skipping duplicate git snapshot", - zap.String("task_id", data.TaskID), - zap.String("session_id", data.TaskSessionID)) + zap.String("task_id", taskID), + zap.String("session_id", sessionID)) return } } if err := s.repo.CreateGitSnapshot(bgCtx, snapshot); err != nil { s.logger.Error("failed to create git snapshot", - zap.String("task_id", data.TaskID), - zap.String("session_id", data.TaskSessionID), + zap.String("task_id", taskID), + zap.String("session_id", sessionID), zap.Error(err)) } else { s.logger.Debug("created git snapshot", - zap.String("task_id", data.TaskID), - zap.String("session_id", data.TaskSessionID), + zap.String("task_id", taskID), + zap.String("session_id", sessionID), zap.String("snapshot_id", snapshot.ID)) // Publish event to notify frontend if s.eventBus != nil { - event := bus.NewEvent(events.GitSnapshotCreated, "orchestrator", map[string]interface{}{ - "session_id": data.TaskSessionID, - "snapshot": snapshot, + event := bus.NewEvent(events.GitEvent, "orchestrator", &lifecycle.GitEventPayload{ + Type: lifecycle.GitEventTypeSnapshotCreated, + SessionID: sessionID, + TaskID: taskID, + Timestamp: snapshot.CreatedAt.Format("2006-01-02T15:04:05.000000000Z07:00"), + Snapshot: &lifecycle.GitSnapshotData{ + ID: snapshot.ID, + SessionID: snapshot.SessionID, + SnapshotType: string(snapshot.SnapshotType), + Branch: snapshot.Branch, + RemoteBranch: snapshot.RemoteBranch, + HeadCommit: snapshot.HeadCommit, + BaseCommit: snapshot.BaseCommit, + Ahead: snapshot.Ahead, + Behind: snapshot.Behind, + Files: snapshot.Files, + TriggeredBy: snapshot.TriggeredBy, + CreatedAt: snapshot.CreatedAt.Format("2006-01-02T15:04:05.000000000Z07:00"), + }, }) - _ = s.eventBus.Publish(bgCtx, events.BuildGitSnapshotSubject(data.TaskSessionID), event) + _ = s.eventBus.Publish(bgCtx, events.BuildGitWSEventSubject(sessionID), event) } } }() @@ -660,21 +722,21 @@ func (s *Service) handlePermissionRequest(ctx context.Context, data watcher.Perm } // handleGitCommitCreated handles git commit events by creating session commit records -func (s *Service) handleGitCommitCreated(ctx context.Context, data watcher.GitCommitData) { - s.logger.Debug("handling git commit created", - zap.String("task_id", data.TaskID), - zap.String("commit_sha", data.CommitSHA)) - - if data.TaskSessionID == "" { - s.logger.Debug("missing session_id for git commit event", +func (s *Service) handleGitCommitCreated(ctx context.Context, data watcher.GitEventData) { + if data.Commit == nil { + s.logger.Debug("missing commit data for git commit event", zap.String("task_id", data.TaskID)) return } + s.logger.Debug("handling git commit created", + zap.String("task_id", data.TaskID), + zap.String("commit_sha", data.Commit.CommitSHA)) + // Parse committed_at timestamp var committedAt time.Time - if data.CommittedAt != "" { - if t, err := time.Parse(time.RFC3339Nano, data.CommittedAt); err == nil { + if data.Commit.CommittedAt != "" { + if t, err := time.Parse(time.RFC3339, data.Commit.CommittedAt); err == nil { committedAt = t } else { committedAt = time.Now().UTC() @@ -683,18 +745,22 @@ func (s *Service) handleGitCommitCreated(ctx context.Context, data watcher.GitCo committedAt = time.Now().UTC() } + sessionID := data.SessionID + taskID := data.TaskID + commitSHA := data.Commit.CommitSHA + // Create session commit record commit := &models.SessionCommit{ - SessionID: data.TaskSessionID, - CommitSHA: data.CommitSHA, - ParentSHA: data.ParentSHA, - AuthorName: data.AuthorName, - AuthorEmail: data.AuthorEmail, - CommitMessage: data.Message, + SessionID: sessionID, + CommitSHA: data.Commit.CommitSHA, + ParentSHA: data.Commit.ParentSHA, + AuthorName: data.Commit.AuthorName, + AuthorEmail: data.Commit.AuthorEmail, + CommitMessage: data.Commit.Message, CommittedAt: committedAt, - FilesChanged: data.FilesChanged, - Insertions: data.Insertions, - Deletions: data.Deletions, + FilesChanged: data.Commit.FilesChanged, + Insertions: data.Commit.Insertions, + Deletions: data.Commit.Deletions, } // Persist commit record to database asynchronously @@ -702,23 +768,136 @@ func (s *Service) handleGitCommitCreated(ctx context.Context, data watcher.GitCo bgCtx := context.Background() if err := s.repo.CreateSessionCommit(bgCtx, commit); err != nil { s.logger.Error("failed to create session commit record", - zap.String("task_id", data.TaskID), - zap.String("session_id", data.TaskSessionID), - zap.String("commit_sha", data.CommitSHA), + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.String("commit_sha", commitSHA), zap.Error(err)) } else { s.logger.Debug("created session commit record", - zap.String("task_id", data.TaskID), - zap.String("session_id", data.TaskSessionID), - zap.String("commit_sha", data.CommitSHA)) + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.String("commit_sha", commitSHA)) - // Publish event to notify frontend + // Publish event to notify frontend using unified format if s.eventBus != nil { - event := bus.NewEvent(events.GitCommitRecorded, "orchestrator", map[string]interface{}{ - "session_id": data.TaskSessionID, - "commit": commit, + event := bus.NewEvent(events.GitEvent, "orchestrator", &lifecycle.GitEventPayload{ + Type: lifecycle.GitEventTypeCommitCreated, + SessionID: sessionID, + TaskID: taskID, + Timestamp: time.Now().Format("2006-01-02T15:04:05.000000000Z07:00"), + Commit: &lifecycle.GitCommitData{ + ID: commit.ID, + CommitSHA: commit.CommitSHA, + ParentSHA: commit.ParentSHA, + Message: commit.CommitMessage, + AuthorName: commit.AuthorName, + AuthorEmail: commit.AuthorEmail, + FilesChanged: commit.FilesChanged, + Insertions: commit.Insertions, + Deletions: commit.Deletions, + CommittedAt: commit.CommittedAt.Format(time.RFC3339), + CreatedAt: commit.CreatedAt.Format("2006-01-02T15:04:05.000000000Z07:00"), + }, }) - _ = s.eventBus.Publish(bgCtx, events.BuildGitCommitRecordedSubject(data.TaskSessionID), event) + _ = s.eventBus.Publish(bgCtx, events.BuildGitWSEventSubject(sessionID), event) + } + } + }() +} + +// handleGitCommitsReset handles git reset events by removing orphaned commits +func (s *Service) handleGitCommitsReset(ctx context.Context, data watcher.GitEventData) { + if data.Reset == nil { + s.logger.Debug("missing reset data for git reset event", + zap.String("task_id", data.TaskID)) + return + } + + sessionID := data.SessionID + taskID := data.TaskID + previousHead := data.Reset.PreviousHead + currentHead := data.Reset.CurrentHead + + s.logger.Info("handling git commits reset", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.String("previous_head", previousHead), + zap.String("current_head", currentHead)) + + // Remove orphaned commits asynchronously + go func() { + bgCtx := context.Background() + + // Get all stored commits for this session + commits, err := s.repo.GetSessionCommits(bgCtx, sessionID) + if err != nil { + s.logger.Error("failed to get session commits for reset handling", + zap.String("session_id", sessionID), + zap.Error(err)) + return + } + + if len(commits) == 0 { + return + } + + // Build a map for quick lookup + commitBySHA := make(map[string]*models.SessionCommit) + for _, c := range commits { + commitBySHA[c.CommitSHA] = c + } + + // Walk the parent chain from currentHead to find reachable commits + reachable := make(map[string]bool) + current := currentHead + for current != "" { + reachable[current] = true + if c, exists := commitBySHA[current]; exists { + current = c.ParentSHA + } else { + // Parent not in our stored commits, stop walking + break + } + } + + // Delete commits that are not reachable from currentHead + var deleted int + for _, c := range commits { + if !reachable[c.CommitSHA] { + if err := s.repo.DeleteSessionCommit(bgCtx, c.ID); err != nil { + s.logger.Error("failed to delete orphaned commit", + zap.String("session_id", sessionID), + zap.String("commit_sha", c.CommitSHA), + zap.Error(err)) + } else { + deleted++ + s.logger.Debug("deleted orphaned commit after reset", + zap.String("session_id", sessionID), + zap.String("commit_sha", c.CommitSHA)) + } + } + } + + if deleted > 0 { + s.logger.Info("removed orphaned commits after git reset", + zap.String("session_id", sessionID), + zap.Int("deleted_count", deleted), + zap.String("new_head", currentHead)) + + // Publish event to notify frontend that commits changed + if s.eventBus != nil { + event := bus.NewEvent(events.GitEvent, "orchestrator", &lifecycle.GitEventPayload{ + Type: lifecycle.GitEventTypeCommitsReset, + SessionID: sessionID, + TaskID: taskID, + Timestamp: time.Now().Format("2006-01-02T15:04:05.000000000Z07:00"), + Reset: &lifecycle.GitResetData{ + PreviousHead: previousHead, + CurrentHead: currentHead, + DeletedCount: deleted, + }, + }) + _ = s.eventBus.Publish(bgCtx, events.BuildGitWSEventSubject(sessionID), event) } } }() diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index b94163ae31..1a73f63cd9 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -158,8 +158,7 @@ func NewService( OnAgentStreamEvent: s.handleAgentStreamEvent, OnACPSessionCreated: s.handleACPSessionCreated, OnPermissionRequest: s.handlePermissionRequest, - OnGitStatusUpdated: s.handleGitStatusUpdated, - OnGitCommitCreated: s.handleGitCommitCreated, + OnGitEvent: s.handleGitEvent, OnContextWindowUpdated: s.handleContextWindowUpdated, } s.watcher = watcher.NewWatcher(eventBus, handlers, log) diff --git a/apps/backend/internal/orchestrator/watcher/watcher.go b/apps/backend/internal/orchestrator/watcher/watcher.go index a094ef056a..3ed4778a1d 100644 --- a/apps/backend/internal/orchestrator/watcher/watcher.go +++ b/apps/backend/internal/orchestrator/watcher/watcher.go @@ -53,41 +53,9 @@ type PermissionRequestData struct { ActionDetails map[string]interface{} `json:"action_details"` } -// GitStatusData contains data from git status events -type GitStatusData struct { - TaskID string `json:"task_id"` - TaskSessionID string `json:"session_id"` - AgentID string `json:"agent_id"` - Branch string `json:"branch"` - RemoteBranch string `json:"remote_branch"` - HeadCommit string `json:"head_commit"` - BaseCommit string `json:"base_commit"` - Modified []string `json:"modified"` - Added []string `json:"added"` - Deleted []string `json:"deleted"` - Untracked []string `json:"untracked"` - Renamed []string `json:"renamed"` - Ahead int `json:"ahead"` - Behind int `json:"behind"` - Files map[string]interface{} `json:"files"` - Timestamp string `json:"timestamp"` -} - -// GitCommitData contains data from git commit events -type GitCommitData struct { - TaskID string `json:"task_id"` - TaskSessionID string `json:"session_id"` - AgentID string `json:"agent_id"` - CommitSHA string `json:"commit_sha"` - ParentSHA string `json:"parent_sha"` - Message string `json:"message"` - AuthorName string `json:"author_name"` - AuthorEmail string `json:"author_email"` - FilesChanged int `json:"files_changed"` - Insertions int `json:"insertions"` - Deletions int `json:"deletions"` - CommittedAt string `json:"committed_at"` -} +// GitEventData is an alias for lifecycle.GitEventPayload. +// Kept for backwards compatibility with existing handler signatures. +type GitEventData = lifecycle.GitEventPayload // ContextWindowData contains data from context window events type ContextWindowData struct { @@ -123,11 +91,8 @@ type EventHandlers struct { // Permission request events OnPermissionRequest func(ctx context.Context, data PermissionRequestData) - // Git status events - OnGitStatusUpdated func(ctx context.Context, data GitStatusData) - - // Git commit events - OnGitCommitCreated func(ctx context.Context, data GitCommitData) + // Unified git events (status, commit, reset, snapshot) + OnGitEvent func(ctx context.Context, data GitEventData) // Context window events OnContextWindowUpdated func(ctx context.Context, data ContextWindowData) @@ -197,14 +162,8 @@ func (w *Watcher) Start(ctx context.Context) error { return err } - // Subscribe to git status events - if err := w.subscribeToGitStatusEvents(); err != nil { - w.unsubscribeAll() - return err - } - - // Subscribe to git commit events - if err := w.subscribeToGitCommitEvents(); err != nil { + // Subscribe to unified git events + if err := w.subscribeToGitEvents(); err != nil { w.unsubscribeAll() return err } @@ -490,19 +449,17 @@ func (w *Watcher) createPermissionRequestHandler() bus.EventHandler { } } -// subscribeToGitStatusEvents subscribes to git status events -func (w *Watcher) subscribeToGitStatusEvents() error { - if w.handlers.OnGitStatusUpdated == nil { +// subscribeToGitEvents subscribes to unified git events +func (w *Watcher) subscribeToGitEvents() error { + if w.handlers.OnGitEvent == nil { return nil } - // Use wildcard to subscribe to all git status events (git.status.updated.{session_id}) - subject := events.BuildGitStatusWildcardSubject() + subject := events.BuildGitEventWildcardSubject() - // Use regular subscription (each instance needs all messages) - sub, err := w.eventBus.Subscribe(subject, w.createGitStatusHandler()) + sub, err := w.eventBus.Subscribe(subject, w.createGitEventHandler()) if err != nil { - w.logger.Error("Failed to subscribe to git status events", + w.logger.Error("Failed to subscribe to git events", zap.String("subject", subject), zap.Error(err)) return err @@ -511,68 +468,24 @@ func (w *Watcher) subscribeToGitStatusEvents() error { return nil } -// createGitStatusHandler creates a bus.EventHandler for git status events -func (w *Watcher) createGitStatusHandler() bus.EventHandler { +// createGitEventHandler creates a bus.EventHandler for unified git events +func (w *Watcher) createGitEventHandler() bus.EventHandler { return func(ctx context.Context, event *bus.Event) error { - var data GitStatusData + var data GitEventData if err := w.parseEventData(event.Data, &data); err != nil { - w.logger.Error("Failed to parse git status event data", + w.logger.Error("Failed to parse git event data", zap.String("event_type", event.Type), zap.String("event_id", event.ID), zap.Error(err)) - return nil // Don't return error to continue processing other events + return nil } - w.logger.Debug("Handling git status event", + w.logger.Debug("Handling git event", + zap.String("type", string(data.Type)), zap.String("task_id", data.TaskID), - zap.String("branch", data.Branch), - zap.Int("modified", len(data.Modified))) + zap.String("session_id", data.SessionID)) - w.handlers.OnGitStatusUpdated(ctx, data) - return nil - } -} - -// subscribeToGitCommitEvents subscribes to git commit events -func (w *Watcher) subscribeToGitCommitEvents() error { - if w.handlers.OnGitCommitCreated == nil { - return nil - } - - // Use wildcard to subscribe to all git commit events (git.commit.created.{session_id}) - subject := events.BuildGitCommitWildcardSubject() - - // Use regular subscription (each instance needs all messages) - sub, err := w.eventBus.Subscribe(subject, w.createGitCommitHandler()) - if err != nil { - w.logger.Error("Failed to subscribe to git commit events", - zap.String("subject", subject), - zap.Error(err)) - return err - } - w.subscriptions = append(w.subscriptions, sub) - return nil -} - -// createGitCommitHandler creates a bus.EventHandler for git commit events -func (w *Watcher) createGitCommitHandler() bus.EventHandler { - return func(ctx context.Context, event *bus.Event) error { - var data GitCommitData - if err := w.parseEventData(event.Data, &data); err != nil { - w.logger.Error("Failed to parse git commit event data", - zap.String("event_type", event.Type), - zap.String("event_id", event.ID), - zap.Error(err)) - return nil // Don't return error to continue processing other events - } - - w.logger.Debug("Handling git commit event", - zap.String("task_id", data.TaskID), - zap.String("commit_sha", data.CommitSHA)) - - if w.handlers.OnGitCommitCreated != nil { - w.handlers.OnGitCommitCreated(ctx, data) - } + w.handlers.OnGitEvent(ctx, data) return nil } } diff --git a/apps/backend/internal/task/handlers/process_handlers_test.go b/apps/backend/internal/task/handlers/process_handlers_test.go index cd3f46ce3b..73ed38171b 100644 --- a/apps/backend/internal/task/handlers/process_handlers_test.go +++ b/apps/backend/internal/task/handlers/process_handlers_test.go @@ -335,6 +335,9 @@ func (m *mockRepository) GetSessionCommits(ctx context.Context, sessionID string func (m *mockRepository) GetLatestSessionCommit(ctx context.Context, sessionID string) (*models.SessionCommit, error) { return nil, nil } +func (m *mockRepository) DeleteSessionCommit(ctx context.Context, id string) error { + return nil +} func newTestService(t *testing.T, scripts map[string][]*models.RepositoryScript) *service.Service { log, err := logger.NewLogger(logger.LoggingConfig{ diff --git a/apps/backend/internal/task/repository/interface.go b/apps/backend/internal/task/repository/interface.go index f1d77bbd0c..9f4c9f68c1 100644 --- a/apps/backend/internal/task/repository/interface.go +++ b/apps/backend/internal/task/repository/interface.go @@ -101,6 +101,7 @@ type Repository interface { CreateSessionCommit(ctx context.Context, commit *models.SessionCommit) error GetSessionCommits(ctx context.Context, sessionID string) ([]*models.SessionCommit, error) GetLatestSessionCommit(ctx context.Context, sessionID string) (*models.SessionCommit, error) + DeleteSessionCommit(ctx context.Context, id string) error // Repository operations CreateRepository(ctx context.Context, repository *models.Repository) error diff --git a/apps/backend/internal/task/repository/sqlite/git_snapshots.go b/apps/backend/internal/task/repository/sqlite/git_snapshots.go index dd4c83b0b7..5363d1b974 100644 --- a/apps/backend/internal/task/repository/sqlite/git_snapshots.go +++ b/apps/backend/internal/task/repository/sqlite/git_snapshots.go @@ -273,3 +273,8 @@ func (r *Repository) GetLatestSessionCommit(ctx context.Context, sessionID strin return commit, nil } +// DeleteSessionCommit removes a commit record from the database. +func (r *Repository) DeleteSessionCommit(ctx context.Context, id string) error { + _, err := r.db.ExecContext(ctx, `DELETE FROM task_session_commits WHERE id = ?`, id) + return err +} diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index 28718f884f..0ff40bced7 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -166,14 +166,14 @@ const ( ActionShellInput = "shell.input" // Send input to shell ActionSessionShellOutput = "session.shell.output" // Shell output notification (also used for exit with type: "exit") - // Session git status - ActionSessionGitStatus = "session.git.status" + // Session git actions (requests) ActionSessionGitSnapshots = "session.git.snapshots" // Get git snapshots for a session ActionSessionGitCommits = "session.git.commits" // Get commits for a session ActionSessionCumulativeDiff = "session.cumulative_diff" // Get cumulative diff from base branch ActionSessionCommitDiff = "session.commit_diff" // Get diff for a specific commit - ActionSessionGitSnapshot = "session.git.snapshot" // Notification: new git snapshot created - ActionSessionGitCommit = "session.git.commit" // Notification: new session commit recorded + + // Session git event (unified notification) + ActionSessionGitEvent = "session.git.event" // Notification: unified git event // Process runner actions ActionSessionProcessOutput = "session.process.output" diff --git a/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts b/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts index e22d1de606..5b97eb7262 100644 --- a/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts +++ b/apps/web/lib/state/slices/session-runtime/session-runtime-slice.ts @@ -124,4 +124,9 @@ export const createSessionRuntimeSlice: StateCreator< // Add to front (newest first) draft.sessionCommits.bySessionId[sessionId] = [commit, ...existing]; }), + clearSessionCommits: (sessionId) => + set((draft) => { + // Delete the entry so hook will refetch (undefined triggers fetch, [] does not) + delete draft.sessionCommits.bySessionId[sessionId]; + }), }); diff --git a/apps/web/lib/state/slices/session-runtime/types.ts b/apps/web/lib/state/slices/session-runtime/types.ts index b9aedcf4d1..6ef17f1b40 100644 --- a/apps/web/lib/state/slices/session-runtime/types.ts +++ b/apps/web/lib/state/slices/session-runtime/types.ts @@ -171,6 +171,7 @@ export type SessionRuntimeSliceActions = { setSessionCommits: (sessionId: string, commits: SessionCommit[]) => void; setSessionCommitsLoading: (sessionId: string, loading: boolean) => void; addSessionCommit: (sessionId: string, commit: SessionCommit) => void; + clearSessionCommits: (sessionId: string) => void; }; export type SessionRuntimeSlice = SessionRuntimeSliceState & SessionRuntimeSliceActions; diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index ad361a6d47..1a187ab998 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -225,6 +225,7 @@ export type AppState = { setSessionCommits: (sessionId: string, commits: SessionCommit[]) => void; setSessionCommitsLoading: (sessionId: string, loading: boolean) => void; addSessionCommit: (sessionId: string, commit: SessionCommit) => void; + clearSessionCommits: (sessionId: string) => void; setContextWindow: (sessionId: string, contextWindow: ContextWindowEntry) => void; bumpAgentProfilesVersion: () => void; setPendingModel: (sessionId: string, modelId: string) => void; diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index 9cb48e8050..35a6d292c6 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -8,9 +8,7 @@ export type BackendMessageType = | 'agent.available.updated' | 'terminal.output' | 'diff.update' - | 'session.git.status' - | 'session.git.snapshot' - | 'session.git.commit' + | 'session.git.event' | 'system.error' | 'workspace.created' | 'workspace.updated' @@ -54,6 +52,7 @@ export type BackendMessage = { }; import type { AvailableAgent, TaskState } from '@/lib/types/http'; +import type { GitEventPayload } from '@/lib/types/git-events'; export type KanbanUpdatePayload = { boardId: string; @@ -190,63 +189,6 @@ export type FileInfo = { diff?: string; }; -export type GitStatusPayload = { - task_id: string; - session_id?: string; - branch: string; - remote_branch?: string; - modified: string[]; - added: string[]; - deleted: string[]; - untracked: string[]; - renamed: string[]; - ahead: number; - behind: number; - files: Record; - timestamp: string; -}; - -export type GitSnapshotPayload = { - task_id: string; - session_id: string; - snapshot: { - id: string; - session_id: string; - snapshot_type: string; - branch: string; - remote_branch: string; - head_commit: string; - base_commit: string; - ahead: number; - behind: number; - files: Record; - triggered_by: string; - metadata?: Record; - created_at: string; - }; -}; - -export type GitCommitPayload = { - task_id: string; - session_id: string; - commit: { - id: string; - session_id: string; - commit_sha: string; - parent_sha: string; - author_name: string; - author_email: string; - commit_message: string; - committed_at: string; - pre_commit_snapshot_id?: string; - post_commit_snapshot_id?: string; - files_changed: number; - insertions: number; - deletions: number; - created_at: string; - }; -}; - export type ProcessOutputPayload = { session_id: string; process_id: string; @@ -355,9 +297,7 @@ export type BackendMessageMap = { 'agent.available.updated': BackendMessage<'agent.available.updated', AgentAvailableUpdatedPayload>; 'terminal.output': BackendMessage<'terminal.output', TerminalOutputPayload>; 'diff.update': BackendMessage<'diff.update', DiffUpdatePayload>; - 'session.git.status': BackendMessage<'session.git.status', GitStatusPayload>; - 'session.git.snapshot': BackendMessage<'session.git.snapshot', GitSnapshotPayload>; - 'session.git.commit': BackendMessage<'session.git.commit', GitCommitPayload>; + 'session.git.event': BackendMessage<'session.git.event', GitEventPayload>; 'system.error': BackendMessage<'system.error', SystemErrorPayload>; 'workspace.created': BackendMessage<'workspace.created', WorkspacePayload>; 'workspace.updated': BackendMessage<'workspace.updated', WorkspacePayload>; diff --git a/apps/web/lib/types/git-events.ts b/apps/web/lib/types/git-events.ts new file mode 100644 index 0000000000..bea0112bc0 --- /dev/null +++ b/apps/web/lib/types/git-events.ts @@ -0,0 +1,91 @@ +import type { FileInfo } from '@/lib/state/slices/session-runtime/types'; + +// Base payload with discriminator +type GitEventBase = { + session_id: string; + task_id?: string; + agent_id?: string; + timestamp: string; +}; + +// Git status data +export type GitStatusData = { + branch: string; + remote_branch: string | null; + head_commit?: string; + base_commit?: string; + modified: string[]; + added: string[]; + deleted: string[]; + untracked: string[]; + renamed: string[]; + ahead: number; + behind: number; + files: Record; +}; + +// Git commit data +export type GitCommitData = { + id: string; + commit_sha: string; + parent_sha: string; + commit_message: string; + author_name: string; + author_email: string; + files_changed: number; + insertions: number; + deletions: number; + committed_at: string; + created_at?: string; +}; + +// Git reset data +export type GitResetData = { + previous_head: string; + current_head: string; + deleted_count: number; +}; + +// Git snapshot data +export type GitSnapshotData = { + id: string; + session_id: string; + snapshot_type: string; + branch: string; + remote_branch: string; + head_commit: string; + base_commit: string; + ahead: number; + behind: number; + files: Record; + triggered_by: string; + created_at: string; +}; + +// Individual event variants +export type GitStatusUpdateEvent = GitEventBase & { + type: 'status_update'; + status: GitStatusData; +}; + +export type GitCommitCreatedEvent = GitEventBase & { + type: 'commit_created'; + commit: GitCommitData; +}; + +export type GitCommitsResetEvent = GitEventBase & { + type: 'commits_reset'; + reset: GitResetData; +}; + +export type GitSnapshotCreatedEvent = GitEventBase & { + type: 'snapshot_created'; + snapshot: GitSnapshotData; +}; + +// Discriminated union +export type GitEventPayload = + | GitStatusUpdateEvent + | GitCommitCreatedEvent + | GitCommitsResetEvent + | GitSnapshotCreatedEvent; diff --git a/apps/web/lib/ws/handlers/git-status.ts b/apps/web/lib/ws/handlers/git-status.ts index 1f480655ba..0ffc9ba133 100644 --- a/apps/web/lib/ws/handlers/git-status.ts +++ b/apps/web/lib/ws/handlers/git-status.ts @@ -1,42 +1,102 @@ import type { StoreApi } from 'zustand'; import type { AppState } from '@/lib/state/store'; import type { WsHandlers } from '@/lib/ws/handlers/types'; -import type { GitSnapshot, SessionCommit } from '@/lib/state/slices/session-runtime/types'; +import type { + GitEventPayload, + GitStatusUpdateEvent, + GitCommitCreatedEvent, + GitCommitsResetEvent, + GitSnapshotCreatedEvent, +} from '@/lib/types/git-events'; + +// Handler functions for each event type +type GitEventHandlers = { + status_update: (store: StoreApi, event: GitStatusUpdateEvent) => void; + commit_created: (store: StoreApi, event: GitCommitCreatedEvent) => void; + commits_reset: (store: StoreApi, event: GitCommitsResetEvent) => void; + snapshot_created: (store: StoreApi, event: GitSnapshotCreatedEvent) => void; +}; + +const gitEventHandlers: GitEventHandlers = { + status_update: (store, event) => { + store.getState().setGitStatus(event.session_id, { + branch: event.status.branch, + remote_branch: event.status.remote_branch, + modified: event.status.modified, + added: event.status.added, + deleted: event.status.deleted, + untracked: event.status.untracked, + renamed: event.status.renamed, + ahead: event.status.ahead, + behind: event.status.behind, + files: event.status.files, + timestamp: event.timestamp, + }); + }, + + commit_created: (store, event) => { + store.getState().addSessionCommit(event.session_id, { + id: event.commit.id, + session_id: event.session_id, + commit_sha: event.commit.commit_sha, + parent_sha: event.commit.parent_sha, + commit_message: event.commit.commit_message, + author_name: event.commit.author_name, + author_email: event.commit.author_email, + files_changed: event.commit.files_changed, + insertions: event.commit.insertions, + deletions: event.commit.deletions, + committed_at: event.commit.committed_at, + created_at: event.commit.created_at ?? event.timestamp, + }); + }, + + commits_reset: (store, event) => { + // Clear commits to trigger refetch in useSessionCommits hook + store.getState().clearSessionCommits(event.session_id); + }, + + snapshot_created: (store, event) => { + store.getState().addGitSnapshot(event.session_id, { + id: event.snapshot.id, + session_id: event.snapshot.session_id, + snapshot_type: event.snapshot.snapshot_type as 'status_update' | 'pre_commit' | 'post_commit' | 'pre_stage' | 'post_stage', + branch: event.snapshot.branch, + remote_branch: event.snapshot.remote_branch, + head_commit: event.snapshot.head_commit, + base_commit: event.snapshot.base_commit, + ahead: event.snapshot.ahead, + behind: event.snapshot.behind, + files: event.snapshot.files, + triggered_by: event.snapshot.triggered_by, + created_at: event.snapshot.created_at, + }); + }, +}; export function registerGitStatusHandlers(store: StoreApi): WsHandlers { return { - 'session.git.status': (message) => { - const payload = message.payload; - if (!payload.session_id) { + 'session.git.event': (message) => { + const payload = message.payload as GitEventPayload; + if (!payload.session_id || !payload.type) { return; } - store.getState().setGitStatus(payload.session_id, { - branch: payload.branch, - remote_branch: payload.remote_branch ?? null, - modified: payload.modified, - added: payload.added, - deleted: payload.deleted, - untracked: payload.untracked, - renamed: payload.renamed, - ahead: payload.ahead, - behind: payload.behind, - files: payload.files, - timestamp: payload.timestamp, - }); - }, - 'session.git.snapshot': (message) => { - const payload = message.payload; - if (!payload.session_id || !payload.snapshot) { - return; + + // Use switch for proper type narrowing + switch (payload.type) { + case 'status_update': + gitEventHandlers.status_update(store, payload); + break; + case 'commit_created': + gitEventHandlers.commit_created(store, payload); + break; + case 'commits_reset': + gitEventHandlers.commits_reset(store, payload); + break; + case 'snapshot_created': + gitEventHandlers.snapshot_created(store, payload); + break; } - store.getState().addGitSnapshot(payload.session_id, payload.snapshot as GitSnapshot); - }, - 'session.git.commit': (message) => { - const payload = message.payload; - if (!payload.session_id || !payload.commit) { - return; - } - store.getState().addSessionCommit(payload.session_id, payload.commit as SessionCommit); }, }; } diff --git a/docs/manual-git-commit-sync-analysis.md b/docs/manual-git-commit-sync-analysis.md new file mode 100644 index 0000000000..a761d97816 --- /dev/null +++ b/docs/manual-git-commit-sync-analysis.md @@ -0,0 +1,438 @@ +# Manual Git Commit Sync on Page Refresh - Feasibility Analysis + +## Problem Statement + +When users execute git commands directly in the shell/console (e.g., `git commit`, `git reset`, `git rebase`), the UI and data model don't reflect these changes. The user has accepted that manual git operations will only sync on page refresh. This document analyzes whether we can **fully synchronize** our data model with the actual git state when the UI first requests the data. + +**Full sync means:** +- **Add** commits that exist in git but not in our model (manual `git commit`) +- **Remove** commits that exist in our model but not in git (manual `git reset`, `git rebase`) + +## Current Data Model + +### Key Entities + +1. **SessionCommit** (`task_session_commits` table) + - Stores commits made during a session + - Fields: `commit_sha`, `parent_sha`, `author_name`, `author_email`, `commit_message`, `committed_at`, `files_changed`, `insertions`, `deletions` + - Currently populated only by API-initiated commits via `GitOperator` + +2. **GitSnapshot** (`task_session_git_snapshots` table) + - Point-in-time snapshots of git state + - Fields: `head_commit`, `base_commit`, `branch`, `ahead`, `behind`, `files` + - First snapshot contains `base_commit` (the commit SHA the session started from) + +3. **Worktree** (`task_session_worktrees` table) + - Associates sessions with worktrees + - Fields: `worktree_path`, `worktree_branch`, `repository_id` + - `BaseBranch` stored in `Worktree` model (the branch the worktree was created from) + +4. **TaskSession** (`task_sessions` table) + - Has `repository_id`, `base_branch` fields + - Associated with worktrees via `TaskSessionWorktree` + +### Key Relationships + +``` +TaskSession + └── TaskSessionWorktree (worktree_path, worktree_branch) + └── GitSnapshot (first has base_commit = starting point) + └── SessionCommit (commits we track) +``` + +## Detection Strategy + +### Data Available for Commit Range + +1. **Starting Point**: First `GitSnapshot.base_commit` OR resolve `origin/{baseBranch}` in worktree +2. **Current HEAD**: Run `git rev-parse HEAD` in worktree path +3. **Worktree Path**: From `TaskSessionWorktree.worktree_path` + +### Sync Algorithm + +``` +1. Get worktree path for session (from TaskSessionWorktree) +2. Get base_commit from first GitSnapshot (or derive from BaseBranch) +3. Run: git log --format="%H|%P|%an|%ae|%s|%aI" base_commit..HEAD +4. Parse commits from git output → actualCommits (set of SHAs) +5. Get existing SessionCommit records → storedCommits (set of SHAs) +6. Compute diff: + - toAdd = actualCommits - storedCommits (commits in git, not in DB) + - toRemove = storedCommits - actualCommits (commits in DB, not in git) +7. Insert toAdd commits +8. Delete toRemove commits +``` + +This handles: +- `git commit` → new commit appears in actualCommits → added to DB +- `git reset --hard HEAD~1` → commit disappears from actualCommits → removed from DB +- `git rebase` → old commits gone, new commits appear → DB updated accordingly +- `git commit --amend` → old SHA gone, new SHA appears → old removed, new added + +### Git Command to List Commits + +```bash +git log --format="%H|%P|%an|%ae|%s|%aI" --numstat base_commit..HEAD +``` + +This provides: +- `%H` - commit SHA +- `%P` - parent SHA(s) +- `%an` - author name +- `%ae` - author email +- `%s` - subject (commit message) +- `%aI` - author date (ISO 8601) +- `--numstat` - files changed, insertions, deletions + +## Critical Constraint: Remote Execution + +**The backend cannot directly execute git commands in the worktree because:** + +1. **Docker containers** - The worktree lives inside a container, not accessible from the host filesystem +2. **Remote execution** - The agent might run on a remote VPS or Kubernetes pod +3. **Isolation** - agentctl is the **only** component with filesystem access to the workspace + +**Therefore: All git operations must go through agentctl.** + +## Architecture Options + +### Option A: Handler Layer via Lifecycle Manager (Recommended) + +**Location**: `task/handlers/TaskHandlers.wsGetSessionCommits()` or `agent/handlers/GitHandlers` + +**Flow**: +``` +Frontend (page refresh) + → WS: session.git.commits + → Handler: wsGetSessionCommits + → Check if session has running agentctl (via lifecycle manager) + → If running: call agentctl API to get git log + → Sync commits in DB (add missing, remove orphaned) + → Return synchronized commits + → If not running: return stored commits only (no sync possible) +``` + +**Changes Required**: +1. Add new agentctl endpoint: `GET /api/v1/git/log` (returns commits in range) +2. Add agentctl client method: `GitLog(ctx, baseCommit) ([]*CommitInfo, error)` +3. Modify handler to call agentctl and sync before returning +4. Add `DeleteSessionCommit` to repository + +**Pros**: +- Works with Docker, remote, and Kubernetes execution +- Leverages existing agentctl infrastructure +- Handler already has access to lifecycle manager + +**Cons**: +- Sync only works when session is running (agentctl available) +- Adds latency to the request (git command execution) + +### Option B: Sync on Session Start/Resume + +**Location**: `agent/lifecycle/SessionManager.InitializeSession()` + +**Flow**: +``` +Session start/resume + → agentctl becomes available + → Backend calls agentctl to get git log + → Sync commits in DB + → (Later) Frontend requests commits → returns already-synced data +``` + +**Pros**: +- Sync happens once at session start, not on every request +- Commits are ready when UI requests them + +**Cons**: +- Doesn't sync if user does manual git after session starts +- Still need Option A for mid-session sync + +### Option C: Hybrid (Recommended) + +Combine both: +1. **On session start**: Sync commits via agentctl +2. **On page refresh (if session running)**: Re-sync via agentctl +3. **If session not running**: Return stored commits (stale but acceptable) + +This provides: +- Fresh data when session is active +- Best-effort data when session is stopped +- User understands "refresh while running" = fresh data + +## Recommended Implementation (Option C - Hybrid) + +### 1. New agentctl Endpoint + +```go +// In agentctl/server/api/git.go + +// GET /api/v1/git/log?base_commit= +// Returns all commits from base_commit to HEAD +func (s *Server) handleGitLog(c *gin.Context) { + baseCommit := c.Query("base_commit") + if baseCommit == "" { + c.JSON(400, gin.H{"error": "base_commit is required"}) + return + } + + commits, err := s.procMgr.GetGitOperator().Log(c.Request.Context(), baseCommit) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + + c.JSON(200, gin.H{"commits": commits}) +} +``` + +### 2. GitOperator.Log Method + +```go +// In agentctl/server/process/git.go + +type CommitInfo struct { + SHA string `json:"sha"` + ParentSHA string `json:"parent_sha"` + AuthorName string `json:"author_name"` + AuthorEmail string `json:"author_email"` + Message string `json:"message"` + CommittedAt time.Time `json:"committed_at"` + FilesChanged int `json:"files_changed"` + Insertions int `json:"insertions"` + Deletions int `json:"deletions"` +} + +func (g *GitOperator) Log(ctx context.Context, baseCommit string) ([]*CommitInfo, error) { + // git log --format="%H|%P|%an|%ae|%s|%aI" --numstat base_commit..HEAD + cmd := exec.CommandContext(ctx, "git", "log", + "--format=%H|%P|%an|%ae|%s|%aI", + "--numstat", + baseCommit+"..HEAD") + cmd.Dir = g.workDir + output, err := cmd.Output() + if err != nil { + return nil, err + } + return parseGitLog(string(output)) +} +``` + +### 3. agentctl Client Method + +```go +// In agentctl/client/client.go + +func (c *Client) GitLog(ctx context.Context, baseCommit string) ([]*CommitInfo, error) { + resp, err := c.get(ctx, "/api/v1/git/log?base_commit="+url.QueryEscape(baseCommit)) + if err != nil { + return nil, err + } + var result struct { + Commits []*CommitInfo `json:"commits"` + } + if err := json.Unmarshal(resp, &result); err != nil { + return nil, err + } + return result.Commits, nil +} +``` + +### 4. Handler with Sync Logic + +```go +// In task/handlers/task_handlers.go + +func (h *TaskHandlers) wsGetSessionCommits(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req wsGetSessionCommitsRequest + if err := msg.ParsePayload(&req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.SessionID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + } + + // Try to sync if session is running + if err := h.syncCommitsIfRunning(ctx, req.SessionID); err != nil { + h.logger.Warn("commit sync failed", zap.Error(err), zap.String("session_id", req.SessionID)) + // Non-fatal - continue with stored commits + } + + commits, err := h.controller.GetSessionCommits(ctx, req.SessionID) + if err != nil { + h.logger.Error("failed to get session commits", zap.Error(err), zap.String("session_id", req.SessionID)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get session commits", nil) + } + + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + "session_id": req.SessionID, + "commits": commits, + }) +} + +func (h *TaskHandlers) syncCommitsIfRunning(ctx context.Context, sessionID string) error { + // 1. Check if session has running agentctl + execution, found := h.lifecycle.GetExecutionBySessionID(sessionID) + if !found { + return nil // Not running, skip sync + } + client := execution.GetAgentCtlClient() + if client == nil { + return nil // No client, skip sync + } + + // 2. Get base commit from first snapshot + baseCommit, err := h.controller.GetSessionBaseCommit(ctx, sessionID) + if err != nil || baseCommit == "" { + return nil // No base commit, skip sync + } + + // 3. Get actual commits from agentctl + actualCommits, err := client.GitLog(ctx, baseCommit) + if err != nil { + return fmt.Errorf("git log failed: %w", err) + } + + // 4. Sync with DB + return h.controller.SyncSessionCommits(ctx, sessionID, actualCommits) +} +``` + +### 5. Controller Sync Method + +```go +// In task/controller/task.go + +func (c *TaskController) SyncSessionCommits(ctx context.Context, sessionID string, actual []*CommitInfo) error { + return c.service.SyncSessionCommits(ctx, sessionID, actual) +} + +func (c *TaskController) GetSessionBaseCommit(ctx context.Context, sessionID string) (string, error) { + snapshot, err := c.service.GetFirstGitSnapshot(ctx, sessionID) + if err != nil { + return "", err + } + return snapshot.BaseCommit, nil +} +``` + +### 6. Service Sync Method + +```go +// In task/service/service.go + +func (s *Service) SyncSessionCommits(ctx context.Context, sessionID string, actual []*CommitInfo) error { + stored, err := s.repo.GetSessionCommits(ctx, sessionID) + if err != nil { + return err + } + + storedSHAs := make(map[string]*models.SessionCommit) + for _, c := range stored { + storedSHAs[c.CommitSHA] = c + } + + actualSHAs := make(map[string]bool) + for _, c := range actual { + actualSHAs[c.SHA] = true + } + + // Add commits in git but not in DB + for _, c := range actual { + if _, exists := storedSHAs[c.SHA]; !exists { + commit := &models.SessionCommit{ + SessionID: sessionID, + CommitSHA: c.SHA, + ParentSHA: c.ParentSHA, + AuthorName: c.AuthorName, + AuthorEmail: c.AuthorEmail, + CommitMessage: c.Message, + CommittedAt: c.CommittedAt, + FilesChanged: c.FilesChanged, + Insertions: c.Insertions, + Deletions: c.Deletions, + } + if err := s.repo.CreateSessionCommit(ctx, commit); err != nil { + return fmt.Errorf("failed to add commit %s: %w", c.SHA, err) + } + } + } + + // Remove commits in DB but not in git + for sha, commit := range storedSHAs { + if !actualSHAs[sha] { + if err := s.repo.DeleteSessionCommit(ctx, commit.ID); err != nil { + return fmt.Errorf("failed to remove commit %s: %w", sha, err) + } + } + } + + return nil +} +``` + +### Abstraction Layer Assessment + +| Layer | Current Responsibility | Added Responsibility | Breaks Abstraction? | +|-------|------------------------|----------------------|---------------------| +| agentctl | Workspace operations | GitLog endpoint | No - fits existing pattern | +| Repository | Data access (CRUD) | DeleteSessionCommit | No - standard CRUD | +| Service | Business logic | SyncSessionCommits | No - business logic | +| Controller | Request/response mapping | GetSessionBaseCommit, SyncSessionCommits | No - orchestration | +| Handler | WS/HTTP routing | syncCommitsIfRunning | Minor - but has lifecycle access | + +**Verdict**: This follows existing patterns where handlers access lifecycle manager for agentctl operations (see `agent/handlers/git_handlers.go`). The sync logic is appropriately distributed across layers. + +## Edge Cases + +1. **Session not running** - No agentctl available; return stored commits (stale but acceptable) +2. **No first snapshot** - Cannot determine base commit; skip sync +3. **Git command fails** - Log warning, return existing commits +4. **Concurrent requests** - Use session-level mutex or idempotent operations +5. **Rewritten history (reset, rebase, amend)** - Handled by removing orphaned commits +6. **Force push from remote** - If user pulls rewritten history, sync will update accordingly +7. **Merge commits** - Handled normally; parent_sha may have multiple parents +8. **Container restarted** - agentctl restarts, sync works on next request + +## Required Repository Changes + +A new method is needed to delete commits: + +```go +// In task/repository/interface.go +DeleteSessionCommit(ctx context.Context, id string) error + +// In task/repository/sqlite/git_snapshots.go +func (r *Repository) DeleteSessionCommit(ctx context.Context, id string) error { + _, err := r.db.ExecContext(ctx, `DELETE FROM task_session_commits WHERE id = ?`, id) + return err +} +``` + +## Implementation Summary + +| Component | Changes | +|-----------|---------| +| `agentctl/server/api` | Add `GET /api/v1/git/log` endpoint | +| `agentctl/server/process/git.go` | Add `GitOperator.Log()` method | +| `agentctl/client/client.go` | Add `GitLog()` client method | +| `task/repository/interface.go` | Add `DeleteSessionCommit()` | +| `task/repository/sqlite` | Implement `DeleteSessionCommit()` | +| `task/service/service.go` | Add `SyncSessionCommits()` | +| `task/controller/task.go` | Add `SyncSessionCommits()`, `GetSessionBaseCommit()` | +| `task/handlers/task_handlers.go` | Add `syncCommitsIfRunning()`, modify `wsGetSessionCommits` | + +## Conclusion + +**Yes, this is feasible without breaking abstraction layers.** + +The implementation requires routing through agentctl since the workspace may be in a container or remote environment. The sync happens: +1. **On page refresh** - If session is running, sync via agentctl before returning commits +2. **If session stopped** - Return stored commits (user understands they may be stale) + +This is a "lazy sync" pattern - we only sync when data is requested AND the session is running. The sync is **bidirectional**: +- Commits added manually → appear in UI after refresh (if session running) +- Commits removed (reset/rebase/amend) → disappear from UI after refresh (if session running) + +**Limitation**: If the session is stopped, manual git operations won't sync until the session is started again. This is acceptable given the constraint that agentctl must be running to access the workspace. +