Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7471 fix(daemon): durably replay terminal reports (#8533)

Multica Eveff2933d67a6a
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 1db5db8611..274389c30e 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -532,6 +532,10 @@ func (c *Client) ReportTaskMessages(ctx context.Context, taskID string, messages
}
func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) error {
+ return c.completeTaskWithRetrySchedule(ctx, taskID, output, branchName, sessionID, workDir, sessionRolloutMissing, retiredSessionID, durableWorkDir, defaultTerminalRetrySchedule)
+}
+
+func (c *Client) completeTaskWithRetrySchedule(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string, schedule []time.Duration) error {
body := map[string]any{"output": output}
if branchName != "" {
body["branch_name"] = branchName
@@ -551,7 +555,7 @@ func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, s
if retiredSessionID != "" {
body["retired_session_id"] = retiredSessionID
}
- return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/complete", taskID), body, nil, defaultTerminalRetrySchedule)
+ return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/complete", taskID), body, nil, schedule)
}
func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []TaskUsageEntry) error {
@@ -564,6 +568,10 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}
func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) error {
+ return c.failTaskWithRetrySchedule(ctx, taskID, errMsg, sessionID, workDir, branchName, failureReason, sessionRolloutMissing, retiredSessionID, durableWorkDir, defaultTerminalRetrySchedule)
+}
+
+func (c *Client) failTaskWithRetrySchedule(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string, schedule []time.Duration) error {
body := map[string]any{"error": errMsg}
if sessionID != "" {
body["session_id"] = sessionID
@@ -589,7 +597,7 @@ func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDi
if retiredSessionID != "" {
body["retired_session_id"] = retiredSessionID
}
- return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil, defaultTerminalRetrySchedule)
+ return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/fail", taskID), body, nil, schedule)
}
// PinTaskSession persists the agent's session_id and work_dir on the task
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 2e4818d25b..42ed5e91d5 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -243,6 +243,8 @@ type terminalTaskReport struct {
retiredSessionID string
}
+type terminalReportSendFunc func(context.Context, terminalTaskReport, []time.Duration) error
+
type executionEnvironmentCommand func() ([]string, error)
func defaultExecutionEnvironmentCommand() ([]string, error) {
@@ -384,6 +386,16 @@ type Daemon struct {
skillCache *SkillBundleCache
logger *slog.Logger
+ // terminalReports is the durable outbox for complete/fail callbacks. The
+ // sender hook is production-wired through Client and overridable in focused
+ // tests; terminalReportWakeup coalesces new-report and reconnect nudges.
+ terminalReports *terminalReportStore
+ terminalReportSend terminalReportSendFunc
+ terminalReportWakeup chan struct{}
+ terminalReportNow func() time.Time
+ terminalReportMu sync.Mutex
+ terminalReportFlight map[string]struct{}
+
mu sync.Mutex
workspaces map[string]*workspaceState
runtimeIndex map[string]Runtime // runtimeID -> Runtime for provider lookups
@@ -694,6 +706,10 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
repoCache: repocache.New(cacheRoot, logger),
skillCache: NewSkillBundleCache(skillCacheRoot),
logger: logger,
+ terminalReports: newTerminalReportStore(cfg),
+ terminalReportWakeup: make(chan struct{}, 1),
+ terminalReportNow: time.Now,
+ terminalReportFlight: make(map[string]struct{}),
workspaces: make(map[string]*workspaceState),
runtimeIndex: make(map[string]Runtime),
profileLaunchSpecs: make(map[string]profileLaunchSpec),
@@ -2130,6 +2146,7 @@ func (d *Daemon) Run(ctx context.Context) error {
// Start workspace sync loop to discover newly created workspaces.
go d.workspaceSyncLoop(ctx)
+ go d.terminalReportReplayLoop(ctx)
// Discover agent CLIs installed after startup (MUL-5439). Separate from the
// workspace sync loop because that one runs on a thirty-minute consistency
@@ -2149,7 +2166,7 @@ func (d *Daemon) Run(ctx context.Context) error {
// readiness wait blocks on, so success is reported only after startup
// actually completed, not merely because the health port came up.
d.ready.Store(true)
- d.logger.Debug("background loops launched (workspace-sync, task-wakeup, heartbeat, gc, auto-update, token-renewal); health now reporting ready")
+ d.logger.Debug("background loops launched (workspace-sync, terminal-report-replay, task-wakeup, heartbeat, gc, auto-update, token-renewal); health now reporting ready")
err = d.pollLoop(ctx, taskWakeups)
d.logger.Debug("daemon main loop returning", "error", err)
return err
@@ -6235,48 +6252,11 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
if err == nil {
return
}
- // CompleteTask retries transient errors internally. A transient
- // error reaching us here means the schedule was exhausted while
- // the upstream was still 5xx / unreachable. Converting that into
- // a fail would lose the agent's actual result and surface a
- // misleading red badge in the UI — leave the task in running
- // instead so a future fix (server-side stuck-task reaper, or a
- // daemon-side persistent pending queue) can recover it. Only
- // permanent server-side rejections (4xx other than 408/429)
- // warrant the legacy fallback, because at that point the server
- // has already refused this task and the only useful UI signal
- // left is a concrete failure.
- if isTransientError(err) {
- taskLog.Error("complete task failed after retries; leaving task in running rather than falling back to fail", "error", err)
- return
- }
- taskLog.Error("complete task rejected by server, falling back to fail", "error", err)
- // MUL-2946: this fallback fires when a server-side complete
- // callback was permanently rejected (4xx other than 408/429)
- // — the agent itself succeeded, so the err here describes the
- // server response rather than an agent failure. The classifier
- // is unlikely to match anything in the server's error text and
- // will land at ReasonAgentUnknown ("agent_error.unknown"),
- // which is the canonical replacement for the legacy
- // "agent_error" coarse bucket.
- fallbackErrMsg := fmt.Sprintf("complete task failed: %s", err.Error())
- if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
- kind: terminalTaskReportFail,
- taskID: taskID,
- errorMessage: fallbackErrMsg,
- // The agent succeeded here — only the server's complete callback was
- // rejected. Its branch is real and already committed, so it must
- // survive the downgrade to a failure report.
- branchName: result.BranchName,
- sessionID: result.SessionID,
- workDir: result.WorkDir,
- durableWorkDir: result.DurableWorkDir,
- failureReason: taskfailure.Classify(fallbackErrMsg).String(),
- sessionRolloutMissing: result.SessionRolloutMissing,
- retiredSessionID: result.RetiredSessionID,
- }); failErr != nil {
- taskLog.Error("fail task fallback also failed", "error", failErr)
- }
+ // The original completion is already durable. Never overwrite it with a
+ // synthetic failure: a temporary auth/config skew can make a 4xx recover
+ // after restart just as a transport outage can make a 5xx recover, and the
+ // user's successful output must remain authoritative in both cases.
+ taskLog.Error("complete task callback not acknowledged; durable report remains queued", "error", err)
default:
failureReason := result.FailureReason
if failureReason == "" {
@@ -6318,20 +6298,102 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
}
}
-// reportTerminalTask is the only path that sends complete/fail callbacks.
+// reportTerminalTask is the only path that sends complete/fail callbacks. It
+// attempts to persist the exact report before the first network request and
+// removes a persisted copy only after a successful response. A crash after the
+// server commit but before local acknowledgement merely replays the same
+// idempotent terminal request. If persistence itself fails, the direct request
+// still runs so a healthy server is not held hostage by the local disk.
+//
// It deliberately preserves context values while discarding cancellation and
// parent deadlines: daemon shutdown cancels the root context before pollLoop's
// 30-second drain, but terminal callbacks must still use that remaining window.
// The explicit timeout keeps this detached work bounded during normal runs.
func (d *Daemon) reportTerminalTask(parentCtx context.Context, report terminalTaskReport) error {
+ if _, err := persistedTerminalReport(report, time.Now()); err != nil {
+ return err
+ }
+ release, ok := d.beginTerminalReportDelivery(report.taskID)
+ if !ok {
+ return fmt.Errorf("terminal task report for %s is already being delivered", report.taskID)
+ }
+ defer release()
+
+ persisted := false
+ if d.terminalReports != nil {
+ if err := d.terminalReports.enqueue(report); err != nil {
+ // Durability is an availability improvement, not a prerequisite for
+ // the online callback. A read-only/full disk must not turn a request
+ // that the server could accept right now into a stuck task.
+ d.logger.Error("persist terminal task report; continuing with direct delivery",
+ "task", report.taskID,
+ "kind", report.kind,
+ "error", err,
+ )
+ } else {
+ persisted = true
+ }
+ }
+
ctx, cancel := context.WithTimeout(context.WithoutCancel(parentCtx), terminalTaskReportTimeout)
defer cancel()
+ err := d.sendTerminalTaskReport(ctx, report, defaultTerminalRetrySchedule)
+ if err != nil {
+ quarantined := false
+ if persisted {
+ item := pendingTerminalTaskReport{fileName: terminalReportFileName(report.taskID), report: report}
+ quarantined = d.handleTerminalReportDeliveryError(ctx, item, err)
+ }
+ if persisted && !quarantined {
+ d.signalTerminalReportReplay()
+ }
+ return err
+ }
+ if !persisted {
+ return nil
+ }
+ item := pendingTerminalTaskReport{fileName: terminalReportFileName(report.taskID), report: report}
+ if err := d.terminalReports.acknowledge(item); err != nil {
+ d.signalTerminalReportReplay()
+ return fmt.Errorf("acknowledge terminal task report: %w", err)
+ }
+ return nil
+}
+func (d *Daemon) beginTerminalReportDelivery(taskID string) (func(), bool) {
+ d.terminalReportMu.Lock()
+ if d.terminalReportFlight == nil {
+ d.terminalReportFlight = make(map[string]struct{})
+ }
+ if _, exists := d.terminalReportFlight[taskID]; exists {
+ d.terminalReportMu.Unlock()
+ return nil, false
+ }
+ d.terminalReportFlight[taskID] = struct{}{}
+ d.terminalReportMu.Unlock()
+ return func() {
+ d.terminalReportMu.Lock()
+ delete(d.terminalReportFlight, taskID)
+ d.terminalReportMu.Unlock()
+ }, true
+}
+
+func (d *Daemon) terminalReportClock() time.Time {
+ if d.terminalReportNow != nil {
+ return d.terminalReportNow()
+ }
+ return time.Now()
+}
+
+func (d *Daemon) sendTerminalTaskReport(ctx context.Context, report terminalTaskReport, schedule []time.Duration) error {
+ if d.terminalReportSend != nil {
+ return d.terminalReportSend(ctx, report, schedule)
+ }
switch report.kind {
case terminalTaskReportComplete:
- return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir)
+ return d.client.completeTaskWithRetrySchedule(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir, schedule)
case terminalTaskReportFail:
- return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.branchName, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir)
+ return d.client.failTaskWithRetrySchedule(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.branchName, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID, report.durableWorkDir, schedule)
default:
return fmt.Errorf("unsupported terminal task report kind %d", report.kind)
}
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index ab211eb183..894a7a1607 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -4909,10 +4909,10 @@ func TestReportTaskResult_TransientCompleteExhaustedDoesNotFallback(t *testing.T
}
}
-// On permanent 4xx from /complete (e.g. 400 bad body, 404 task not found)
-// the helper bails immediately and the daemon falls back to /fail so the
-// UI shows a concrete failure rather than a perpetually-running task.
-func TestReportTaskResult_PermanentCompleteFallsBackToFail(t *testing.T) {
+// A permanent response can become recoverable after a daemon/server upgrade
+// or credential refresh. Preserve the successful result instead of replacing
+// it with a synthetic failure payload.
+func TestReportTaskResult_PermanentCompleteDoesNotReplaceOriginal(t *testing.T) {
defer noSleepRetry(t)()
var completeCalls, failCalls atomic.Int32
@@ -4939,12 +4939,12 @@ func TestReportTaskResult_PermanentCompleteFallsBackToFail(t *testing.T) {
if got := completeCalls.Load(); got != 1 {
t.Fatalf("permanent 400 should not retry, got %d complete attempts", got)
}
- if got := failCalls.Load(); got != 1 {
- t.Fatalf("permanent /complete should fall back to /fail exactly once, got %d", got)
+ if got := failCalls.Load(); got != 0 {
+ t.Fatalf("permanent /complete must not replace the original with /fail, got %d calls", got)
}
}
-func TestReportTaskResult_CancelledParentStillRunsPermanentFailureFallback(t *testing.T) {
+func TestReportTaskResult_CancelledParentStillPreservesPermanentCompletion(t *testing.T) {
defer noSleepRetry(t)()
var completeCalls, failCalls atomic.Int32
@@ -4974,8 +4974,8 @@ func TestReportTaskResult_CancelledParentStillRunsPermanentFailureFallback(t *te
if got := completeCalls.Load(); got != 1 {
t.Fatalf("complete calls = %d, want 1", got)
}
- if got := failCalls.Load(); got != 1 {
- t.Fatalf("fallback fail calls = %d, want 1", got)
+ if got := failCalls.Load(); got != 0 {
+ t.Fatalf("fallback fail calls = %d, want 0", got)
}
}
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index 1b4c263442..2faed3264a 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -58,9 +58,16 @@ type HealthResponse struct {
// Repo maintenance stays a liveness-safe background activity, so health
// remains HTTP 200/running. These additive counters explain degraded repo
// checkout capacity to operators without exposing local cache paths.
- RepoMaintenanceActive int `json:"repo_maintenance_active,omitempty"`
- RepoCheckoutWaiters int `json:"repo_checkout_waiters,omitempty"`
- Agents []string `json:"agents"`
+ RepoMaintenanceActive int `json:"repo_maintenance_active,omitempty"`
+ RepoCheckoutWaiters int `json:"repo_checkout_waiters,omitempty"`
+ // Terminal report queue diagnostics are additive and expose only counts and
+ // bytes, never payloads or local paths. Failed records require operator
+ // attention; pending records are still being replayed automatically.
+ PendingTerminalReportCount int `json:"pending_terminal_report_count"`
+ PendingTerminalReportBytes int64 `json:"pending_terminal_report_bytes"`
+ FailedTerminalReportCount int `json:"failed_terminal_report_count"`
+ FailedTerminalReportBytes int64 `json:"failed_terminal_report_bytes"`
+ Agents []string `json:"agents"`
// SkippedAgents maps a provider that WAS discovered on this machine to the
// reason the last registration round dropped it (version undetectable,
// below the minimum supported version). Purely diagnostic, and omitted when
@@ -353,6 +360,14 @@ func (d *Daemon) healthHandler(startedAt time.Time) http.HandlerFunc {
resp.RepoMaintenanceActive = activity.MaintenanceActive
resp.RepoCheckoutWaiters = activity.ForegroundWaiters
}
+ if stats, err := d.terminalReports.stats(); err != nil {
+ d.logger.Warn("health: scan terminal report queue", "error", err)
+ } else {
+ resp.PendingTerminalReportCount = stats.PendingCount
+ resp.PendingTerminalReportBytes = stats.PendingBytes
+ resp.FailedTerminalReportCount = stats.FailedCount
+ resp.FailedTerminalReportBytes = stats.FailedBytes
+ }
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.go
index 375c85dcc8..616569170b 100644
--- a/server/internal/daemon/health_test.go
+++ b/server/internal/daemon/health_test.go
@@ -9,6 +9,8 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"runtime"
"strings"
"sync"
@@ -96,6 +98,38 @@ func TestHealthHandlerReportsCLIVersionAndTaskCounts(t *testing.T) {
}
}
+func TestHealthHandlerReportsTerminalReportQueueCountsAndBytes(t *testing.T) {
+ d := New(Config{
+ WorkspacesRoot: t.TempDir(),
+ ServerBaseURL: "https://api.example.test",
+ DaemonID: "health-terminal-reports",
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ d.ready.Store(true)
+ report := terminalTaskReport{kind: terminalTaskReportComplete, taskID: "pending", output: "private output"}
+ if err := d.terminalReports.enqueue(report); err != nil {
+ t.Fatalf("enqueue pending report: %v", err)
+ }
+ if err := os.MkdirAll(d.terminalReports.failedDir(), 0o700); err != nil {
+ t.Fatalf("create failed queue: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(d.terminalReports.failedDir(), "failed.json"), []byte("failed payload"), 0o600); err != nil {
+ t.Fatalf("write failed report: %v", err)
+ }
+
+ rec := httptest.NewRecorder()
+ d.healthHandler(time.Now()).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))
+ var resp HealthResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode health response: %v", err)
+ }
+ if resp.PendingTerminalReportCount != 1 || resp.PendingTerminalReportBytes == 0 ||
+ resp.FailedTerminalReportCount != 1 || resp.FailedTerminalReportBytes != int64(len("failed payload")) {
+ t.Fatalf("terminal report health = pending:%d/%d failed:%d/%d",
+ resp.PendingTerminalReportCount, resp.PendingTerminalReportBytes,
+ resp.FailedTerminalReportCount, resp.FailedTerminalReportBytes)
+ }
+}
+
// TestHealthHandlerReportsDeferredReload covers the "while waiting to restart,
// the reason and state are visible" criterion. When trySelfReload has confirmed
// a multica version change but the daemon was busy at the barrier check, the
diff --git a/server/internal/daemon/terminal_report_queue.go b/server/internal/daemon/terminal_report_queue.go
new file mode 100644
index 0000000000..3ed234839d
--- /dev/null
+++ b/server/internal/daemon/terminal_report_queue.go
@@ -0,0 +1,847 @@
+package daemon
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ terminalReportRecordVersion = 1
+ terminalReportReplayWorkers = 4
+
+ terminalReportReplayInitialBackoff = 5 * time.Second
+ terminalReportReplayMaxBackoff = 5 * time.Minute
+
+ // Only an unchanged request that receives three explicit permanent
+ // rejections over at least ten minutes is quarantined. The count rejects a
+ // one-off proxy response; the age prevents reconnect/startup nudges from
+ // turning three rapid attempts into a false permanent verdict.
+ terminalReportPermanentRejectionLimit = 3
+ terminalReportPermanentRejectionAge = 10 * time.Minute
+)
+
+// persistedTerminalTaskReport is the versioned on-disk form of one terminal
+// callback. It deliberately contains no auth token: replay always uses the
+// daemon's current credential, while the potentially sensitive agent output is
+// protected by owner-only modes on Unix. On Windows Go's mode bits are not an
+// ACL boundary, so protection comes from the current user's profile/workspace
+// ACL; the queue never carries an auth token on either platform.
+//
+// Version stays at 1 because the rejection fields are additive and older
+// daemons ignore unknown JSON fields. A future incompatible version is left
+// untouched and reported on every replay pass; downgrading must never delete a
+// payload merely because the older binary cannot decode it.
+type persistedTerminalTaskReport struct {
+ Version int `json:"version"`
+ CreatedAt time.Time `json:"created_at"`
+ Kind string `json:"kind"`
+ TaskID string `json:"task_id"`
+ Output string `json:"output,omitempty"`
+ BranchName string `json:"branch_name,omitempty"`
+ ErrorMessage string `json:"error,omitempty"`
+ SessionID string `json:"session_id,omitempty"`
+ WorkDir string `json:"work_dir,omitempty"`
+ DurableWorkDir string `json:"durable_work_dir,omitempty"`
+ FailureReason string `json:"failure_reason,omitempty"`
+ SessionRolloutMissing bool `json:"session_rollout_missing,omitempty"`
+ RetiredSessionID string `json:"retired_session_id,omitempty"`
+
+ PermanentRejectionCount int `json:"permanent_rejection_count,omitempty"`
+ FirstPermanentRejectionAt *time.Time `json:"first_permanent_rejection_at,omitempty"`
+ LastPermanentRejectionAt *time.Time `json:"last_permanent_rejection_at,omitempty"`
+ LastPermanentStatus int `json:"last_permanent_status,omitempty"`
+ QuarantinedAt *time.Time `json:"quarantined_at,omitempty"`
+}
+
+type pendingTerminalTaskReport struct {
+ fileName string
+ report terminalTaskReport
+}
+
+type terminalReportStoreStats struct {
+ PendingCount int
+ PendingBytes int64
+ FailedCount int
+ FailedBytes int64
+}
+
+type terminalReportNamespaceStats struct {
+ name string
+ stats terminalReportStoreStats
+}
+
+// terminalReportStore is a file-backed outbox. One file per task keeps each
+// acknowledgement independent, and hashing task IDs prevents a malformed or
+// tampered task ID from becoming a path traversal primitive.
+type terminalReportStore struct {
+ root string
+ namespace string
+ dir string
+ mu sync.Mutex
+}
+
+func newTerminalReportStore(cfg Config) *terminalReportStore {
+ if strings.TrimSpace(cfg.WorkspacesRoot) == "" {
+ return nil
+ }
+ identity := strings.TrimRight(cfg.ServerBaseURL, "/") + "\x00" + cfg.Profile + "\x00" + cfg.DaemonID
+ sum := sha256.Sum256([]byte(identity))
+ namespace := hex.EncodeToString(sum[:16])
+ root := filepath.Join(cfg.WorkspacesRoot, ".pending-terminal-reports", "v1")
+ return &terminalReportStore{
+ root: root,
+ namespace: namespace,
+ dir: filepath.Join(root, namespace),
+ }
+}
+
+func (s *terminalReportStore) failedDir() string { return filepath.Join(s.dir, "failed") }
+
+func terminalReportFileName(taskID string) string {
+ sum := sha256.Sum256([]byte(taskID))
+ return hex.EncodeToString(sum[:]) + ".json"
+}
+
+func terminalReportKindName(kind terminalTaskReportKind) (string, error) {
+ switch kind {
+ case terminalTaskReportComplete:
+ return "complete", nil
+ case terminalTaskReportFail:
+ return "fail", nil
+ default:
+ return "", fmt.Errorf("unsupported terminal task report kind %d", kind)
+ }
+}
+
+func persistedTerminalReport(report terminalTaskReport, createdAt time.Time) (persistedTerminalTaskReport, error) {
+ if strings.TrimSpace(report.taskID) == "" {
+ return persistedTerminalTaskReport{}, errors.New("terminal task report has no task id")
+ }
+ kind, err := terminalReportKindName(report.kind)
+ if err != nil {
+ return persistedTerminalTaskReport{}, err
+ }
+ return persistedTerminalTaskReport{
+ Version: terminalReportRecordVersion,
+ CreatedAt: createdAt.UTC(),
+ Kind: kind,
+ TaskID: report.taskID,
+ Output: report.output,
+ BranchName: report.branchName,
+ ErrorMessage: report.errorMessage,
+ SessionID: report.sessionID,
+ WorkDir: report.workDir,
+ DurableWorkDir: report.durableWorkDir,
+ FailureReason: report.failureReason,
+ SessionRolloutMissing: report.sessionRolloutMissing,
+ RetiredSessionID: report.retiredSessionID,
+ }, nil
+}
+
+func (record persistedTerminalTaskReport) terminalReport() (terminalTaskReport, error) {
+ if record.Version != terminalReportRecordVersion {
+ return terminalTaskReport{}, fmt.Errorf("unsupported terminal report version %d", record.Version)
+ }
+ if strings.TrimSpace(record.TaskID) == "" {
+ return terminalTaskReport{}, errors.New("terminal report has no task id")
+ }
+ var kind terminalTaskReportKind
+ switch record.Kind {
+ case "complete":
+ kind = terminalTaskReportComplete
+ case "fail":
+ kind = terminalTaskReportFail
+ default:
+ return terminalTaskReport{}, fmt.Errorf("unsupported terminal report kind %q", record.Kind)
+ }
+ return terminalTaskReport{
+ kind: kind,
+ taskID: record.TaskID,
+ output: record.Output,
+ branchName: record.BranchName,
+ errorMessage: record.ErrorMessage,
+ sessionID: record.SessionID,
+ workDir: record.WorkDir,
+ durableWorkDir: record.DurableWorkDir,
+ failureReason: record.FailureReason,
+ sessionRolloutMissing: record.SessionRolloutMissing,
+ retiredSessionID: record.RetiredSessionID,
+ }, nil
+}
+
+func (s *terminalReportStore) ensureDir() error {
+ if s == nil {
+ return errors.New("terminal report store is not configured")
+ }
+ return ensureTerminalReportDir(s.dir)
+}
+
+func ensureTerminalReportDir(dir string) error {
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("create terminal report queue: %w", err)
+ }
+ info, err := os.Lstat(dir)
+ if err != nil {
+ return fmt.Errorf("inspect terminal report queue: %w", err)
+ }
+ if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
+ return fmt.Errorf("terminal report queue is not a real directory: %s", dir)
+ }
+ // Tighten an existing directory as well as a newly-created one. Terminal
+ // payloads may include private prompts, results, paths, and error details.
+ if err := os.Chmod(dir, 0o700); err != nil {
+ return fmt.Errorf("secure terminal report queue: %w", err)
+ }
+ return nil
+}
+
+func (s *terminalReportStore) enqueue(report terminalTaskReport) error {
+ record, err := persistedTerminalReport(report, time.Now())
+ if err != nil {
+ return err
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err := s.ensureDir(); err != nil {
+ return err
+ }
+ name := terminalReportFileName(report.taskID)
+ path := filepath.Join(s.dir, name)
+ if existingBody, readErr := os.ReadFile(path); readErr == nil {
+ existing, decodeErr := decodePersistedTerminalReport(existingBody)
+ if decodeErr != nil {
+ return fmt.Errorf("existing terminal report %s is unreadable: %w", name, decodeErr)
+ }
+ existingReport, decodeErr := existing.terminalReport()
+ if decodeErr != nil {
+ return fmt.Errorf("existing terminal report %s is invalid: %w", name, decodeErr)
+ }
+ if existingReport != report {
+ return fmt.Errorf("terminal report for task %s conflicts with the original pending payload", report.taskID)
+ }
+ return nil
+ } else if !errors.Is(readErr, os.ErrNotExist) {
+ return fmt.Errorf("read existing terminal report %s: %w", name, readErr)
+ }
+
+ return writeTerminalReportRecord(s.dir, name, record)
+}
+
+// writeTerminalReportRecord publishes a fully-flushed record with an atomic
+// rename. Callers hold the store mutex. Temp files use the task-derived prefix
+// so startup recovery can validate where an interrupted write belonged.
+func writeTerminalReportRecord(dir, name string, record persistedTerminalTaskReport) error {
+ body, err := json.Marshal(record)
+ if err != nil {
+ return fmt.Errorf("encode terminal report: %w", err)
+ }
+ body = append(body, '\n')
+
+ tmp, err := os.CreateTemp(dir, "."+strings.TrimSuffix(name, ".json")+"-*.tmp")
+ if err != nil {
+ return fmt.Errorf("create terminal report temp file: %w", err)
+ }
+ tmpPath := tmp.Name()
+ cleanup := func() {
+ _ = tmp.Close()
+ _ = os.Remove(tmpPath)
+ }
+ if err := tmp.Chmod(0o600); err != nil {
+ cleanup()
+ return fmt.Errorf("secure terminal report temp file: %w", err)
+ }
+ if _, err := tmp.Write(body); err != nil {
+ cleanup()
+ return fmt.Errorf("write terminal report temp file: %w", err)
+ }
+ if err := tmp.Sync(); err != nil {
+ cleanup()
+ return fmt.Errorf("sync terminal report temp file: %w", err)
+ }
+ if err := tmp.Close(); err != nil {
+ _ = os.Remove(tmpPath)
+ return fmt.Errorf("close terminal report temp file: %w", err)
+ }
+ if err := os.Rename(tmpPath, filepath.Join(dir, name)); err != nil {
+ _ = os.Remove(tmpPath)
+ return fmt.Errorf("publish terminal report: %w", err)
+ }
+ if err := syncTerminalReportDir(dir); err != nil {
+ return fmt.Errorf("sync terminal report queue after enqueue: %w", err)
+ }
+ return nil
+}
+
+func decodePersistedTerminalReport(body []byte) (persistedTerminalTaskReport, error) {
+ var record persistedTerminalTaskReport
+ if err := json.Unmarshal(body, &record); err != nil {
+ return persistedTerminalTaskReport{}, err
+ }
+ return record, nil
+}
+
+func (s *terminalReportStore) list() ([]pendingTerminalTaskReport, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err := s.ensureDir(); err != nil {
+ return nil, err
+ }
+ entries, err := os.ReadDir(s.dir)
+ if err != nil {
+ return nil, fmt.Errorf("read terminal report queue: %w", err)
+ }
+ recoveryErr := s.recoverTempFiles(entries)
+ entries, err = os.ReadDir(s.dir)
+ if err != nil {
+ return nil, errors.Join(recoveryErr, fmt.Errorf("reread terminal report queue: %w", err))
+ }
+ items := make([]pendingTerminalTaskReport, 0, len(entries))
+ var errs []error
+ if recoveryErr != nil {
+ errs = append(errs, recoveryErr)
+ }
+ for _, entry := range entries {
+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
+ continue
+ }
+ body, readErr := os.ReadFile(filepath.Join(s.dir, entry.Name()))
+ if readErr != nil {
+ errs = append(errs, fmt.Errorf("read %s: %w", entry.Name(), readErr))
+ continue
+ }
+ record, decodeErr := decodePersistedTerminalReport(body)
+ if decodeErr != nil {
+ errs = append(errs, fmt.Errorf("decode %s: %w", entry.Name(), decodeErr))
+ continue
+ }
+ report, decodeErr := record.terminalReport()
+ if decodeErr != nil {
+ errs = append(errs, fmt.Errorf("validate %s: %w", entry.Name(), decodeErr))
+ continue
+ }
+ if want := terminalReportFileName(report.taskID); entry.Name() != want {
+ errs = append(errs, fmt.Errorf("terminal report %s does not match task id", entry.Name()))
+ continue
+ }
+ items = append(items, pendingTerminalTaskReport{fileName: entry.Name(), report: report})
+ }
+ sort.Slice(items, func(i, j int) bool { return items[i].fileName < items[j].fileName })
+ return items, errors.Join(errs...)
+}
+
+// recoverTempFiles closes the atomic-write crash window after the temp file is
+// fully flushed but before its rename. A partial/corrupt temp file is retained
+// for forensic recovery and reported as an error; silently deleting it could
+// discard the only copy of a terminal payload.
+func (s *terminalReportStore) recoverTempFiles(entries []os.DirEntry) error {
+ var errs []error
+ changed := false
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".tmp") {
+ continue
+ }
+ tempPath := filepath.Join(s.dir, name)
+ body, err := os.ReadFile(tempPath)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("read interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ record, err := decodePersistedTerminalReport(body)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("decode interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ report, err := record.terminalReport()
+ if err != nil {
+ errs = append(errs, fmt.Errorf("validate interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ targetName := terminalReportFileName(report.taskID)
+ wantPrefix := "." + strings.TrimSuffix(targetName, ".json") + "-"
+ if !strings.HasPrefix(name, wantPrefix) {
+ errs = append(errs, fmt.Errorf("interrupted terminal report %s does not match task id", name))
+ continue
+ }
+ targetPath := filepath.Join(s.dir, targetName)
+ if existingBody, readErr := os.ReadFile(targetPath); readErr == nil {
+ existing, decodeErr := decodePersistedTerminalReport(existingBody)
+ if decodeErr != nil {
+ errs = append(errs, fmt.Errorf("decode terminal report while recovering %s: %w", targetName, decodeErr))
+ continue
+ }
+ existingReport, decodeErr := existing.terminalReport()
+ if decodeErr != nil || existingReport != report {
+ errs = append(errs, fmt.Errorf("interrupted terminal report %s conflicts with existing payload", name))
+ continue
+ }
+ if err := os.Remove(tempPath); err != nil {
+ errs = append(errs, fmt.Errorf("remove duplicate interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ changed = true
+ continue
+ } else if !errors.Is(readErr, os.ErrNotExist) {
+ errs = append(errs, fmt.Errorf("inspect terminal report while recovering %s: %w", targetName, readErr))
+ continue
+ }
+ if err := os.Chmod(tempPath, 0o600); err != nil {
+ errs = append(errs, fmt.Errorf("secure interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ if err := os.Rename(tempPath, targetPath); err != nil {
+ errs = append(errs, fmt.Errorf("recover interrupted terminal report %s: %w", name, err))
+ continue
+ }
+ changed = true
+ }
+ if changed {
+ if err := syncTerminalReportDir(s.dir); err != nil {
+ errs = append(errs, fmt.Errorf("sync terminal report queue after recovery: %w", err))
+ }
+ }
+ return errors.Join(errs...)
+}
+
+func (s *terminalReportStore) acknowledge(item pendingTerminalTaskReport) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if item.fileName != terminalReportFileName(item.report.taskID) {
+ return errors.New("terminal report acknowledgement does not match task id")
+ }
+ path := filepath.Join(s.dir, item.fileName)
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("remove acknowledged terminal report: %w", err)
+ }
+ if err := syncTerminalReportDir(s.dir); err != nil {
+ return fmt.Errorf("sync terminal report queue after acknowledgement: %w", err)
+ }
+ return nil
+}
+
+// terminalReportPermanentRejection classifies only response semantics that are
+// stable for an unchanged terminal request. Authentication expiry (401), rate
+// limiting (429), timeout (408), conflicts, and generic/missing-route 404s stay
+// pending because credentials, deployment version, or server state can recover.
+func terminalReportPermanentRejection(err error) (int, bool) {
+ var reqErr *requestError
+ if !errors.As(err, &reqErr) {
+ return 0, false
+ }
+ switch reqErr.StatusCode {
+ case http.StatusBadRequest, http.StatusForbidden:
+ return reqErr.StatusCode, true
+ case http.StatusNotFound:
+ return reqErr.StatusCode, isTaskNotFoundError(err)
+ default:
+ return 0, false
+ }
+}
+
+// recordPermanentRejection durably counts explicit server rejections and moves
+// the unchanged original payload to failed/ once both the count and age gates
+// are met. The failed record is intentionally retained indefinitely: automatic
+// TTL/size eviction would silently discard the result this outbox protects.
+func (s *terminalReportStore) recordPermanentRejection(item pendingTerminalTaskReport, status int, now time.Time) (bool, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err := s.ensureDir(); err != nil {
+ return false, err
+ }
+ path := filepath.Join(s.dir, item.fileName)
+ body, err := os.ReadFile(path)
+ if err != nil {
+ return false, fmt.Errorf("read rejected terminal report: %w", err)
+ }
+ record, err := decodePersistedTerminalReport(body)
+ if err != nil {
+ return false, fmt.Errorf("decode rejected terminal report: %w", err)
+ }
+ report, err := record.terminalReport()
+ if err != nil {
+ return false, fmt.Errorf("validate rejected terminal report: %w", err)
+ }
+ if item.fileName != terminalReportFileName(report.taskID) || report != item.report {
+ return false, errors.New("rejected terminal report no longer matches queued payload")
+ }
+
+ now = now.UTC()
+ if record.FirstPermanentRejectionAt == nil {
+ first := now
+ record.FirstPermanentRejectionAt = &first
+ }
+ last := now
+ record.LastPermanentRejectionAt = &last
+ record.LastPermanentStatus = status
+ record.PermanentRejectionCount++
+ age := now.Sub(*record.FirstPermanentRejectionAt)
+ quarantine := record.PermanentRejectionCount >= terminalReportPermanentRejectionLimit && age >= terminalReportPermanentRejectionAge
+ if quarantine {
+ quarantinedAt := now
+ record.QuarantinedAt = &quarantinedAt
+ }
+ if err := writeTerminalReportRecord(s.dir, item.fileName, record); err != nil {
+ return false, fmt.Errorf("persist terminal report rejection: %w", err)
+ }
+ if !quarantine {
+ return false, nil
+ }
+ if err := ensureTerminalReportDir(s.failedDir()); err != nil {
+ return false, fmt.Errorf("create failed terminal report queue: %w", err)
+ }
+ failedPath := filepath.Join(s.failedDir(), item.fileName)
+ if existingBody, readErr := os.ReadFile(failedPath); readErr == nil {
+ existing, decodeErr := decodePersistedTerminalReport(existingBody)
+ if decodeErr != nil {
+ return false, fmt.Errorf("existing failed terminal report is unreadable: %w", decodeErr)
+ }
+ existingReport, decodeErr := existing.terminalReport()
+ if decodeErr != nil || existingReport != report {
+ return false, errors.New("failed terminal report conflicts with queued payload")
+ }
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return false, fmt.Errorf("remove duplicate quarantined terminal report: %w", err)
+ }
+ } else if errors.Is(readErr, os.ErrNotExist) {
+ if err := os.Rename(path, failedPath); err != nil {
+ return false, fmt.Errorf("quarantine terminal report: %w", err)
+ }
+ } else {
+ return false, fmt.Errorf("inspect failed terminal report: %w", readErr)
+ }
+ // The rename/removal has completed at this point. Report sync failures to
+ // operators, but also return quarantined=true so the caller performs the
+ // one-time server compensation. Returning false would leave no pending file
+ // for a later pass to rediscover and could strand the server row in running.
+ failedSyncErr := syncTerminalReportDir(s.failedDir())
+ pendingSyncErr := syncTerminalReportDir(s.dir)
+ return true, errors.Join(
+ wrapTerminalReportSyncError("sync failed terminal report queue", failedSyncErr),
+ wrapTerminalReportSyncError("sync pending terminal report queue after quarantine", pendingSyncErr),
+ )
+}
+
+func wrapTerminalReportSyncError(message string, err error) error {
+ if err == nil {
+ return nil
+ }
+ return fmt.Errorf("%s: %w", message, err)
+}
+
+func terminalReportDirectoryStats(dir string) (count int, bytes int64, err error) {
+ entries, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return 0, 0, nil
+ }
+ if err != nil {
+ return 0, 0, err
+ }
+ var errs []error
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ info, infoErr := entry.Info()
+ if infoErr != nil {
+ errs = append(errs, fmt.Errorf("stat %s: %w", entry.Name(), infoErr))
+ continue
+ }
+ count++
+ bytes += info.Size()
+ }
+ return count, bytes, errors.Join(errs...)
+}
+
+func (s *terminalReportStore) stats() (terminalReportStoreStats, error) {
+ if s == nil {
+ return terminalReportStoreStats{}, nil
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ var stats terminalReportStoreStats
+ var errs []error
+ if count, bytes, err := terminalReportDirectoryStats(s.dir); err != nil {
+ errs = append(errs, fmt.Errorf("scan pending terminal reports: %w", err))
+ } else {
+ stats.PendingCount, stats.PendingBytes = count, bytes
+ }
+ if count, bytes, err := terminalReportDirectoryStats(s.failedDir()); err != nil {
+ errs = append(errs, fmt.Errorf("scan failed terminal reports: %w", err))
+ } else {
+ stats.FailedCount, stats.FailedBytes = count, bytes
+ }
+ return stats, errors.Join(errs...)
+}
+
+// otherNamespaceStats surfaces records owned by a different server/profile/
+// daemon identity. Replaying them with the current credential could cross an
+// account boundary, so startup warns instead of adopting or deleting them.
+func (s *terminalReportStore) otherNamespaceStats() ([]terminalReportNamespaceStats, error) {
+ if s == nil {
+ return nil, nil
+ }
+ entries, err := os.ReadDir(s.root)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("scan terminal report namespaces: %w", err)
+ }
+ var out []terminalReportNamespaceStats
+ var errs []error
+ for _, entry := range entries {
+ if !entry.IsDir() || entry.Name() == s.namespace {
+ continue
+ }
+ dir := filepath.Join(s.root, entry.Name())
+ pendingCount, pendingBytes, pendingErr := terminalReportDirectoryStats(dir)
+ failedCount, failedBytes, failedErr := terminalReportDirectoryStats(filepath.Join(dir, "failed"))
+ if pendingErr != nil || failedErr != nil {
+ errs = append(errs, fmt.Errorf("scan terminal report namespace %s: %w", entry.Name(), errors.Join(pendingErr, failedErr)))
+ }
+ stats := terminalReportStoreStats{
+ PendingCount: pendingCount,
+ PendingBytes: pendingBytes,
+ FailedCount: failedCount,
+ FailedBytes: failedBytes,
+ }
+ if stats.PendingCount+stats.FailedCount > 0 {
+ out = append(out, terminalReportNamespaceStats{name: entry.Name(), stats: stats})
+ }
+ }
+ return out, errors.Join(errs...)
+}
+
+func (d *Daemon) signalTerminalReportReplay() {
+ if d.terminalReportWakeup == nil {
+ return
+ }
+ select {
+ case d.terminalReportWakeup <- struct{}{}:
+ default:
+ }
+}
+
+// handleTerminalReportDeliveryError records an explicit permanent rejection.
+// It returns true only after the original payload has been moved out of the
+// replay set into failed/. Transient failures and early permanent rejections
+// remain pending; a post-rename sync error is logged while compensation still
+// runs because there is no pending path left for a later pass to discover.
+func (d *Daemon) handleTerminalReportDeliveryError(ctx context.Context, item pendingTerminalTaskReport, deliveryErr error) bool {
+ status, permanent := terminalReportPermanentRejection(deliveryErr)
+ if !permanent || d.terminalReports == nil {
+ return false
+ }
+ quarantined, err := d.terminalReports.recordPermanentRejection(item, status, d.terminalReportClock())
+ if err != nil {
+ d.logger.Error("record permanent terminal report rejection",
+ "task", item.report.taskID,
+ "kind", item.report.kind,
+ "status", status,
+ "error", err,
+ )
+ }
+ if !quarantined {
+ return false
+ }
+ d.logger.Error("terminal report permanently rejected and quarantined",
+ "task", item.report.taskID,
+ "kind", item.report.kind,
+ "status", status,
+ "failed_queue", true,
+ )
+
+ // A rejected success can otherwise leave a server row in running forever.
+ // Preserve the complete payload in failed/ first, then make the legacy fail
+ // compensation as a separate request. It can settle the row but can never
+ // overwrite or delete the user's original successful result. A semantic
+ // task-not-found response needs no compensation because no row remains.
+ if item.report.kind == terminalTaskReportComplete && !isTaskNotFoundError(deliveryErr) {
+ fallback := terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: item.report.taskID,
+ errorMessage: fmt.Sprintf("successful terminal result was rejected by the server with HTTP %d; the original completion is preserved in the daemon failed terminal-report queue", status),
+ branchName: item.report.branchName,
+ sessionID: item.report.sessionID,
+ workDir: item.report.workDir,
+ durableWorkDir: item.report.durableWorkDir,
+ failureReason: "agent_error.unknown",
+ sessionRolloutMissing: item.report.sessionRolloutMissing,
+ retiredSessionID: item.report.retiredSessionID,
+ }
+ if err := d.sendTerminalTaskReport(ctx, fallback, defaultTerminalRetrySchedule); err != nil {
+ d.logger.Error("terminal report quarantine failure compensation was not accepted",
+ "task", item.report.taskID,
+ "error", err,
+ )
+ } else {
+ d.logger.Warn("terminal report quarantine settled server task as failed; original completion retained",
+ "task", item.report.taskID,
+ )
+ }
+ }
+ return true
+}
+
+// replayPendingTerminalReports makes one delivery attempt per queued report.
+// A small fixed worker pool avoids one dead endpoint blocking every later task
+// for the HTTP client's full timeout while still bounding reconnect pressure.
+// The caller owns the outer backoff; each pending item gets exactly one HTTP
+// attempt. The one-time fail compensation after quarantine uses the normal
+// bounded terminal schedule because there will be no later replay for it.
+func (d *Daemon) replayPendingTerminalReports(ctx context.Context) (pending, delivered int) {
+ if d.terminalReports == nil {
+ return 0, 0
+ }
+ items, err := d.terminalReports.list()
+ listFailed := err != nil
+ if err != nil {
+ d.logger.Error("load pending terminal reports", "error", err)
+ }
+ if len(items) == 0 {
+ if listFailed {
+ // Keep the replay timer alive so corrupt/unsupported/unreadable
+ // records continue to alert instead of warning once at startup and
+ // silently disappearing from operational view.
+ return 1, 0
+ }
+ return 0, 0
+ }
+
+ workers := terminalReportReplayWorkers
+ if len(items) < workers {
+ workers = len(items)
+ }
+ jobs := make(chan pendingTerminalTaskReport)
+ var wg sync.WaitGroup
+ var resultMu sync.Mutex
+ remaining := len(items)
+ for range workers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for item := range jobs {
+ if ctx.Err() != nil {
+ continue
+ }
+ release, ok := d.beginTerminalReportDelivery(item.report.taskID)
+ if !ok {
+ continue
+ }
+ err := d.sendTerminalTaskReport(ctx, item.report, nil)
+ quarantined := false
+ if err == nil {
+ err = d.terminalReports.acknowledge(item)
+ } else {
+ quarantined = d.handleTerminalReportDeliveryError(ctx, item, err)
+ }
+ release()
+ resultMu.Lock()
+ if err == nil {
+ remaining--
+ delivered++
+ } else if quarantined {
+ remaining--
+ } else {
+ d.logger.Warn("pending terminal report remains queued",
+ "task", item.report.taskID,
+ "kind", item.report.kind,
+ "error", err,
+ )
+ }
+ resultMu.Unlock()
+ }
+ }()
+ }
+ for _, item := range items {
+ select {
+ case jobs <- item:
+ case <-ctx.Done():
+ close(jobs)
+ wg.Wait()
+ return remaining, delivered
+ }
+ }
+ close(jobs)
+ wg.Wait()
+ if listFailed && remaining == 0 {
+ remaining = 1
+ }
+ return remaining, delivered
+}
+
+func (d *Daemon) terminalReportReplayLoop(ctx context.Context) {
+ if namespaces, err := d.terminalReports.otherNamespaceStats(); err != nil {
+ d.logger.Warn("scan terminal report namespaces", "error", err)
+ } else {
+ for _, namespace := range namespaces {
+ d.logger.Warn("terminal reports exist for a different daemon identity; not replaying",
+ "namespace", namespace.name,
+ "pending_count", namespace.stats.PendingCount,
+ "pending_bytes", namespace.stats.PendingBytes,
+ "failed_count", namespace.stats.FailedCount,
+ "failed_bytes", namespace.stats.FailedBytes,
+ )
+ }
+ }
+ backoff := terminalReportReplayInitialBackoff
+ var timer *time.Timer
+ resetTimer := func(delay time.Duration) <-chan time.Time {
+ if timer == nil {
+ timer = time.NewTimer(delay)
+ } else {
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ timer.Reset(delay)
+ }
+ return timer.C
+ }
+ defer func() {
+ if timer != nil {
+ timer.Stop()
+ }
+ }()
+
+ // Startup is itself a replay trigger. The queue is loaded only after auth
+ // preflight, so recovered reports use the daemon's current credential.
+ timerCh := resetTimer(0)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-d.terminalReportWakeup:
+ backoff = terminalReportReplayInitialBackoff
+ timerCh = resetTimer(0)
+ case <-timerCh:
+ pending, delivered := d.replayPendingTerminalReports(ctx)
+ if delivered > 0 {
+ d.logger.Info("replayed pending terminal reports", "delivered", delivered, "remaining", pending)
+ }
+ if pending == 0 {
+ timerCh = nil
+ backoff = terminalReportReplayInitialBackoff
+ continue
+ }
+ timerCh = resetTimer(backoff)
+ backoff *= 2
+ if backoff > terminalReportReplayMaxBackoff {
+ backoff = terminalReportReplayMaxBackoff
+ }
+ }
+ }
+}
diff --git a/server/internal/daemon/terminal_report_queue_sync_unix.go b/server/internal/daemon/terminal_report_queue_sync_unix.go
new file mode 100644
index 0000000000..56f1cf42d5
--- /dev/null
+++ b/server/internal/daemon/terminal_report_queue_sync_unix.go
@@ -0,0 +1,14 @@
+//go:build !windows
+
+package daemon
+
+import "os"
+
+func syncTerminalReportDir(path string) error {
+ dir, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer dir.Close()
+ return dir.Sync()
+}
diff --git a/server/internal/daemon/terminal_report_queue_sync_windows.go b/server/internal/daemon/terminal_report_queue_sync_windows.go
new file mode 100644
index 0000000000..ed52716444
--- /dev/null
+++ b/server/internal/daemon/terminal_report_queue_sync_windows.go
@@ -0,0 +1,10 @@
+//go:build windows
+
+package daemon
+
+// Windows does not support fsync on a directory handle. The report file itself
+// is flushed before the atomic rename; duplicate replay remains safe if a crash
+// loses the directory entry or resurrects an acknowledged one. Go's 0600/0700
+// mode arguments also do not create Windows ACLs: confidentiality relies on the
+// current user's profile/workspace ACL. No credential is stored in the queue.
+func syncTerminalReportDir(string) error { return nil }
diff --git a/server/internal/daemon/terminal_report_queue_test.go b/server/internal/daemon/terminal_report_queue_test.go
new file mode 100644
index 0000000000..6a8b679312
--- /dev/null
+++ b/server/internal/daemon/terminal_report_queue_test.go
@@ -0,0 +1,595 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestTerminalReportStoreRoundTripAndPermissions(t *testing.T) {
+ store := newTerminalReportStore(Config{
+ WorkspacesRoot: t.TempDir(),
+ ServerBaseURL: "https://api.example.test",
+ Profile: "work",
+ DaemonID: "daemon-1",
+ })
+ report := terminalTaskReport{
+ kind: terminalTaskReportComplete,
+ taskID: "task-private",
+ output: "private final answer",
+ branchName: "agent/private",
+ sessionID: "session-private",
+ workDir: "/private/workdir",
+ durableWorkDir: "/private/project",
+ sessionRolloutMissing: true,
+ retiredSessionID: "retired-private",
+ }
+ if err := store.enqueue(report); err != nil {
+ t.Fatalf("enqueue terminal report: %v", err)
+ }
+ items, err := store.list()
+ if err != nil {
+ t.Fatalf("list terminal reports: %v", err)
+ }
+ if len(items) != 1 || items[0].report != report {
+ t.Fatalf("round trip = %+v, want %+v", items, report)
+ }
+
+ if runtime.GOOS != "windows" {
+ if info, err := os.Stat(store.dir); err != nil {
+ t.Fatalf("stat queue directory: %v", err)
+ } else if got := info.Mode().Perm(); got != 0o700 {
+ t.Fatalf("queue directory mode = %o, want 700", got)
+ }
+ path := store.dir + string(os.PathSeparator) + items[0].fileName
+ if info, err := os.Stat(path); err != nil {
+ t.Fatalf("stat queue file: %v", err)
+ } else if got := info.Mode().Perm(); got != 0o600 {
+ t.Fatalf("queue file mode = %o, want 600", got)
+ }
+ }
+
+ conflict := report
+ conflict.output = "replacement must not overwrite the original"
+ if err := store.enqueue(conflict); err == nil || !strings.Contains(err.Error(), "conflicts with the original") {
+ t.Fatalf("conflicting enqueue error = %v, want original-payload conflict", err)
+ }
+ items, err = store.list()
+ if err != nil {
+ t.Fatalf("list after conflict: %v", err)
+ }
+ if len(items) != 1 || items[0].report.output != report.output {
+ t.Fatalf("conflicting enqueue changed original payload: %+v", items)
+ }
+}
+
+func TestTerminalReportStoreRecoversFlushedTempFileAfterCrash(t *testing.T) {
+ store := newTerminalReportStore(Config{
+ WorkspacesRoot: t.TempDir(),
+ ServerBaseURL: "https://api.example.test",
+ DaemonID: "daemon-crash",
+ })
+ if err := store.ensureDir(); err != nil {
+ t.Fatalf("prepare store: %v", err)
+ }
+ report := terminalTaskReport{kind: terminalTaskReportComplete, taskID: "task-crash", output: "durable answer"}
+ record, err := persistedTerminalReport(report, time.Now())
+ if err != nil {
+ t.Fatalf("build persisted report: %v", err)
+ }
+ body, err := json.Marshal(record)
+ if err != nil {
+ t.Fatalf("marshal report: %v", err)
+ }
+ targetName := terminalReportFileName(report.taskID)
+ temp, err := os.CreateTemp(store.dir, "."+strings.TrimSuffix(targetName, ".json")+"-*.tmp")
+ if err != nil {
+ t.Fatalf("create interrupted temp: %v", err)
+ }
+ tempName := temp.Name()
+ if err := temp.Chmod(0o600); err != nil {
+ t.Fatalf("chmod interrupted temp: %v", err)
+ }
+ if _, err := temp.Write(body); err != nil {
+ t.Fatalf("write interrupted temp: %v", err)
+ }
+ if err := temp.Sync(); err != nil {
+ t.Fatalf("sync interrupted temp: %v", err)
+ }
+ if err := temp.Close(); err != nil {
+ t.Fatalf("close interrupted temp: %v", err)
+ }
+
+ items, err := store.list()
+ if err != nil {
+ t.Fatalf("recover interrupted report: %v", err)
+ }
+ if len(items) != 1 || items[0].report != report {
+ t.Fatalf("recovered reports = %+v, want %+v", items, report)
+ }
+ if _, err := os.Stat(tempName); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("interrupted temp still exists after recovery: %v", err)
+ }
+}
+
+func TestTerminalReportReplaysAfterClientRetryWindow(t *testing.T) {
+ defer noSleepRetry(t)()
+ previousSchedule := defaultTerminalRetrySchedule
+ defaultTerminalRetrySchedule = []time.Duration{time.Nanosecond, time.Nanosecond}
+ t.Cleanup(func() { defaultTerminalRetrySchedule = previousSchedule })
+
+ var online atomic.Bool
+ var calls atomic.Int32
+ var mu sync.Mutex
+ var bodies []map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if !strings.HasSuffix(req.URL.Path, "/complete") {
+ t.Errorf("unexpected request path %q", req.URL.Path)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
+ t.Errorf("decode request: %v", err)
+ }
+ mu.Lock()
+ bodies = append(bodies, body)
+ mu.Unlock()
+ calls.Add(1)
+ if !online.Load() {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ d := New(Config{
+ ServerBaseURL: srv.URL,
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-retry",
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ report := terminalTaskReport{
+ kind: terminalTaskReportComplete,
+ taskID: "task-retry-window",
+ output: "the original answer",
+ branchName: "agent/recovered",
+ sessionID: "session-1",
+ workDir: "/tmp/work",
+ durableWorkDir: "/tmp/project",
+ }
+ if err := d.reportTerminalTask(context.Background(), report); err == nil {
+ t.Fatal("terminal report unexpectedly succeeded while server was offline")
+ }
+ if got, want := calls.Load(), int32(len(defaultTerminalRetrySchedule)+1); got != want {
+ t.Fatalf("initial callback attempts = %d, want exhausted window of %d", got, want)
+ }
+ if items, err := d.terminalReports.list(); err != nil || len(items) != 1 {
+ t.Fatalf("pending reports after exhausted retries = %d, %v; want 1", len(items), err)
+ }
+
+ online.Store(true)
+ pending, delivered := d.replayPendingTerminalReports(context.Background())
+ if pending != 0 || delivered != 1 {
+ t.Fatalf("replay result pending=%d delivered=%d, want 0/1", pending, delivered)
+ }
+ if got := calls.Load(); got != int32(len(defaultTerminalRetrySchedule)+2) {
+ t.Fatalf("calls after recovery = %d, want one replay after retry exhaustion", got)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ for i, body := range bodies {
+ if body["output"] != report.output || body["branch_name"] != report.branchName || body["durable_work_dir"] != report.durableWorkDir {
+ t.Fatalf("attempt %d payload = %#v, want original report", i+1, body)
+ }
+ }
+}
+
+func TestTerminalReportReplaysAfterDaemonRestart(t *testing.T) {
+ cfg := Config{
+ ServerBaseURL: "https://api.example.test",
+ WorkspacesRoot: t.TempDir(),
+ Profile: "restart",
+ DaemonID: "daemon-restart",
+ }
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ report := terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: "task-restart",
+ errorMessage: "provider failed after doing useful work",
+ branchName: "agent/partial-work",
+ failureReason: "agent_error.process_failure",
+ }
+
+ beforeRestart := New(cfg, logger)
+ beforeRestart.terminalReportSend = func(context.Context, terminalTaskReport, []time.Duration) error {
+ return errors.New("network unavailable")
+ }
+ if err := beforeRestart.reportTerminalTask(context.Background(), report); err == nil {
+ t.Fatal("terminal report unexpectedly succeeded before restart")
+ }
+
+ afterRestart := New(cfg, logger)
+ var replayed terminalTaskReport
+ afterRestart.terminalReportSend = func(_ context.Context, got terminalTaskReport, schedule []time.Duration) error {
+ if schedule != nil {
+ t.Fatalf("replay schedule = %v, want one HTTP attempt", schedule)
+ }
+ replayed = got
+ return nil
+ }
+ pending, delivered := afterRestart.replayPendingTerminalReports(context.Background())
+ if pending != 0 || delivered != 1 {
+ t.Fatalf("restart replay pending=%d delivered=%d, want 0/1", pending, delivered)
+ }
+ if replayed != report {
+ t.Fatalf("restart replay = %+v, want %+v", replayed, report)
+ }
+}
+
+func TestTerminalReportEnqueueFailureStillAttemptsHTTP(t *testing.T) {
+ cfg := Config{
+ ServerBaseURL: "https://api.example.test",
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-read-only-queue",
+ }
+ d := New(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err := os.MkdirAll(filepath.Dir(d.terminalReports.dir), 0o700); err != nil {
+ t.Fatalf("create queue parent: %v", err)
+ }
+ // A regular file where the namespace directory must be deterministically
+ // exercises an unwritable/unusable outbox even when tests run as root.
+ if err := os.WriteFile(d.terminalReports.dir, []byte("not a directory"), 0o600); err != nil {
+ t.Fatalf("create invalid queue path: %v", err)
+ }
+
+ var calls atomic.Int32
+ d.terminalReportSend = func(_ context.Context, got terminalTaskReport, _ []time.Duration) error {
+ calls.Add(1)
+ if got.taskID != "task-online" || got.output != "deliver me" {
+ t.Fatalf("direct report = %+v", got)
+ }
+ return nil
+ }
+ if err := d.reportTerminalTask(context.Background(), terminalTaskReport{
+ kind: terminalTaskReportComplete, taskID: "task-online", output: "deliver me",
+ }); err != nil {
+ t.Fatalf("online delivery failed because enqueue failed: %v", err)
+ }
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("HTTP attempts = %d, want 1 despite enqueue failure", got)
+ }
+}
+
+func TestTerminalReportPermanentRejectionQuarantinesOriginalAndStopsReplay(t *testing.T) {
+ d := New(Config{
+ ServerBaseURL: "https://api.example.test",
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-quarantine",
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+
+ base := time.Date(2026, time.September, 18, 0, 0, 0, 0, time.UTC)
+ now := base
+ d.terminalReportNow = func() time.Time { return now }
+ report := terminalTaskReport{
+ kind: terminalTaskReportComplete, taskID: "task-rejected", output: "original successful answer",
+ branchName: "agent/original", sessionID: "session-original",
+ }
+ var completeCalls, fallbackCalls atomic.Int32
+ d.terminalReportSend = func(_ context.Context, got terminalTaskReport, _ []time.Duration) error {
+ switch got.kind {
+ case terminalTaskReportComplete:
+ completeCalls.Add(1)
+ return &requestError{Method: http.MethodPost, Path: "/complete", StatusCode: http.StatusForbidden, Body: "forbidden"}
+ case terminalTaskReportFail:
+ fallbackCalls.Add(1)
+ return nil
+ default:
+ t.Fatalf("unexpected terminal report kind %d", got.kind)
+ return nil
+ }
+ }
+
+ if err := d.reportTerminalTask(context.Background(), report); err == nil {
+ t.Fatal("permanently rejected completion unexpectedly succeeded")
+ }
+ now = base.Add(5 * time.Minute)
+ if pending, delivered := d.replayPendingTerminalReports(context.Background()); pending != 1 || delivered != 0 {
+ t.Fatalf("second rejection replay = pending:%d delivered:%d, want 1/0", pending, delivered)
+ }
+ now = base.Add(terminalReportPermanentRejectionAge)
+ if pending, delivered := d.replayPendingTerminalReports(context.Background()); pending != 0 || delivered != 0 {
+ t.Fatalf("quarantine replay = pending:%d delivered:%d, want 0/0", pending, delivered)
+ }
+ if got := completeCalls.Load(); got != terminalReportPermanentRejectionLimit {
+ t.Fatalf("completion attempts = %d, want %d", got, terminalReportPermanentRejectionLimit)
+ }
+ if got := fallbackCalls.Load(); got != 1 {
+ t.Fatalf("failure compensation attempts = %d, want 1", got)
+ }
+
+ stats, err := d.terminalReports.stats()
+ if err != nil {
+ t.Fatalf("terminal report stats: %v", err)
+ }
+ if stats.PendingCount != 0 || stats.FailedCount != 1 || stats.FailedBytes == 0 {
+ t.Fatalf("queue stats = %+v, want one non-empty failed record", stats)
+ }
+ body, err := os.ReadFile(filepath.Join(d.terminalReports.failedDir(), terminalReportFileName(report.taskID)))
+ if err != nil {
+ t.Fatalf("read failed terminal report: %v", err)
+ }
+ record, err := decodePersistedTerminalReport(body)
+ if err != nil {
+ t.Fatalf("decode failed terminal report: %v", err)
+ }
+ got, err := record.terminalReport()
+ if err != nil {
+ t.Fatalf("validate failed terminal report: %v", err)
+ }
+ if got != report {
+ t.Fatalf("quarantined payload = %+v, want original %+v", got, report)
+ }
+ if record.PermanentRejectionCount != terminalReportPermanentRejectionLimit || record.QuarantinedAt == nil {
+ t.Fatalf("quarantine metadata = %+v", record)
+ }
+ // failed/ is not part of list(), so another replay pass cannot hot-loop it.
+ if pending, delivered := d.replayPendingTerminalReports(context.Background()); pending != 0 || delivered != 0 {
+ t.Fatalf("post-quarantine replay = pending:%d delivered:%d, want 0/0", pending, delivered)
+ }
+}
+
+func TestTerminalReportPermanentRejectionClassification(t *testing.T) {
+ t.Parallel()
+ tests := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"bad request", &requestError{StatusCode: http.StatusBadRequest}, true},
+ {"forbidden", &requestError{StatusCode: http.StatusForbidden}, true},
+ {"semantic missing task", &requestError{StatusCode: http.StatusNotFound, Body: "task not found"}, true},
+ {"generic missing route", &requestError{StatusCode: http.StatusNotFound, Body: "not found"}, false},
+ {"expired auth", &requestError{StatusCode: http.StatusUnauthorized}, false},
+ {"rate limited", &requestError{StatusCode: http.StatusTooManyRequests}, false},
+ {"conflict", &requestError{StatusCode: http.StatusConflict}, false},
+ {"server failure", &requestError{StatusCode: http.StatusBadGateway}, false},
+ {"transport", errors.New("connection reset"), false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ _, got := terminalReportPermanentRejection(tc.err)
+ if got != tc.want {
+ t.Fatalf("classification = %t, want %t", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestTerminalReportForegroundAndReplayDoNotSendConcurrently(t *testing.T) {
+ d := New(Config{
+ ServerBaseURL: "https://api.example.test",
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-in-flight",
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ report := terminalTaskReport{kind: terminalTaskReportComplete, taskID: "task-race", output: "once"}
+ if err := d.terminalReports.enqueue(report); err != nil {
+ t.Fatalf("seed pending report: %v", err)
+ }
+
+ started := make(chan struct{})
+ releaseSend := make(chan struct{})
+ var calls atomic.Int32
+ d.terminalReportSend = func(_ context.Context, _ terminalTaskReport, _ []time.Duration) error {
+ if calls.Add(1) == 1 {
+ close(started)
+ }
+ <-releaseSend
+ return nil
+ }
+ foregroundDone := make(chan error, 1)
+ go func() { foregroundDone <- d.reportTerminalTask(context.Background(), report) }()
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("foreground terminal send did not start")
+ }
+
+ if pending, delivered := d.replayPendingTerminalReports(context.Background()); pending != 1 || delivered != 0 {
+ t.Fatalf("racing replay = pending:%d delivered:%d, want 1/0", pending, delivered)
+ }
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("concurrent terminal sends = %d, want exactly one in flight", got)
+ }
+ close(releaseSend)
+ if err := <-foregroundDone; err != nil {
+ t.Fatalf("foreground terminal report: %v", err)
+ }
+ if items, err := d.terminalReports.list(); err != nil || len(items) != 0 {
+ t.Fatalf("pending reports after foreground ack = %d, %v", len(items), err)
+ }
+}
+
+func TestTerminalReportCorruptRecordRemainsVisibleAcrossReplayPasses(t *testing.T) {
+ d := New(Config{
+ ServerBaseURL: "https://api.example.test",
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-corrupt",
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err := d.terminalReports.ensureDir(); err != nil {
+ t.Fatalf("prepare terminal report queue: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(d.terminalReports.dir, "corrupt.json"), []byte("private-corrupt-payload"), 0o600); err != nil {
+ t.Fatalf("write corrupt record: %v", err)
+ }
+ for pass := 1; pass <= 2; pass++ {
+ if pending, delivered := d.replayPendingTerminalReports(context.Background()); pending != 1 || delivered != 0 {
+ t.Fatalf("replay pass %d = pending:%d delivered:%d, want 1/0", pass, pending, delivered)
+ }
+ }
+ stats, err := d.terminalReports.stats()
+ if err != nil {
+ t.Fatalf("terminal report stats: %v", err)
+ }
+ if stats.PendingCount != 1 || stats.PendingBytes == 0 {
+ t.Fatalf("corrupt record stats = %+v", stats)
+ }
+}
+
+func TestTerminalReportFutureVersionIsRetainedAcrossDowngrade(t *testing.T) {
+ store := newTerminalReportStore(Config{
+ ServerBaseURL: "https://api.example.test", WorkspacesRoot: t.TempDir(), DaemonID: "older-daemon",
+ })
+ if err := store.ensureDir(); err != nil {
+ t.Fatalf("prepare terminal report queue: %v", err)
+ }
+ report := terminalTaskReport{kind: terminalTaskReportComplete, taskID: "future-task", output: "future payload"}
+ record, err := persistedTerminalReport(report, time.Now())
+ if err != nil {
+ t.Fatalf("build terminal report: %v", err)
+ }
+ record.Version = terminalReportRecordVersion + 1
+ body, err := json.Marshal(record)
+ if err != nil {
+ t.Fatalf("marshal future report: %v", err)
+ }
+ path := filepath.Join(store.dir, terminalReportFileName(report.taskID))
+ if err := os.WriteFile(path, body, 0o600); err != nil {
+ t.Fatalf("write future report: %v", err)
+ }
+ for pass := 1; pass <= 2; pass++ {
+ items, listErr := store.list()
+ if listErr == nil || !strings.Contains(listErr.Error(), "unsupported terminal report version") {
+ t.Fatalf("list pass %d error = %v, want unsupported-version warning", pass, listErr)
+ }
+ if len(items) != 0 {
+ t.Fatalf("list pass %d replayed future-version record: %+v", pass, items)
+ }
+ got, readErr := os.ReadFile(path)
+ if readErr != nil {
+ t.Fatalf("future-version record removed on pass %d: %v", pass, readErr)
+ }
+ if string(got) != string(body) {
+ t.Fatalf("future-version record changed on pass %d", pass)
+ }
+ }
+}
+
+func TestTerminalReportFindsOtherNamespacesWithoutAdoptingThem(t *testing.T) {
+ cfg := Config{ServerBaseURL: "https://api.example.test", WorkspacesRoot: t.TempDir(), DaemonID: "current"}
+ store := newTerminalReportStore(cfg)
+ otherDir := filepath.Join(store.root, "different-identity")
+ if err := os.MkdirAll(filepath.Join(otherDir, "failed"), 0o700); err != nil {
+ t.Fatalf("create other namespace: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(otherDir, "old.json"), []byte("pending"), 0o600); err != nil {
+ t.Fatalf("write other pending record: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(otherDir, "failed", "old.json"), []byte("failed"), 0o600); err != nil {
+ t.Fatalf("write other failed record: %v", err)
+ }
+ namespaces, err := store.otherNamespaceStats()
+ if err != nil {
+ t.Fatalf("scan namespaces: %v", err)
+ }
+ if len(namespaces) != 1 || namespaces[0].name != "different-identity" ||
+ namespaces[0].stats.PendingCount != 1 || namespaces[0].stats.FailedCount != 1 {
+ t.Fatalf("other namespace stats = %+v", namespaces)
+ }
+ if items, err := store.list(); err != nil || len(items) != 0 {
+ t.Fatalf("current namespace adopted other reports: %d, %v", len(items), err)
+ }
+}
+
+func TestRunBatchPollerReleasesSlotAfterTerminalRetryExhaustion(t *testing.T) {
+ defer noSleepRetry(t)()
+ previousSchedule := defaultTerminalRetrySchedule
+ defaultTerminalRetrySchedule = []time.Duration{time.Nanosecond, time.Nanosecond}
+ t.Cleanup(func() { defaultTerminalRetrySchedule = previousSchedule })
+
+ var completeAttempts atomic.Int32
+ var secondServed atomic.Bool
+ secondStarted := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(req.URL.Path, "/api/daemon/tasks/claim"):
+ switch {
+ case completeAttempts.Load() == 0:
+ _, _ = w.Write([]byte(`{"tasks":[{"id":"t1","runtime_id":"rt-1","issue_id":"i1"}]}`))
+ case secondServed.CompareAndSwap(false, true):
+ _, _ = w.Write([]byte(`{"tasks":[{"id":"t2","runtime_id":"rt-1","issue_id":"i2"}]}`))
+ default:
+ _, _ = w.Write([]byte(`{"tasks":[]}`))
+ }
+ case strings.HasSuffix(req.URL.Path, "/tasks/t1/complete"):
+ completeAttempts.Add(1)
+ w.WriteHeader(http.StatusBadGateway)
+ case strings.HasSuffix(req.URL.Path, "/tasks/t2/complete"):
+ w.WriteHeader(http.StatusOK)
+ default:
+ _, _ = w.Write([]byte(`{}`))
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ d := New(Config{
+ ServerBaseURL: srv.URL,
+ WorkspacesRoot: t.TempDir(),
+ DaemonID: "daemon-slot",
+ PollInterval: time.Hour,
+ MaxConcurrentTasks: 1,
+ }, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1"}}
+ d.runtimeIndex["rt-1"] = Runtime{ID: "rt-1"}
+ d.cancelPollInterval = time.Hour
+ d.taskSlotWait = 20 * time.Millisecond
+ d.runner = taskRunnerFunc(func(_ context.Context, task Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ if task.ID == "t2" {
+ close(secondStarted)
+ }
+ return TaskResult{Status: "completed"}, nil
+ })
+
+ sem := newTaskSlotSemaphore(1)
+ wakeup := make(chan struct{}, 1)
+ var taskWG sync.WaitGroup
+ ctx, cancel := context.WithCancel(context.Background())
+ pollDone := make(chan struct{})
+ go func() {
+ defer close(pollDone)
+ d.runBatchPoller(ctx, ctx, sem, wakeup, &taskWG)
+ }()
+
+ select {
+ case <-secondStarted:
+ case <-time.After(2 * time.Second):
+ cancel()
+ <-pollDone
+ t.Fatalf("second task did not start after first report exhausted retries; attempts=%d", completeAttempts.Load())
+ }
+ if got, want := completeAttempts.Load(), int32(len(defaultTerminalRetrySchedule)+1); got != want {
+ t.Fatalf("first terminal callback attempts = %d, want %d", got, want)
+ }
+ cancel()
+ <-pollDone
+ taskWG.Wait()
+ items, err := d.terminalReports.list()
+ if err != nil {
+ t.Fatalf("list pending reports: %v", err)
+ }
+ if len(items) != 1 || items[0].report.taskID != "t1" {
+ t.Fatalf("pending reports = %+v, want only exhausted task t1", items)
+ }
+}
diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.go
index 07d42aaabe..cfe15dddce 100644
--- a/server/internal/daemon/wakeup.go
+++ b/server/internal/daemon/wakeup.go
@@ -144,6 +144,10 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin
d.logger.Info("task wakeup websocket connected", "runtimes", len(runtimeIDs))
signalTaskWakeup(taskWakeups, "")
+ // A healthy reconnect is the strongest signal that a terminal callback
+ // stranded during an outage may now succeed. The buffered wakeup also
+ // preserves a connect that races replay-loop startup.
+ d.signalTerminalReportReplay()
// signalTaskWakeup only wakes idle ClaimTask pollers. In-flight tasks and
// the workspace sync loop park on coarse tickers (5s and 30s) that do not
// observe the wakeup channel, so anything the server changed during the
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 516db493a3..24af1afe3f 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -457,12 +457,15 @@ func TestCompleteTask_ChatCallbackIdempotent(t *testing.T) {
if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", "", false, "", ""); err != nil {
t.Fatalf("first complete: %v", err)
}
- // Replay: the status CAS fails, so this is an idempotent no-op success.
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", "", false, "", ""); err != nil {
+ // Replay with conflicting content: the status CAS fails, so this is an
+ // idempotent no-op success and the first terminal payload remains final.
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "conflicting replay"), "", "", "", false, "", ""); err != nil {
t.Fatalf("replayed complete must be idempotent success, got %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 1 {
t.Fatalf("expected exactly one assistant outcome after replay, got %d", len(rows))
+ } else if rows[0].Content != "reply" {
+ t.Fatalf("replayed completion replaced the first outcome with %q", rows[0].Content)
}
}
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index 08a3144854..faf911b762 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -106,6 +106,65 @@ func TestCompleteTask_ReconcilesMemberCommentPostedDuringRun(t *testing.T) {
}
}
+// A daemon may replay /complete after the server committed but its response was
+// lost. The task CAS makes that replay a 200, but the handler must also skip the
+// transaction-external reconciliation; otherwise a follow-up that finished
+// between deliveries leaves no pending dedupe row and the same member comment
+// creates a second real agent run.
+func TestCompleteTask_ReplayDoesNotCreateSecondFollowUp(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ dbfx.QueryRow(t,
+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,
+ testWorkspaceID).Scan(&agentID, &runtimeID)
+ issueID := dbfx.Issue(t, "replayed-complete fixture", testutil.Cols{
+ "status": "in_progress",
+ "number": 999009,
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{
+ "created_at": testutil.Raw("now() - interval '10 minutes'"),
+ })
+ var taskID string
+ dbfx.QueryRow(t, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)
+ VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')
+ RETURNING id
+ `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID)
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })
+ dbfx.Exec(t, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, created_at)
+ VALUES ($1, $2, 'member', $3, 'also handle this once', 'comment', $4, now() - interval '1 minute')
+ `, issueID, testWorkspaceID, testUserID, triggerCommentID)
+
+ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("first CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var followUpID string
+ dbfx.QueryRow(t, `
+ SELECT id FROM agent_task_queue
+ WHERE issue_id = $1 AND agent_id = $2 AND id <> $3 AND status = 'queued'
+ `, issueID, agentID, taskID).Scan(&followUpID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, followUpID)
+
+ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {
+ t.Fatalf("replayed CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var total int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, agentID).Scan(&total)
+ if total != 2 {
+ t.Fatalf("task rows after replay = %d, want original + exactly one follow-up", total)
+ }
+ if pending := pendingTaskCountForAgentIssue(t, issueID, agentID); pending != 0 {
+ t.Fatalf("replayed completion created %d additional pending follow-up(s)", pending)
+ }
+}
+
// TestCompleteTask_NoReconcileWhenNoNewMemberComment guards against spurious
// follow-ups: when no member comment arrived after the run started, completion
// must not enqueue any new task.
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 173c46b9db..5a84da2ca6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4111,7 +4111,7 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
// transaction (force session_id NULL + flag the row), so an auto-retry the
// same commit creates and wakes can never observe the withheld pointer or a
// missing continuity-gap flag.
- task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.BranchName, req.SessionRolloutMissing, req.RetiredSessionID, req.DurableWorkDir)
+ task, transitioned, err := h.TaskService.CompleteTaskWithTransition(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.BranchName, req.SessionRolloutMissing, req.RetiredSessionID, req.DurableWorkDir)
if err != nil {
// A CompleteTask error is an infrastructure failure (transaction /
// assistant-outcome write), not a bad request: an already-finalized
@@ -4122,6 +4122,10 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
+ if !transitioned {
+ writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))
+ return
+ }
h.emitIssueExecutedOnFirstCompletion(r, task)
@@ -4809,7 +4813,7 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works
// keep a stale mid-flight pin) and flagging the row in the same commit that
// creates and wakes the auto-retry, so the retry can never claim the withheld
// pointer or miss the continuity gap.
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.BranchName, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID, req.DurableWorkDir)
+ task, transitioned, err := h.TaskService.FailTaskWithTransition(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.BranchName, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID, req.DurableWorkDir)
if err != nil {
// A FailTask error is an infrastructure failure (the terminal
// transaction that also clears the withheld session, writes the
@@ -4822,6 +4826,10 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works
writeError(w, http.StatusInternalServerError, err.Error())
return
}
+ if !transitioned {
+ writeJSON(w, http.StatusOK, taskToResponse(*task, workspaceID))
+ return
+ }
h.TaskService.NotifyTaskFinished(*task)
// Best-effort revoke of the mat_ task token minted at claim. Same
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index ec8c9f1ee5..53eb0b693d 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4288,6 +4288,15 @@ func startsWithAbsolutePath(s string) bool {
// durableWorkDir is terminal delivery metadata, not a resume pointer: it is
// populated only after the daemon confirms a disposable worktree is gone.
func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir, branchName string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, error) {
+ task, _, err := s.CompleteTaskWithTransition(ctx, taskID, result, sessionID, workDir, branchName, sessionRolloutMissing, retiredSessionID, durableWorkDir)
+ return task, err
+}
+
+// CompleteTaskWithTransition reports whether this call won the running ->
+// completed compare-and-swap. Callers with transaction-external side effects
+// must only run them when transitioned is true; a replay against an already
+// terminal task is still an idempotent success but must not emit them again.
+func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir, branchName string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, bool, error) {
var task db.AgentTaskQueue
// chatAssistantMsg is the single assistant outcome row written for a chat
// task inside the completion transaction below. It is broadcast (chat:done)
@@ -4379,7 +4388,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
"current_status", existing.Status,
"agent_id", util.UUIDToString(existing.AgentID),
)
- return &existing, nil
+ return &existing, false, nil
}
slog.Warn("complete task failed",
"task_id", util.UUIDToString(taskID),
@@ -4395,7 +4404,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
"lookup_error", lookupErr,
)
}
- return nil, fmt.Errorf("complete task: %w", err)
+ return nil, false, fmt.Errorf("complete task: %w", err)
}
slog.Info("task completed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
@@ -4490,7 +4499,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// Broadcast
s.broadcastTaskEvent(ctx, protocol.EventTaskCompleted, task)
- return &task, nil
+ return &task, true, nil
}
// chatNoResponseFallback is the non-empty English body stored on a no_response
@@ -4703,6 +4712,14 @@ func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body st
// (via classifyPoisonedError, the timeout / runtime classifier, etc.)
// will have their value preserved untouched.
func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, error) {
+ task, _, err := s.FailTaskWithTransition(ctx, taskID, errMsg, sessionID, workDir, branchName, failureReason, sessionRolloutMissing, retiredSessionID, durableWorkDir)
+ return task, err
+}
+
+// FailTaskWithTransition is the failure counterpart to
+// CompleteTaskWithTransition. The bool is false for an idempotent replay that
+// observed an already-terminal row.
+func (s *TaskService) FailTaskWithTransition(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, bool, error) {
// Strip bytes PostgreSQL cannot store before anything else reads errMsg, so
// the classifier, the transaction and every downstream consumer see the one
// text we will actually persist (GH #7098). Kept at the service boundary
@@ -5000,7 +5017,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
"current_status", existing.Status,
"agent_id", util.UUIDToString(existing.AgentID),
)
- return &existing, nil
+ return &existing, false, nil
}
slog.Warn("fail task failed",
"task_id", util.UUIDToString(taskID),
@@ -5016,7 +5033,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
"lookup_error", lookupErr,
)
}
- return nil, fmt.Errorf("fail task: %w", err)
+ return nil, false, fmt.Errorf("fail task: %w", err)
}
slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg, "failure_reason", failureReason)
@@ -5102,7 +5119,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// because its child reports the eventual terminal outcome.
s.broadcastTaskFailedEvent(ctx, task, errMsg, failureReason, retried != nil)
- return &task, nil
+ return &task, true, nil
}
// retryableReasons enumerates failure reasons that the auto-retry path is
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 8f7ed42c21..8953c9548d 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -110,10 +110,13 @@ func TestCompleteTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.CompleteTask(context.Background(), taskID, nil, "", "", "", false, "", "")
+ got, transitioned, err := svc.CompleteTaskWithTransition(context.Background(), taskID, nil, "", "", "", false, "", "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
+ if transitioned {
+ t.Fatal("already-finalized task reported a new completion transition")
+ }
if got == nil {
t.Fatal("expected task, got nil")
}
@@ -152,10 +155,13 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", "", false, "", "")
+ got, transitioned, err := svc.FailTaskWithTransition(context.Background(), taskID, "agent crashed", "", "", "", "", false, "", "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
+ if transitioned {
+ t.Fatal("already-finalized task reported a new failure transition")
+ }
if got == nil {
t.Fatal("expected task, got nil")
}