From 9255e47c13888ee48eaec502f8303a9d562bcab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Mon, 10 Aug 2026 21:57:02 +0200 Subject: [PATCH] test(backend): cover the office sqlite persistence surface (#2498) Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 5 (1M context) --- .../repository/sqlite/agent_summary_test.go | 493 +++++++++++ .../office/repository/sqlite/agents_test.go | 802 ++++++++++++++++++ .../repository/sqlite/dashboard_test.go | 529 ++++++++++++ .../office/repository/sqlite/failure_test.go | 617 ++++++++++++++ .../sqlite/participants_ops_test.go | 306 +++++++ .../office/repository/sqlite/projects_test.go | 419 +++++++++ .../repository/sqlite/runtime_cleanup_test.go | 260 ++++++ .../repository/sqlite/tasks_filtered_test.go | 181 ++++ .../repository/sqlite/tasks_ops_test.go | 753 ++++++++++++++++ .../office/repository/sqlite/tasks_test.go | 3 + 10 files changed, 4363 insertions(+) create mode 100644 apps/backend/internal/office/repository/sqlite/agent_summary_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/agents_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/dashboard_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/failure_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/participants_ops_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/projects_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/runtime_cleanup_test.go create mode 100644 apps/backend/internal/office/repository/sqlite/tasks_ops_test.go diff --git a/apps/backend/internal/office/repository/sqlite/agent_summary_test.go b/apps/backend/internal/office/repository/sqlite/agent_summary_test.go new file mode 100644 index 0000000000..318f68cecc --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/agent_summary_test.go @@ -0,0 +1,493 @@ +package sqlite_test + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// seedSummaryRun inserts a runs row with explicit timestamps. Timestamps +// are passed as plain "YYYY-MM-DD HH:MM:SS" strings so every comparison +// in the summary queries (which mix stored values with datetime('now')) +// compares like-for-like. +func seedSummaryRun( + t *testing.T, repo *sqlite.Repository, + id, agentID, status, requestedAt, claimedAt, finishedAt, payload string, +) { + t.Helper() + var claimed, finished interface{} + if claimedAt != "" { + claimed = claimedAt + } + if finishedAt != "" { + finished = finishedAt + } + if payload == "" { + payload = "{}" + } + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO runs + (id, agent_profile_id, reason, payload, status, error_message, requested_at, claimed_at, finished_at) + VALUES (?, ?, 'test', ?, ?, '', ?, ?, ?) + `, id, agentID, payload, status, requestedAt, claimed, finished); err != nil { + t.Fatalf("seed run %s: %v", id, err) + } +} + +// seedCostEvent inserts an office_cost_events row with every summed column set. +func seedCostEvent( + t *testing.T, repo *sqlite.Repository, + id, agentID, taskID, occurredAt string, in, cachedIn, out, subcents int, +) { + t.Helper() + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO office_cost_events + (id, session_id, task_id, agent_profile_id, project_id, model, provider, + tokens_in, tokens_cached_in, tokens_out, cost_subcents, estimated, occurred_at, created_at) + VALUES (?, 'sess', ?, ?, '', 'model', 'provider', ?, ?, ?, ?, 0, ?, ?) + `, id, taskID, agentID, in, cachedIn, out, subcents, occurredAt, occurredAt); err != nil { + t.Fatalf("seed cost event %s: %v", id, err) + } +} + +// seedActivity inserts an office_activity_log row. +func seedActivity(t *testing.T, repo *sqlite.Repository, id, actorID, targetType, targetID, createdAt string) { + t.Helper() + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO office_activity_log + (id, workspace_id, actor_type, actor_id, action, target_type, target_id, details, created_at) + VALUES (?, 'ws-1', 'agent', ?, 'worked', ?, ?, '{}', ?) + `, id, actorID, targetType, targetID, createdAt); err != nil { + t.Fatalf("seed activity %s: %v", id, err) + } +} + +func TestRunCountsByDayForAgent_BucketsStatuses(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + base := time.Now().UTC() + + today, yday, ancient := dayStamp(base, 0, 10), dayStamp(base, 1, 10), dayStamp(base, 60, 10) + seedSummaryRun(t, repo, "r-fin", "agent-a", "finished", today, "", "", "") + seedSummaryRun(t, repo, "r-fail", "agent-a", "failed", today, "", "", "") + seedSummaryRun(t, repo, "r-timeout", "agent-a", "timed_out", today, "", "", "") + seedSummaryRun(t, repo, "r-queued", "agent-a", "queued", today, "", "", "") + seedSummaryRun(t, repo, "r-cancel", "agent-a", "cancelled", today, "", "", "") + seedSummaryRun(t, repo, "r-yday", "agent-a", "finished", yday, "", "", "") + seedSummaryRun(t, repo, "r-old", "agent-a", "finished", ancient, "", "", "") + seedSummaryRun(t, repo, "r-other", "agent-b", "finished", today, "", "", "") + + rows, err := repo.RunCountsByDayForAgent(ctx, "agent-a", 14) + if err != nil { + t.Fatalf("RunCountsByDayForAgent: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (today + yesterday, the 60-day-old row is past the cutoff): %+v", + len(rows), rows) + } + if rows[0].Date != dayDate(base, 1) { + t.Errorf("rows[0].Date = %q, want %q (ORDER BY date ascending)", rows[0].Date, dayDate(base, 1)) + } + if want := (sqlite.AgentRunDayRow{Date: dayDate(base, 1), Succeeded: 1}); rows[0] != want { + t.Errorf("yesterday = %+v, want %+v", rows[0], want) + } + want := sqlite.AgentRunDayRow{Date: dayDate(base, 0), Succeeded: 1, Failed: 2, Other: 2} + if rows[1] != want { + t.Errorf("today = %+v, want %+v (timed_out counts as failed; queued+cancelled as other)", rows[1], want) + } +} + +func TestRunCountsByDayForAgent_NonPositiveDaysDefaultsTo14(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + base := time.Now().UTC() + + seedSummaryRun(t, repo, "r-in", "agent-a", "finished", dayStamp(base, 10, 10), "", "", "") + seedSummaryRun(t, repo, "r-out", "agent-a", "finished", dayStamp(base, 20, 10), "", "", "") + + rows, err := repo.RunCountsByDayForAgent(ctx, "agent-a", 0) + if err != nil { + t.Fatalf("RunCountsByDayForAgent: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1 (14-day default window): %+v", len(rows), rows) + } + if rows[0].Date != dayDate(base, 10) { + t.Errorf("date = %q, want %q", rows[0].Date, dayDate(base, 10)) + } +} + +func TestTasksByPriorityByDayForAgent(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + base := time.Now().UTC() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, priority, created_at, updated_at) VALUES + ('pt-crit', 'ws-1', 'a', 'critical', datetime('now'), datetime('now')), + ('pt-high', 'ws-1', 'b', 'high', datetime('now'), datetime('now')), + ('pt-med', 'ws-1', 'c', 'medium', datetime('now'), datetime('now')), + ('pt-low', 'ws-1', 'd', 'low', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + today, yday := dayStamp(base, 0, 10), dayStamp(base, 1, 10) + // Two activity rows on the same (day, task) must collapse to one count. + seedActivity(t, repo, "a-1", "agent-a", "task", "pt-crit", today) + seedActivity(t, repo, "a-2", "agent-a", "task", "pt-crit", dayStamp(base, 0, 14)) + seedActivity(t, repo, "a-3", "agent-a", "task", "pt-high", today) + seedActivity(t, repo, "a-4", "agent-a", "task", "pt-med", yday) + seedActivity(t, repo, "a-5", "agent-a", "task", "pt-low", yday) + // Filtered out: wrong actor, wrong target type, empty target, unjoinable target. + seedActivity(t, repo, "a-6", "agent-b", "task", "pt-crit", today) + seedActivity(t, repo, "a-7", "agent-a", "run", "pt-crit", today) + seedActivity(t, repo, "a-8", "agent-a", "task", "", today) + seedActivity(t, repo, "a-9", "agent-a", "task", "no-such-task", today) + + rows, err := repo.TasksByPriorityByDayForAgent(ctx, "agent-a", 14) + if err != nil { + t.Fatalf("TasksByPriorityByDayForAgent: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 days: %+v", len(rows), rows) + } + wantYday := sqlite.AgentTaskPriorityDayRow{Date: dayDate(base, 1), Medium: 1, Low: 1} + if rows[0] != wantYday { + t.Errorf("yesterday = %+v, want %+v", rows[0], wantYday) + } + wantToday := sqlite.AgentTaskPriorityDayRow{Date: dayDate(base, 0), Critical: 1, High: 1} + if rows[1] != wantToday { + t.Errorf("today = %+v, want %+v (two activity rows on one task count once)", rows[1], wantToday) + } +} + +func TestTasksByStatusByDayForAgent(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + base := time.Now().UTC() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, created_at, updated_at) VALUES + ('st-todo', 'ws-1', 'a', 'TODO', datetime('now'), datetime('now')), + ('st-prog', 'ws-1', 'b', 'IN_PROGRESS', datetime('now'), datetime('now')), + ('st-review', 'ws-1', 'c', 'REVIEW', datetime('now'), datetime('now')), + ('st-done', 'ws-1', 'd', 'COMPLETED', datetime('now'), datetime('now')), + ('st-block', 'ws-1', 'e', 'BLOCKED', datetime('now'), datetime('now')), + ('st-cancel', 'ws-1', 'f', 'CANCELLED', datetime('now'), datetime('now')), + ('st-backlog','ws-1', 'g', 'BACKLOG', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + today := dayStamp(base, 0, 10) + for i, id := range []string{ + "st-todo", "st-prog", "st-review", "st-done", "st-block", "st-cancel", "st-backlog", + } { + seedActivity(t, repo, string(rune('A'+i)), "agent-a", "task", id, today) + } + seedActivity(t, repo, "other", "agent-b", "task", "st-todo", today) + + rows, err := repo.TasksByStatusByDayForAgent(ctx, "agent-a", 0) + if err != nil { + t.Fatalf("TasksByStatusByDayForAgent: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1 day: %+v", len(rows), rows) + } + want := sqlite.AgentTaskStatusDayRow{ + Date: dayDate(base, 0), Todo: 1, InProgress: 1, InReview: 1, + Done: 1, Blocked: 1, Cancelled: 1, Backlog: 1, + } + if rows[0] != want { + t.Errorf("row = %+v, want %+v", rows[0], want) + } +} + +func TestRecentTasksForAgent(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, identifier, state, created_at, updated_at) VALUES + ('rt-1', 'ws-1', 'First task', 'KAN-1', 'IN_PROGRESS', datetime('now'), datetime('now')), + ('rt-2', 'ws-1', 'Second task', '', 'TODO', datetime('now'), datetime('now')), + ('rt-3', 'ws-1', 'Third task', 'KAN-3', 'COMPLETED', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + seedActivity(t, repo, "ra-1", "agent-a", "task", "rt-1", "2026-01-01 10:00:00") + seedActivity(t, repo, "ra-2", "agent-a", "task", "rt-1", "2026-01-05 10:00:00") + seedActivity(t, repo, "ra-3", "agent-a", "task", "rt-2", "2026-01-03 10:00:00") + seedActivity(t, repo, "ra-4", "agent-b", "task", "rt-3", "2026-01-09 10:00:00") + + rows, err := repo.RecentTasksForAgent(ctx, "agent-a", 10) + if err != nil { + t.Fatalf("RecentTasksForAgent: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (agent-b's task excluded): %+v", len(rows), rows) + } + // MAX(created_at) DESC: rt-1's latest activity (Jan 5) beats rt-2's (Jan 3). + if rows[0].TaskID != "rt-1" || rows[1].TaskID != "rt-2" { + t.Fatalf("order = %q,%q, want rt-1,rt-2", rows[0].TaskID, rows[1].TaskID) + } + if rows[0].Identifier != "KAN-1" { + t.Errorf("Identifier = %q, want KAN-1", rows[0].Identifier) + } + if rows[0].Title != "First task" { + t.Errorf("Title = %q, want 'First task'", rows[0].Title) + } + if rows[0].State != "IN_PROGRESS" { + t.Errorf("State = %q, want IN_PROGRESS", rows[0].State) + } + // MAX() strips the column's declared type, so the value arrives as the + // raw stored text rather than the driver's RFC3339 rendering. + if rows[0].LastActiveAt != "2026-01-05 10:00:00" { + t.Errorf("LastActiveAt = %q, want the MAX activity timestamp 2026-01-05 10:00:00", rows[0].LastActiveAt) + } + if rows[1].Identifier != "" { + t.Errorf("rt-2 Identifier = %q, want empty", rows[1].Identifier) + } +} + +func TestRecentTasksForAgent_NonPositiveLimitDefaultsTo10(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + base := time.Now().UTC() + + for i := 0; i < 12; i++ { + id := string(rune('a' + i)) + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, created_at, updated_at) + VALUES (?, 'ws-1', 'title', 'TODO', datetime('now'), datetime('now')) + `, id); err != nil { + t.Fatalf("seed task %s: %v", id, err) + } + seedActivity(t, repo, "act-"+id, "agent-a", "task", id, dayStamp(base, i, 10)) + } + + rows, err := repo.RecentTasksForAgent(ctx, "agent-a", 0) + if err != nil { + t.Fatalf("RecentTasksForAgent: %v", err) + } + if len(rows) != 10 { + t.Errorf("rows = %d, want the default limit of 10", len(rows)) + } +} + +func TestCostAggregateForAgent(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedCostEvent(t, repo, "c-1", "agent-a", "t-1", "2026-01-01 10:00:00", 100, 10, 20, 5) + seedCostEvent(t, repo, "c-2", "agent-a", "t-2", "2026-01-02 10:00:00", 200, 20, 40, 7) + seedCostEvent(t, repo, "c-3", "agent-b", "t-3", "2026-01-03 10:00:00", 999, 99, 99, 99) + + got, err := repo.CostAggregateForAgent(ctx, "agent-a") + if err != nil { + t.Fatalf("CostAggregateForAgent: %v", err) + } + want := sqlite.AgentCostAggregate{ + InputTokens: 300, OutputTokens: 60, CachedTokens: 30, TotalCostSubcents: 12, + } + if got != want { + t.Errorf("aggregate = %+v, want %+v", got, want) + } +} + +func TestCostAggregateForAgent_NoEventsReturnsZeroValue(t *testing.T) { + repo := newTestRepo(t) + + got, err := repo.CostAggregateForAgent(context.Background(), "agent-silent") + if err != nil { + t.Fatalf("CostAggregateForAgent: %v", err) + } + if got != (sqlite.AgentCostAggregate{}) { + t.Errorf("aggregate = %+v, want the zero value", got) + } +} + +func TestRecentRunCostsForAgent(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + // r-1: finished window, two matching cost events. + seedSummaryRun(t, repo, "r-1", "agent-a", "finished", + "2026-01-01 09:00:00", "2026-01-01 10:00:00", "2026-01-01 12:00:00", `{"task_id":"t-1"}`) + seedCostEvent(t, repo, "c-1", "agent-a", "t-1", "2026-01-01 10:30:00", 100, 0, 10, 3) + seedCostEvent(t, repo, "c-2", "agent-a", "t-1", "2026-01-01 11:30:00", 200, 0, 20, 4) + // Outside the claimed→finished window, so excluded. + seedCostEvent(t, repo, "c-3", "agent-a", "t-1", "2026-01-01 09:30:00", 999, 0, 999, 999) + seedCostEvent(t, repo, "c-4", "agent-a", "t-1", "2026-01-01 13:30:00", 888, 0, 888, 888) + // r-2: later run, one matching event. + seedSummaryRun(t, repo, "r-2", "agent-a", "finished", + "2026-01-02 09:00:00", "2026-01-02 10:00:00", "2026-01-02 12:00:00", `{"task_id":"t-2"}`) + seedCostEvent(t, repo, "c-5", "agent-a", "t-2", "2026-01-02 11:00:00", 50, 0, 5, 1) + // r-3: no cost events at all — must not appear (INNER JOIN). + seedSummaryRun(t, repo, "r-3", "agent-a", "finished", + "2026-01-03 09:00:00", "2026-01-03 10:00:00", "2026-01-03 12:00:00", `{"task_id":"t-3"}`) + // A different agent's run + event must not leak in. + seedSummaryRun(t, repo, "r-other", "agent-b", "finished", + "2026-01-04 09:00:00", "2026-01-04 10:00:00", "2026-01-04 12:00:00", `{"task_id":"t-4"}`) + seedCostEvent(t, repo, "c-6", "agent-b", "t-4", "2026-01-04 11:00:00", 77, 0, 77, 77) + + rows, err := repo.RecentRunCostsForAgent(ctx, "agent-a", 10) + if err != nil { + t.Fatalf("RecentRunCostsForAgent: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (r-3 has no cost events): %+v", len(rows), rows) + } + // ORDER BY requested_at DESC. + if rows[0].RunID != "r-2" || rows[1].RunID != "r-1" { + t.Fatalf("order = %q,%q, want r-2,r-1", rows[0].RunID, rows[1].RunID) + } + if rows[0].RequestedAt != "2026-01-02T09:00:00Z" { + t.Errorf("RequestedAt = %q, want 2026-01-02T09:00:00Z", rows[0].RequestedAt) + } + wantR1 := sqlite.AgentRunCostRow{ + RunID: "r-1", RequestedAt: "2026-01-01T09:00:00Z", + InputTokens: 300, OutputTokens: 30, CostSubcents: 7, + } + if rows[1] != wantR1 { + t.Errorf("r-1 = %+v, want %+v (only the in-window events)", rows[1], wantR1) + } + wantR2 := sqlite.AgentRunCostRow{ + RunID: "r-2", RequestedAt: "2026-01-02T09:00:00Z", + InputTokens: 50, OutputTokens: 5, CostSubcents: 1, + } + if rows[0] != wantR2 { + t.Errorf("r-2 = %+v, want %+v", rows[0], wantR2) + } +} + +func TestRecentRunCostsForAgent_UnclaimedRunHasNoLowerBound(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + // claimed_at NULL → the lower bound is skipped, so an event from + // before the run was requested still matches. + seedSummaryRun(t, repo, "r-unclaimed", "agent-a", "queued", + "2026-01-05 09:00:00", "", "2026-01-05 12:00:00", `{"task_id":"t-1"}`) + seedCostEvent(t, repo, "c-early", "agent-a", "t-1", "2026-01-05 08:00:00", 11, 0, 22, 33) + + rows, err := repo.RecentRunCostsForAgent(ctx, "agent-a", 0) + if err != nil { + t.Fatalf("RecentRunCostsForAgent: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1: %+v", len(rows), rows) + } + if rows[0].InputTokens != 11 || rows[0].OutputTokens != 22 || rows[0].CostSubcents != 33 { + t.Errorf("row = %+v, want the pre-claim event counted", rows[0]) + } +} + +func TestRecentRunCostsForAgent_RespectsLimit(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + for i := 1; i <= 4; i++ { + runID := "r-" + string(rune('0'+i)) + taskID := "t-" + string(rune('0'+i)) + day := "2026-01-0" + string(rune('0'+i)) + seedSummaryRun(t, repo, runID, "agent-a", "finished", + day+" 09:00:00", day+" 10:00:00", day+" 12:00:00", `{"task_id":"`+taskID+`"}`) + seedCostEvent(t, repo, "c-"+runID, "agent-a", taskID, day+" 11:00:00", 1, 0, 1, 1) + } + + rows, err := repo.RecentRunCostsForAgent(ctx, "agent-a", 2) + if err != nil { + t.Fatalf("RecentRunCostsForAgent: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (limit)", len(rows)) + } + if rows[0].RunID != "r-4" { + t.Errorf("newest = %q, want r-4", rows[0].RunID) + } +} + +func TestLatestRunForAgent(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedSummaryRun(t, repo, "lr-old", "agent-a", "finished", + "2026-01-01 09:00:00", "2026-01-01 10:00:00", "2026-01-01 12:00:00", `{"task_id":"t-1"}`) + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO runs + (id, agent_profile_id, reason, payload, status, error_message, requested_at, claimed_at, finished_at) + VALUES ('lr-new', 'agent-a', 'task_assigned', '{"task_id":"t-2"}', 'failed', 'boom', + '2026-01-02 09:00:00', NULL, NULL) + `); err != nil { + t.Fatalf("seed newest run: %v", err) + } + seedSummaryRun(t, repo, "lr-other", "agent-b", "finished", + "2026-01-09 09:00:00", "", "", "{}") + + got, err := repo.LatestRunForAgent(ctx, "agent-a") + if err != nil { + t.Fatalf("LatestRunForAgent: %v", err) + } + if got == nil { + t.Fatal("LatestRunForAgent = nil, want the newest run") + } + if got.ID != "lr-new" { + t.Fatalf("ID = %q, want lr-new (requested_at DESC)", got.ID) + } + if got.AgentProfileID != "agent-a" { + t.Errorf("AgentProfileID = %q, want agent-a", got.AgentProfileID) + } + if got.Reason != "task_assigned" { + t.Errorf("Reason = %q, want task_assigned", got.Reason) + } + if got.Payload != `{"task_id":"t-2"}` { + t.Errorf("Payload = %q, want the stored JSON", got.Payload) + } + if got.Status != "failed" { + t.Errorf("Status = %q, want failed", got.Status) + } + if got.ErrorMessage != "boom" { + t.Errorf("ErrorMessage = %q, want boom", got.ErrorMessage) + } + if got.RequestedAt.Format("2006-01-02 15:04:05") != "2026-01-02 09:00:00" { + t.Errorf("RequestedAt = %v, want 2026-01-02 09:00:00", got.RequestedAt) + } + if got.ClaimedAt != nil { + t.Errorf("ClaimedAt = %v, want nil", got.ClaimedAt) + } + if got.FinishedAt != nil { + t.Errorf("FinishedAt = %v, want nil", got.FinishedAt) + } + + // The older run's nullable timestamps must round-trip as non-nil. + if _, err := repo.ExecRaw(ctx, `DELETE FROM runs WHERE id = 'lr-new'`); err != nil { + t.Fatalf("delete newest: %v", err) + } + got, err = repo.LatestRunForAgent(ctx, "agent-a") + if err != nil { + t.Fatalf("LatestRunForAgent after delete: %v", err) + } + if got == nil || got.ID != "lr-old" { + t.Fatalf("got %+v, want lr-old", got) + } + if got.ClaimedAt == nil || got.ClaimedAt.Format("15:04:05") != "10:00:00" { + t.Errorf("ClaimedAt = %v, want 10:00:00", got.ClaimedAt) + } + if got.FinishedAt == nil || got.FinishedAt.Format("15:04:05") != "12:00:00" { + t.Errorf("FinishedAt = %v, want 12:00:00", got.FinishedAt) + } +} + +func TestLatestRunForAgent_NoRunsReturnsNilNil(t *testing.T) { + repo := newTestRepo(t) + + got, err := repo.LatestRunForAgent(context.Background(), "agent-without-runs") + if err != nil { + t.Fatalf("LatestRunForAgent = %v, want nil error for the no-rows case", err) + } + if got != nil { + t.Errorf("got %+v, want nil", got) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/agents_test.go b/apps/backend/internal/office/repository/sqlite/agents_test.go new file mode 100644 index 0000000000..1f7474a606 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/agents_test.go @@ -0,0 +1,802 @@ +package sqlite_test + +import ( + "context" + "strings" + "testing" + "time" + + settingsmodels "github.com/kandev/kandev/internal/agent/settings/models" + "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +func intPtr(v int) *int { return &v } + +// fullAgentInstance builds an office agent with every column the office +// INSERT writes set to a distinct non-default value. +func fullAgentInstance(id, workspaceID, name string) *models.AgentInstance { + lastRun := time.Date(2026, 2, 3, 4, 5, 6, 0, time.UTC) + return &models.AgentInstance{ + ID: id, + AgentID: "cli-claude", + WorkspaceID: workspaceID, + Name: name, + AgentDisplayName: name + " (display)", + Model: "claude-opus-5", + Mode: "architect", + AutoApprove: true, + DangerouslySkipPermissions: true, + AllowIndexing: true, + CLIPassthrough: true, + UserModified: true, + Role: settingsmodels.AgentRole("cto"), + Icon: "🤖", + Status: settingsmodels.AgentStatus("paused"), + ReportsTo: "agent-ceo", + Permissions: `{"hire_agents":true}`, + BudgetMonthlyCents: 4200, + MaxConcurrentSessions: 3, + CooldownSec: 90, + SkipIdleRuns: true, + LastRunFinishedAt: &lastRun, + SkillIDs: `["skill-a","skill-b"]`, + DesiredSkills: `["go","sql"]`, + CustomPrompt: "be terse", + ExecutorPreference: "local_docker", + PauseReason: "cooling off", + ConsecutiveFailures: 2, + FailureThreshold: intPtr(7), + Settings: `{"routing":{"tier_source":"explicit"}}`, + } +} + +// assertAgentProjection compares every field the office SELECT projection +// surfaces. A column dropped from either the INSERT or the projection +// fails here rather than silently reading back a COALESCE default. +func assertAgentProjection(t *testing.T, got, want *models.AgentInstance) { + t.Helper() + checks := []struct { + field string + got, exp interface{} + }{ + {"ID", got.ID, want.ID}, + {"AgentID", got.AgentID, want.AgentID}, + {"WorkspaceID", got.WorkspaceID, want.WorkspaceID}, + {"Name", got.Name, want.Name}, + {"AgentDisplayName", got.AgentDisplayName, want.AgentDisplayName}, + {"Model", got.Model, want.Model}, + {"AutoApprove", got.AutoApprove, want.AutoApprove}, + {"AllowIndexing", got.AllowIndexing, want.AllowIndexing}, + {"CLIPassthrough", got.CLIPassthrough, want.CLIPassthrough}, + {"Role", got.Role, want.Role}, + {"Icon", got.Icon, want.Icon}, + {"Status", got.Status, want.Status}, + {"ReportsTo", got.ReportsTo, want.ReportsTo}, + {"Permissions", got.Permissions, want.Permissions}, + {"BudgetMonthlyCents", got.BudgetMonthlyCents, want.BudgetMonthlyCents}, + {"MaxConcurrentSessions", got.MaxConcurrentSessions, want.MaxConcurrentSessions}, + {"CooldownSec", got.CooldownSec, want.CooldownSec}, + {"SkipIdleRuns", got.SkipIdleRuns, want.SkipIdleRuns}, + {"SkillIDs", got.SkillIDs, want.SkillIDs}, + {"DesiredSkills", got.DesiredSkills, want.DesiredSkills}, + {"ExecutorPreference", got.ExecutorPreference, want.ExecutorPreference}, + {"PauseReason", got.PauseReason, want.PauseReason}, + {"ConsecutiveFailures", got.ConsecutiveFailures, want.ConsecutiveFailures}, + } + for _, c := range checks { + if c.got != c.exp { + t.Errorf("%s = %v, want %v", c.field, c.got, c.exp) + } + } + switch { + case want.FailureThreshold == nil && got.FailureThreshold != nil: + t.Errorf("FailureThreshold = %d, want nil", *got.FailureThreshold) + case want.FailureThreshold != nil && got.FailureThreshold == nil: + t.Errorf("FailureThreshold = nil, want %d", *want.FailureThreshold) + case want.FailureThreshold != nil && *got.FailureThreshold != *want.FailureThreshold: + t.Errorf("FailureThreshold = %d, want %d", *got.FailureThreshold, *want.FailureThreshold) + } + switch { + case want.LastRunFinishedAt == nil && got.LastRunFinishedAt != nil: + t.Errorf("LastRunFinishedAt = %v, want nil", *got.LastRunFinishedAt) + case want.LastRunFinishedAt != nil && got.LastRunFinishedAt == nil: + t.Error("LastRunFinishedAt = nil, want a timestamp") + case want.LastRunFinishedAt != nil && !got.LastRunFinishedAt.Equal(*want.LastRunFinishedAt): + t.Errorf("LastRunFinishedAt = %v, want %v", *got.LastRunFinishedAt, *want.LastRunFinishedAt) + } + if !got.CreatedAt.Equal(want.CreatedAt) { + t.Errorf("CreatedAt = %v, want %v", got.CreatedAt, want.CreatedAt) + } + if !got.UpdatedAt.Equal(want.UpdatedAt) { + t.Errorf("UpdatedAt = %v, want %v", got.UpdatedAt, want.UpdatedAt) + } +} + +func TestCreateAgentInstance_RoundTripsEveryProjectedField(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + want := fullAgentInstance("agent-full", "ws-1", "Ada") + if err := repo.CreateAgentInstance(ctx, want); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + + got, err := repo.GetAgentInstance(ctx, "agent-full") + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + assertAgentProjection(t, got, want) + + // CreateAgentInstance writes settings as the literal '{}' — the + // struct value is persisted by UpdateAgentSettings / UpdateAgentInstance. + if got.Settings != "{}" { + t.Errorf("Settings = %q, want {} on create", got.Settings) + } + + // Columns written by the INSERT but absent from the office projection + // still have to land, so read them straight from the row. + var row struct { + Mode string `db:"mode"` + CustomPrompt string `db:"custom_prompt"` + DangerouslySkipPermissions int `db:"dangerously_skip_permissions"` + UserModified int `db:"user_modified"` + } + if err := repo.ReaderDB().Get(&row, `SELECT COALESCE(mode,'') AS mode, + COALESCE(custom_prompt,'') AS custom_prompt, + dangerously_skip_permissions, user_modified + FROM agent_profiles WHERE id = 'agent-full'`); err != nil { + t.Fatalf("read unprojected columns: %v", err) + } + if row.Mode != "architect" { + t.Errorf("mode = %q, want architect", row.Mode) + } + if row.CustomPrompt != "be terse" { + t.Errorf("custom_prompt = %q, want 'be terse'", row.CustomPrompt) + } + if row.DangerouslySkipPermissions != 1 { + t.Errorf("dangerously_skip_permissions = %d, want 1", row.DangerouslySkipPermissions) + } + if row.UserModified != 1 { + t.Errorf("user_modified = %d, want 1", row.UserModified) + } +} + +func TestCreateAgentInstance_NormalisesDefaults(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + agent := &models.AgentInstance{WorkspaceID: "ws-1", Name: "Minimal"} + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + if agent.ID == "" { + t.Fatal("CreateAgentInstance left ID empty") + } + + got, err := repo.GetAgentInstance(ctx, agent.ID) + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Status != settingsmodels.AgentStatus("idle") { + t.Errorf("Status = %q, want the idle default", got.Status) + } + if got.AgentDisplayName != "Minimal" { + t.Errorf("AgentDisplayName = %q, want it defaulted to Name", got.AgentDisplayName) + } + if got.SkillIDs != "[]" { + t.Errorf("SkillIDs = %q, want []", got.SkillIDs) + } + if got.DesiredSkills != "[]" { + t.Errorf("DesiredSkills = %q, want []", got.DesiredSkills) + } + if got.Permissions != "{}" { + t.Errorf("Permissions = %q, want {}", got.Permissions) + } + if got.FailureThreshold != nil { + t.Errorf("FailureThreshold = %d, want nil (0 in the column means 'inherit')", *got.FailureThreshold) + } + if got.LastRunFinishedAt != nil { + t.Errorf("LastRunFinishedAt = %v, want nil", *got.LastRunFinishedAt) + } + if got.MaxConcurrentSessions != 0 { + t.Errorf("MaxConcurrentSessions = %d, want the inserted 0", got.MaxConcurrentSessions) + } +} + +func TestCreateAgentInstance_RequiresWorkspace(t *testing.T) { + repo := newTestRepo(t) + + err := repo.CreateAgentInstance(context.Background(), &models.AgentInstance{Name: "Orphan"}) + if err == nil { + t.Fatal("CreateAgentInstance without a workspace = nil error, want a rejection") + } + if !strings.Contains(err.Error(), "workspace_id is required") { + t.Errorf("error = %q, want it to name the missing workspace_id", err) + } +} + +// The agent_id column is a FK onto the CLI-tool registrations, so the +// inheritance fallbacks in CreateAgentInstance are load-bearing under FK +// enforcement. Reuses the FK-enabled repo helper for exactly that reason. +func TestCreateAgentInstance_InheritsAgentIDUnderForeignKeys(t *testing.T) { + repo, db := newRouteAttemptsRepoWithFK(t) + ctx := context.Background() + + now := time.Now().UTC() + if _, err := db.Exec( + `INSERT INTO agents (id, name, created_at, updated_at) VALUES ('cli-first', 'First', ?, ?)`, + now, now); err != nil { + t.Fatalf("seed agents row: %v", err) + } + if _, err := db.Exec( + `INSERT INTO agents (id, name, created_at, updated_at) VALUES ('cli-second', 'Second', ?, ?)`, + now.Add(time.Minute), now.Add(time.Minute)); err != nil { + t.Fatalf("seed second agents row: %v", err) + } + + // No workspace agent exists yet → falls back to the oldest CLI tool. + seeded := &models.AgentInstance{WorkspaceID: "ws-fk", Name: "Seeder"} + if err := repo.CreateAgentInstance(ctx, seeded); err != nil { + t.Fatalf("CreateAgentInstance (CLI fallback): %v", err) + } + if seeded.AgentID != "cli-first" { + t.Errorf("AgentID = %q, want cli-first (oldest registered CLI tool)", seeded.AgentID) + } + + // A later agent in the same workspace inherits from the existing profile. + if _, err := db.Exec( + `UPDATE agent_profiles SET agent_id = 'cli-second' WHERE id = ?`, seeded.ID); err != nil { + t.Fatalf("repoint seeded profile: %v", err) + } + inheritor := &models.AgentInstance{WorkspaceID: "ws-fk", Name: "Inheritor"} + if err := repo.CreateAgentInstance(ctx, inheritor); err != nil { + t.Fatalf("CreateAgentInstance (workspace inherit): %v", err) + } + if inheritor.AgentID != "cli-second" { + t.Errorf("AgentID = %q, want cli-second inherited from the workspace peer", inheritor.AgentID) + } + + // Deleting the CLI registration cascades the profiles away. + if _, err := db.Exec(`DELETE FROM agents WHERE id = 'cli-second'`); err != nil { + t.Fatalf("delete agents row: %v", err) + } + remaining, err := repo.ListAgentInstances(ctx, "ws-fk") + if err != nil { + t.Fatalf("ListAgentInstances: %v", err) + } + if len(remaining) != 0 { + t.Fatalf("agents after cascade = %d, want 0: %+v", len(remaining), remaining) + } +} + +func TestGetAgentInstance_NotFoundAndOfficeScoping(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("agent-1", "ws-1", "Ada")); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + // A shallow kanban profile (workspace_id = '') is invisible to office reads. + seedAgentProfile(t, db, "kanban-profile", "") + + got, err := repo.GetAgentInstance(ctx, "missing") + if err == nil { + t.Fatal("GetAgentInstance(missing) = nil error, want not-found") + } + if !strings.Contains(err.Error(), "agent instance not found: missing") { + t.Errorf("error = %q, want it to name the missing agent", err) + } + if got != nil && got.ID != "" { + t.Errorf("GetAgentInstance(missing) returned %+v", got) + } + + if _, err := repo.GetAgentInstance(ctx, "kanban-profile"); err == nil { + t.Error("GetAgentInstance returned a workspace-less profile, want it hidden from office reads") + } + + // A soft-deleted row is also invisible. + if err := repo.DeleteAgentInstance(ctx, "agent-1"); err != nil { + t.Fatalf("DeleteAgentInstance: %v", err) + } + if _, err := repo.GetAgentInstance(ctx, "agent-1"); err == nil { + t.Error("GetAgentInstance returned a soft-deleted agent") + } + var deletedRows int + if err := db.Get(&deletedRows, + `SELECT COUNT(*) FROM agent_profiles WHERE id = 'agent-1' AND deleted_at IS NOT NULL`); err != nil { + t.Fatalf("count soft-deleted rows: %v", err) + } + if deletedRows != 1 { + t.Errorf("soft-deleted rows = %d, want the audit row preserved", deletedRows) + } +} + +func TestGetAgentInstanceByName(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + want := fullAgentInstance("a-1", "ws-a", "Shared") + if err := repo.CreateAgentInstance(ctx, want); err != nil { + t.Fatalf("create ws-a agent: %v", err) + } + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("a-2", "ws-b", "Shared")); err != nil { + t.Fatalf("create ws-b agent: %v", err) + } + + got, err := repo.GetAgentInstanceByName(ctx, "ws-a", "Shared") + if err != nil { + t.Fatalf("GetAgentInstanceByName: %v", err) + } + assertAgentProjection(t, got, want) + + if _, err := repo.GetAgentInstanceByName(ctx, "ws-a", "Nobody"); err == nil { + t.Error("GetAgentInstanceByName(missing) = nil error, want not-found") + } else if !strings.Contains(err.Error(), "agent instance not found: Nobody") { + t.Errorf("error = %q, want it to name the agent", err) + } +} + +func TestGetAgentInstanceByNameAny(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("a-1", "ws-b", "Unique")); err != nil { + t.Fatalf("create agent: %v", err) + } + + got, err := repo.GetAgentInstanceByNameAny(ctx, "Unique") + if err != nil { + t.Fatalf("GetAgentInstanceByNameAny: %v", err) + } + if got.ID != "a-1" || got.WorkspaceID != "ws-b" { + t.Errorf("got %q in %q, want a-1 in ws-b", got.ID, got.WorkspaceID) + } + + if _, err := repo.GetAgentInstanceByNameAny(ctx, "Nobody"); err == nil { + t.Error("GetAgentInstanceByNameAny(missing) = nil error, want not-found") + } +} + +func TestListAgentInstances_ScopeAndOrdering(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + for i, spec := range []struct{ id, ws, name string }{ + {"l-1", "ws-1", "First"}, + {"l-2", "ws-1", "Second"}, + {"l-3", "ws-2", "Third"}, + } { + agent := fullAgentInstance(spec.id, spec.ws, spec.name) + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("create %s: %v", spec.id, err) + } + // Force a deterministic created_at ordering (reverse of insert order). + stamp := time.Date(2026, 1, 10-i, 0, 0, 0, 0, time.UTC) + if _, err := db.Exec(`UPDATE agent_profiles SET created_at = ? WHERE id = ?`, stamp, spec.id); err != nil { + t.Fatalf("stamp %s: %v", spec.id, err) + } + } + seedAgentProfile(t, db, "kanban", "") + + scoped, err := repo.ListAgentInstances(ctx, "ws-1") + if err != nil { + t.Fatalf("ListAgentInstances(ws-1): %v", err) + } + if len(scoped) != 2 { + t.Fatalf("ws-1 agents = %d, want 2", len(scoped)) + } + if scoped[0].ID != "l-2" || scoped[1].ID != "l-1" { + t.Errorf("order = %q,%q, want l-2,l-1 (created_at ascending)", scoped[0].ID, scoped[1].ID) + } + + all, err := repo.ListAgentInstances(ctx, "") + if err != nil { + t.Fatalf("ListAgentInstances(all): %v", err) + } + if len(all) != 3 { + t.Fatalf("all agents = %d, want 3 (workspace-less profile excluded): %+v", len(all), all) + } + for _, a := range all { + if a.ID == "kanban" { + t.Fatal("workspace-less profile leaked into the office list") + } + } + + empty, err := repo.ListAgentInstances(ctx, "ws-nothing") + if err != nil { + t.Fatalf("ListAgentInstances(empty): %v", err) + } + if empty == nil { + t.Fatal("returned nil slice, want empty non-nil") + } + if len(empty) != 0 { + t.Errorf("len = %d, want 0", len(empty)) + } +} + +func TestUpdateAgentInstance_PersistsEveryMutableField(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + agent := &models.AgentInstance{ID: "u-1", WorkspaceID: "ws-1", Name: "Before"} + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + createdAt := agent.CreatedAt + + lastRun := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC) + agent.Name = "After" + agent.Role = settingsmodels.AgentRole("engineer") + agent.Icon = "🛠" + agent.Status = settingsmodels.AgentStatus("working") + agent.ReportsTo = "agent-boss" + agent.Permissions = `{"approve_budget":true}` + agent.BudgetMonthlyCents = 5150 + agent.MaxConcurrentSessions = 4 + agent.CooldownSec = 30 + agent.SkipIdleRuns = true + agent.LastRunFinishedAt = &lastRun + agent.SkillIDs = `["skill-x"]` + agent.DesiredSkills = `["rust"]` + agent.ExecutorPreference = "sprites" + agent.PauseReason = "waiting on review" + agent.FailureThreshold = intPtr(11) + agent.Settings = `{"routing":{"tier_source":"inherit"}}` + agent.AutoApprove = true + agent.AllowIndexing = true + agent.CLIPassthrough = true + if err := repo.UpdateAgentInstance(ctx, agent); err != nil { + t.Fatalf("UpdateAgentInstance: %v", err) + } + + got, err := repo.GetAgentInstance(ctx, "u-1") + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + // agent_display_name is not in the office UPDATE — it stays at the value + // CreateAgentInstance defaulted from Name. + agent.AgentDisplayName = "Before" + assertAgentProjection(t, got, agent) + if got.Settings != `{"routing":{"tier_source":"inherit"}}` { + t.Errorf("Settings = %q, want the updated JSON", got.Settings) + } + if !got.CreatedAt.Equal(createdAt) { + t.Errorf("CreatedAt moved to %v, want %v", got.CreatedAt, createdAt) + } + if !got.UpdatedAt.After(createdAt) && !got.UpdatedAt.Equal(createdAt) { + t.Errorf("UpdatedAt = %v, want >= CreatedAt", got.UpdatedAt) + } +} + +func TestUpdateAgentInstance_NormalisesEmptyJSONAndStatus(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + agent := fullAgentInstance("u-2", "ws-1", "Normalise") + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + + agent.Status = "" + agent.Settings = "" + agent.Permissions = " " + agent.SkillIDs = "" + agent.DesiredSkills = "" + agent.FailureThreshold = nil + if err := repo.UpdateAgentInstance(ctx, agent); err != nil { + t.Fatalf("UpdateAgentInstance: %v", err) + } + + got, err := repo.GetAgentInstance(ctx, "u-2") + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Status != settingsmodels.AgentStatus("idle") { + t.Errorf("Status = %q, want idle", got.Status) + } + if got.Settings != "{}" { + t.Errorf("Settings = %q, want {}", got.Settings) + } + if got.Permissions != "{}" { + t.Errorf("Permissions = %q, want {}", got.Permissions) + } + if got.SkillIDs != "[]" || got.DesiredSkills != "[]" { + t.Errorf("skill arrays = %q / %q, want [] / []", got.SkillIDs, got.DesiredSkills) + } + if got.FailureThreshold != nil { + t.Errorf("FailureThreshold = %d, want nil after clearing the override", *got.FailureThreshold) + } +} + +func TestUpdateAgentInstance_SkipsDeletedAndForeignRows(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + agent := fullAgentInstance("u-3", "ws-1", "Doomed") + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + if err := repo.DeleteAgentInstance(ctx, "u-3"); err != nil { + t.Fatalf("DeleteAgentInstance: %v", err) + } + + agent.Name = "Renamed after delete" + if err := repo.UpdateAgentInstance(ctx, agent); err != nil { + t.Fatalf("UpdateAgentInstance: %v", err) + } + var name string + if err := db.Get(&name, `SELECT name FROM agent_profiles WHERE id = 'u-3'`); err != nil { + t.Fatalf("read name: %v", err) + } + if name != "Doomed" { + t.Errorf("name = %q, want the soft-deleted row left untouched", name) + } +} + +func TestUpdateAgentSettings(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("s-1", "ws-1", "Settings")); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + + if err := repo.UpdateAgentSettings(ctx, "s-1", `{"routing":{"provider_order_source":"explicit"}}`); err != nil { + t.Fatalf("UpdateAgentSettings: %v", err) + } + got, err := repo.GetAgentInstance(ctx, "s-1") + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Settings != `{"routing":{"provider_order_source":"explicit"}}` { + t.Errorf("Settings = %q, want the written JSON", got.Settings) + } + // Other columns must be untouched. + if got.Name != "Settings" || got.Role != settingsmodels.AgentRole("cto") { + t.Errorf("UpdateAgentSettings changed unrelated fields: name=%q role=%q", got.Name, got.Role) + } + + if err := repo.UpdateAgentSettings(ctx, "s-1", ""); err != nil { + t.Fatalf("UpdateAgentSettings(empty): %v", err) + } + if got, err = repo.GetAgentInstance(ctx, "s-1"); err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Settings != "{}" { + t.Errorf("Settings = %q, want the empty string normalised to {}", got.Settings) + } +} + +func TestUpdateAgentStatusFields(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("st-1", "ws-1", "Status")); err != nil { + t.Fatalf("CreateAgentInstance: %v", err) + } + + if err := repo.UpdateAgentStatusFields(ctx, "st-1", "paused", "Auto-paused: 3 failures"); err != nil { + t.Fatalf("UpdateAgentStatusFields: %v", err) + } + got, err := repo.GetAgentInstance(ctx, "st-1") + if err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Status != settingsmodels.AgentStatus("paused") { + t.Errorf("Status = %q, want paused", got.Status) + } + if got.PauseReason != "Auto-paused: 3 failures" { + t.Errorf("PauseReason = %q, want the written reason", got.PauseReason) + } + + if err := repo.UpdateAgentStatusFields(ctx, "st-1", "idle", ""); err != nil { + t.Fatalf("UpdateAgentStatusFields(clear): %v", err) + } + if got, err = repo.GetAgentInstance(ctx, "st-1"); err != nil { + t.Fatalf("GetAgentInstance: %v", err) + } + if got.Status != settingsmodels.AgentStatus("idle") || got.PauseReason != "" { + t.Errorf("status/reason = %q/%q, want idle and empty", got.Status, got.PauseReason) + } + // Unrelated columns survive. + if got.Icon != "🤖" { + t.Errorf("Icon = %q, want it untouched", got.Icon) + } +} + +func TestCountAgentInstancesByRole(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + specs := []struct{ id, ws, name, role string }{ + {"c-1", "ws-1", "Eng One", "engineer"}, + {"c-2", "ws-1", "Eng Two", "engineer"}, + {"c-3", "ws-1", "The CTO", "cto"}, + {"c-4", "ws-2", "Eng Three", "engineer"}, + } + for _, s := range specs { + agent := fullAgentInstance(s.id, s.ws, s.name) + agent.Role = settingsmodels.AgentRole(s.role) + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("create %s: %v", s.id, err) + } + } + if err := repo.CreateAgentInstance(ctx, func() *models.AgentInstance { + a := fullAgentInstance("c-del", "ws-1", "Deleted Eng") + a.Role = settingsmodels.AgentRole("engineer") + return a + }()); err != nil { + t.Fatalf("create c-del: %v", err) + } + if err := repo.DeleteAgentInstance(ctx, "c-del"); err != nil { + t.Fatalf("delete c-del: %v", err) + } + + cases := []struct { + name string + workspace string + role string + exclude string + want int + }{ + {"workspace scoped", "ws-1", "engineer", "", 2}, + {"other role", "ws-1", "cto", "", 1}, + {"with exclusion", "ws-1", "engineer", "c-1", 1}, + {"all workspaces", "", "engineer", "", 3}, + {"unknown role", "ws-1", "designer", "", 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.CountAgentInstancesByRole(ctx, tc.workspace, tc.role, tc.exclude) + if err != nil { + t.Fatalf("CountAgentInstancesByRole: %v", err) + } + if got != tc.want { + t.Errorf("got %d, want %d", got, tc.want) + } + }) + } +} + +func TestAgentInstanceExistsByName(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("e-1", "ws-1", "Taken")); err != nil { + t.Fatalf("create e-1: %v", err) + } + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("e-2", "ws-2", "Elsewhere")); err != nil { + t.Fatalf("create e-2: %v", err) + } + + cases := []struct { + name string + workspace string + agentName string + exclude string + want bool + }{ + {"name taken in workspace", "ws-1", "Taken", "", true}, + {"excluding the holder frees the name", "ws-1", "Taken", "e-1", false}, + {"other workspace does not clash", "ws-1", "Elsewhere", "", false}, + {"any workspace when unscoped", "", "Elsewhere", "", true}, + {"unknown name", "ws-1", "Free", "", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.AgentInstanceExistsByName(ctx, tc.workspace, tc.agentName, tc.exclude) + if err != nil { + t.Fatalf("AgentInstanceExistsByName: %v", err) + } + if got != tc.want { + t.Errorf("got %v, want %v", got, tc.want) + } + }) + } + + // A soft-deleted agent frees its name. + if err := repo.DeleteAgentInstance(ctx, "e-1"); err != nil { + t.Fatalf("DeleteAgentInstance: %v", err) + } + exists, err := repo.AgentInstanceExistsByName(ctx, "ws-1", "Taken", "") + if err != nil { + t.Fatalf("AgentInstanceExistsByName after delete: %v", err) + } + if exists { + t.Error("soft-deleted agent still reserves its name") + } +} + +func TestDeleteAgentInstance_MissingRowIsNotAnError(t *testing.T) { + repo := newTestRepo(t) + + if err := repo.DeleteAgentInstance(context.Background(), "never-existed"); err != nil { + t.Fatalf("DeleteAgentInstance(missing) = %v, want nil", err) + } +} + +func TestListAgentInstancesFiltered(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + specs := []struct{ id, ws, name, role, status, reportsTo string }{ + {"f-1", "ws-1", "Eng One", "engineer", "idle", "f-boss"}, + {"f-2", "ws-1", "Eng Two", "engineer", "working", "f-boss"}, + {"f-3", "ws-1", "Designer", "designer", "idle", "f-other"}, + {"f-4", "ws-2", "Eng Three", "engineer", "idle", "f-boss"}, + } + for i, s := range specs { + agent := fullAgentInstance(s.id, s.ws, s.name) + agent.Role = settingsmodels.AgentRole(s.role) + agent.Status = settingsmodels.AgentStatus(s.status) + agent.ReportsTo = s.reportsTo + if err := repo.CreateAgentInstance(ctx, agent); err != nil { + t.Fatalf("create %s: %v", s.id, err) + } + stamp := time.Date(2026, 1, 1+i, 0, 0, 0, 0, time.UTC) + if _, err := db.Exec(`UPDATE agent_profiles SET created_at = ? WHERE id = ?`, stamp, s.id); err != nil { + t.Fatalf("stamp %s: %v", s.id, err) + } + } + + cases := []struct { + name string + workspace string + filter sqlite.AgentListFilter + wantIDs []string + }{ + {"no filters, workspace scoped", "ws-1", sqlite.AgentListFilter{}, []string{"f-1", "f-2", "f-3"}}, + {"role", "ws-1", sqlite.AgentListFilter{Role: "engineer"}, []string{"f-1", "f-2"}}, + {"status", "ws-1", sqlite.AgentListFilter{Status: "idle"}, []string{"f-1", "f-3"}}, + {"reports_to", "ws-1", sqlite.AgentListFilter{ReportsTo: "f-boss"}, []string{"f-1", "f-2"}}, + { + "combined", "ws-1", + sqlite.AgentListFilter{Role: "engineer", Status: "working", ReportsTo: "f-boss"}, + []string{"f-2"}, + }, + {"all workspaces", "", sqlite.AgentListFilter{Role: "engineer"}, []string{"f-1", "f-2", "f-4"}}, + {"no match", "ws-1", sqlite.AgentListFilter{Role: "nope"}, []string{}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.ListAgentInstancesFiltered(ctx, tc.workspace, tc.filter) + if err != nil { + t.Fatalf("ListAgentInstancesFiltered: %v", err) + } + if got == nil { + t.Fatal("returned nil slice, want empty non-nil") + } + ids := make([]string, 0, len(got)) + for _, a := range got { + ids = append(ids, a.ID) + } + if strings.Join(ids, ",") != strings.Join(tc.wantIDs, ",") { + t.Errorf("ids = %v, want %v (created_at ascending)", ids, tc.wantIDs) + } + }) + } +} + +func TestListAgentInstancesFiltered_ExcludesDeleted(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("d-1", "ws-1", "Alive")); err != nil { + t.Fatalf("create d-1: %v", err) + } + if err := repo.CreateAgentInstance(ctx, fullAgentInstance("d-2", "ws-1", "Gone")); err != nil { + t.Fatalf("create d-2: %v", err) + } + if err := repo.DeleteAgentInstance(ctx, "d-2"); err != nil { + t.Fatalf("DeleteAgentInstance: %v", err) + } + + got, err := repo.ListAgentInstancesFiltered(ctx, "ws-1", sqlite.AgentListFilter{}) + if err != nil { + t.Fatalf("ListAgentInstancesFiltered: %v", err) + } + if len(got) != 1 || got[0].ID != "d-1" { + t.Errorf("got %+v, want only d-1", got) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/dashboard_test.go b/apps/backend/internal/office/repository/sqlite/dashboard_test.go new file mode 100644 index 0000000000..fe16bc2939 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/dashboard_test.go @@ -0,0 +1,529 @@ +package sqlite_test + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// ensureSessionTables creates the task_sessions / task_session_messages +// stubs the dashboard aggregate queries read. Column types mirror the +// production schema in internal/task/repository/sqlite/base_schema.go so +// the driver's TIMESTAMP↔string conversion behaves the same way here. +func ensureSessionTables(t *testing.T, repo *sqlite.Repository) { + t.Helper() + stmts := []string{ + `CREATE TABLE IF NOT EXISTS task_sessions ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + agent_execution_id TEXT NOT NULL DEFAULT '', + agent_profile_id TEXT, + state TEXT NOT NULL DEFAULT 'CREATED', + started_at TIMESTAMP NOT NULL, + completed_at TIMESTAMP, + updated_at TIMESTAMP NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS task_session_messages ( + id TEXT PRIMARY KEY, + task_session_id TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'message', + created_at TIMESTAMP NOT NULL + )`, + } + for _, s := range stmts { + if _, err := repo.ExecRaw(context.Background(), s); err != nil { + t.Fatalf("create session test schema: %v", err) + } + } +} + +// dayStamp renders a SQLite-storable timestamp `offsetDays` before `base`, +// at the given hour. Returned in the format mattn/go-sqlite3 parses back +// into a UTC time.Time. +// +// The base time is passed in rather than read here so a test's seed rows and +// its assertions come from one clock read: these queries bucket by calendar +// day, so a UTC midnight crossing between seeding and asserting would +// otherwise name a different day and fail with no code defect. +func dayStamp(base time.Time, offsetDays, hour int) string { + d := base.AddDate(0, 0, -offsetDays) + return fmt.Sprintf("%s %02d:00:00", d.Format("2006-01-02"), hour) +} + +func dayDate(base time.Time, offsetDays int) string { + return base.AddDate(0, 0, -offsetDays).Format("2006-01-02") +} + +func TestQueryRunActivity_BucketsOutcomesPerDay(t *testing.T) { + repo := newSearchTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + base := time.Now().UTC() + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, is_ephemeral, origin, created_at, updated_at) VALUES + ('t-main', 'ws-1', 'main', 0, 'manual', datetime('now'), datetime('now')), + ('t-eph', 'ws-1', 'eph', 1, 'manual', datetime('now'), datetime('now')), + ('t-auto', 'ws-1', 'auto', 0, 'automation_run', datetime('now'), datetime('now')), + ('t-other', 'ws-2', 'other', 0, 'manual', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions (id, task_id, state, started_at, updated_at) VALUES + ('s-today-ok', 't-main', 'COMPLETED', ?, ?), + ('s-today-fail', 't-main', 'FAILED', ?, ?), + ('s-today-other', 't-main', 'RUNNING', ?, ?), + ('s-yday-ok', 't-main', 'COMPLETED', ?, ?), + ('s-old', 't-main', 'COMPLETED', ?, ?), + ('s-eph', 't-eph', 'COMPLETED', ?, ?), + ('s-auto', 't-auto', 'COMPLETED', ?, ?), + ('s-otherws', 't-other', 'COMPLETED', ?, ?) + `, + dayStamp(base, 0, 10), dayStamp(base, 0, 10), + dayStamp(base, 0, 11), dayStamp(base, 0, 11), + dayStamp(base, 0, 12), dayStamp(base, 0, 12), + dayStamp(base, 1, 9), dayStamp(base, 1, 9), + dayStamp(base, 60, 9), dayStamp(base, 60, 9), + dayStamp(base, 0, 13), dayStamp(base, 0, 13), + dayStamp(base, 0, 14), dayStamp(base, 0, 14), + dayStamp(base, 0, 15), dayStamp(base, 0, 15), + ); err != nil { + t.Fatalf("seed sessions: %v", err) + } + + rows, err := repo.QueryRunActivity(ctx, "ws-1", 7) + if err != nil { + t.Fatalf("QueryRunActivity: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (today + yesterday): %+v", len(rows), rows) + } + // ORDER BY date — oldest first. + if rows[0].Date != dayDate(base, 1) { + t.Errorf("rows[0].Date = %q, want yesterday %q (ascending order)", rows[0].Date, dayDate(base, 1)) + } + if rows[0] != (sqlite.RunActivityRow{Date: dayDate(base, 1), Succeeded: 1}) { + t.Errorf("yesterday = %+v, want 1 succeeded only", rows[0]) + } + want := sqlite.RunActivityRow{Date: dayDate(base, 0), Succeeded: 1, Failed: 1, Other: 1} + if rows[1] != want { + t.Errorf("today = %+v, want %+v", rows[1], want) + } +} + +func TestQueryRunActivity_EmptyWorkspace(t *testing.T) { + repo := newSearchTestRepo(t) + ensureSessionTables(t, repo) + + rows, err := repo.QueryRunActivity(context.Background(), "ws-nothing", 7) + if err != nil { + t.Fatalf("QueryRunActivity: %v", err) + } + if len(rows) != 0 { + t.Errorf("rows = %+v, want none", rows) + } +} + +func TestQueryTaskBreakdown_GroupsByStateAndFilters(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, state, title, is_ephemeral, origin, archived_at, created_at, updated_at) VALUES + ('b-todo1', 'ws-1', 'TODO', 'a', 0, 'manual', NULL, datetime('now'), datetime('now')), + ('b-todo2', 'ws-1', 'TODO', 'b', 0, 'manual', NULL, datetime('now'), datetime('now')), + ('b-done', 'ws-1', 'COMPLETED', 'c', 0, 'manual', NULL, datetime('now'), datetime('now')), + ('b-eph', 'ws-1', 'TODO', 'd', 1, 'manual', NULL, datetime('now'), datetime('now')), + ('b-auto', 'ws-1', 'TODO', 'e', 0, 'automation_run', NULL, datetime('now'), datetime('now')), + ('b-arch', 'ws-1', 'TODO', 'f', 0, 'manual', '2026-01-01 00:00:00', datetime('now'), datetime('now')), + ('b-other', 'ws-2', 'TODO', 'g', 0, 'manual', NULL, datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + rows, err := repo.QueryTaskBreakdown(ctx, "ws-1") + if err != nil { + t.Fatalf("QueryTaskBreakdown: %v", err) + } + counts := map[string]int{} + for _, row := range rows { + counts[row.State] = row.Count + } + if len(counts) != 2 { + t.Fatalf("state buckets = %+v, want TODO + COMPLETED only", counts) + } + if counts["TODO"] != 2 { + t.Errorf("TODO = %d, want 2 (ephemeral/automation/archived/other-workspace excluded)", counts["TODO"]) + } + if counts["COMPLETED"] != 1 { + t.Errorf("COMPLETED = %d, want 1", counts["COMPLETED"]) + } +} + +func TestQueryRecentTasks_OrdersByUpdatedAtDescAndLimits(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks + (id, workspace_id, workflow_step_id, identifier, title, state, is_ephemeral, origin, created_at, updated_at) + VALUES + ('r-old', 'ws-1', 'step-r', 'KAN-1', 'Oldest', 'TODO', 0, 'manual', '2026-01-01 00:00:00', '2026-01-01 00:00:00'), + ('r-mid', 'ws-1', 'step-r', 'KAN-2', 'Middle', 'BLOCKED', 0, 'manual', '2026-01-02 00:00:00', '2026-01-02 00:00:00'), + ('r-new', 'ws-1', 'step-r', 'KAN-3', 'Newest', 'COMPLETED', 0, 'manual', '2026-01-03 00:00:00', '2026-01-03 00:00:00'), + ('r-arc', 'ws-1', 'step-r', 'KAN-4', 'Archived', 'TODO', 0, 'manual', '2026-01-04 00:00:00', '2026-01-04 00:00:00') + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, + `UPDATE tasks SET archived_at = '2026-01-05 00:00:00' WHERE id = 'r-arc'`); err != nil { + t.Fatalf("archive task: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES ('p-new', 'step-r', 'r-new', 'runner', 'agent-runner', 0, 0) + `); err != nil { + t.Fatalf("seed runner: %v", err) + } + + rows, err := repo.QueryRecentTasks(ctx, "ws-1", 2) + if err != nil { + t.Fatalf("QueryRecentTasks: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (limit): %+v", len(rows), rows) + } + if rows[0].ID != "r-new" || rows[1].ID != "r-mid" { + t.Fatalf("order = %q,%q, want r-new,r-mid (updated_at DESC, archived excluded)", rows[0].ID, rows[1].ID) + } + if rows[0].Identifier != "KAN-3" { + t.Errorf("Identifier = %q, want KAN-3", rows[0].Identifier) + } + if rows[0].Title != "Newest" { + t.Errorf("Title = %q, want Newest", rows[0].Title) + } + if rows[0].State != "COMPLETED" { + t.Errorf("State = %q, want COMPLETED", rows[0].State) + } + if rows[0].AssigneeAgentProfileID != "agent-runner" { + t.Errorf("assignee = %q, want agent-runner from the runner projection", rows[0].AssigneeAgentProfileID) + } + if rows[0].UpdatedAt == "" { + t.Error("UpdatedAt is empty, want the persisted timestamp") + } + // The task with no runner row projects to the empty string, not NULL. + if rows[1].AssigneeAgentProfileID != "" { + t.Errorf("unassigned task assignee = %q, want empty", rows[1].AssigneeAgentProfileID) + } +} + +func TestQueryRecentSessions_ScopesByWorkspaceAndOrders(t *testing.T) { + repo := newSearchTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, is_ephemeral, origin, created_at, updated_at) VALUES + ('t-live', 'ws-1', 'live', 0, 'manual', datetime('now'), datetime('now')), + ('t-eph', 'ws-1', 'eph', 1, 'manual', datetime('now'), datetime('now')), + ('t-auto', 'ws-1', 'auto', 0, 'automation_run', datetime('now'), datetime('now')), + ('t-other', 'ws-2', 'other', 0, 'manual', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions + (id, task_id, agent_execution_id, state, started_at, completed_at, updated_at) + VALUES + ('s-1', 't-live', 'exec-1', 'COMPLETED', '2026-01-01 00:00:00', '2026-01-01 01:00:00', '2026-01-01 01:00:00'), + ('s-2', 't-live', '', 'RUNNING', '2026-01-02 00:00:00', NULL, '2026-01-02 00:00:00'), + ('s-3', 't-eph', 'exec-3', 'COMPLETED', '2026-01-03 00:00:00', NULL, '2026-01-03 00:00:00'), + ('s-4', 't-auto', 'exec-4', 'COMPLETED', '2026-01-04 00:00:00', NULL, '2026-01-04 00:00:00'), + ('s-5', 't-other', 'exec-5', 'COMPLETED', '2026-01-05 00:00:00', NULL, '2026-01-05 00:00:00') + `); err != nil { + t.Fatalf("seed sessions: %v", err) + } + + rows, err := repo.QueryRecentSessions(ctx, "ws-1", 10) + if err != nil { + t.Fatalf("QueryRecentSessions: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (ephemeral / automation / other workspace excluded): %+v", len(rows), rows) + } + if rows[0].ID != "s-2" || rows[1].ID != "s-1" { + t.Fatalf("order = %q,%q, want s-2,s-1 (started_at DESC)", rows[0].ID, rows[1].ID) + } + if rows[0].TaskID != "t-live" { + t.Errorf("TaskID = %q, want t-live", rows[0].TaskID) + } + if rows[0].AgentExecID != "" { + t.Errorf("AgentExecID = %q, want empty for the NULL-ish column", rows[0].AgentExecID) + } + if rows[0].State != "RUNNING" { + t.Errorf("State = %q, want RUNNING", rows[0].State) + } + if rows[0].StartedAt != "2026-01-02T00:00:00Z" { + t.Errorf("StartedAt = %q, want 2026-01-02T00:00:00Z", rows[0].StartedAt) + } + if rows[0].CompletedAt != nil { + t.Errorf("CompletedAt = %v, want nil for an in-flight session", *rows[0].CompletedAt) + } + if rows[1].AgentExecID != "exec-1" { + t.Errorf("AgentExecID = %q, want exec-1", rows[1].AgentExecID) + } + if rows[1].CompletedAt == nil || *rows[1].CompletedAt != "2026-01-01T01:00:00Z" { + t.Errorf("CompletedAt = %v, want 2026-01-01T01:00:00Z", rows[1].CompletedAt) + } +} + +func TestQueryRecentSessions_RespectsLimit(t *testing.T) { + repo := newSearchTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, created_at, updated_at) + VALUES ('t-lim', 'ws-1', 'lim', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + for i := 0; i < 5; i++ { + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions (id, task_id, state, started_at, updated_at) + VALUES (?, 't-lim', 'COMPLETED', ?, ?) + `, fmt.Sprintf("s-%d", i), + fmt.Sprintf("2026-01-0%d 00:00:00", i+1), + fmt.Sprintf("2026-01-0%d 00:00:00", i+1)); err != nil { + t.Fatalf("seed session %d: %v", i, err) + } + } + + rows, err := repo.QueryRecentSessions(ctx, "ws-1", 3) + if err != nil { + t.Fatalf("QueryRecentSessions: %v", err) + } + if len(rows) != 3 { + t.Fatalf("rows = %d, want 3", len(rows)) + } + if rows[0].ID != "s-4" { + t.Errorf("newest = %q, want s-4", rows[0].ID) + } +} + +func TestGetTasksByIDs(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, identifier, created_at, updated_at) VALUES + ('g-1', 'ws-1', 'First', 'KAN-1', datetime('now'), datetime('now')), + ('g-2', 'ws-1', 'Second', 'KAN-2', datetime('now'), datetime('now')), + ('g-3', 'ws-2', 'Third', '', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + rows, err := repo.GetTasksByIDs(ctx, []string{"g-1", "g-3", "missing"}) + if err != nil { + t.Fatalf("GetTasksByIDs: %v", err) + } + if len(rows) != 2 { + t.Fatalf("rows = %d, want 2 (missing id silently omitted): %+v", len(rows), rows) + } + byID := map[string]sqlite.TaskTitleRow{} + for _, row := range rows { + byID[row.ID] = row + } + if byID["g-1"].Title != "First" || byID["g-1"].Identifier != "KAN-1" { + t.Errorf("g-1 = %+v, want title First / identifier KAN-1", byID["g-1"]) + } + // Workspace is not part of the filter — the enrichment lookup is by id only. + if byID["g-3"].Title != "Third" || byID["g-3"].Identifier != "" { + t.Errorf("g-3 = %+v, want title Third / empty identifier", byID["g-3"]) + } +} + +func TestGetTasksByIDs_EmptyInput(t *testing.T) { + repo := newSearchTestRepo(t) + + rows, err := repo.GetTasksByIDs(context.Background(), nil) + if err != nil { + t.Fatalf("GetTasksByIDs(nil): %v", err) + } + if len(rows) != 0 { + t.Errorf("rows = %+v, want none", rows) + } +} + +func TestListRecentSessionsByAgentBatch_PartitionsPerAgent(t *testing.T) { + repo := newTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + // agent-a has 3 sessions, agent-b has 1, agent-c has none. + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions + (id, task_id, agent_profile_id, state, started_at, completed_at, updated_at) + VALUES + ('a-1', 't-1', 'agent-a', 'COMPLETED', '2026-01-01 00:00:00', '2026-01-01 02:00:00', '2026-01-01 02:00:00'), + ('a-2', 't-1', 'agent-a', 'FAILED', '2026-01-02 00:00:00', NULL, '2026-01-02 03:00:00'), + ('a-3', 't-2', 'agent-a', 'IDLE', '2026-01-03 00:00:00', NULL, '2026-01-03 04:00:00'), + ('b-1', 't-3', 'agent-b', 'COMPLETED', '2026-01-04 00:00:00', NULL, '2026-01-04 05:00:00'), + ('z-1', 't-4', 'agent-z', 'COMPLETED', '2026-01-05 00:00:00', NULL, '2026-01-05 06:00:00') + `); err != nil { + t.Fatalf("seed sessions: %v", err) + } + + out, err := repo.ListRecentSessionsByAgentBatch(ctx, []string{"agent-a", "agent-b", "agent-c"}, 2) + if err != nil { + t.Fatalf("ListRecentSessionsByAgentBatch: %v", err) + } + if len(out) != 2 { + t.Fatalf("map keys = %d, want 2 (agent-c has no rows, agent-z not requested): %+v", len(out), out) + } + if _, ok := out["agent-z"]; ok { + t.Error("agent-z leaked into the result despite not being requested") + } + a := out["agent-a"] + if len(a) != 2 { + t.Fatalf("agent-a rows = %d, want 2 (perAgentLimit)", len(a)) + } + if a[0].ID != "a-3" || a[1].ID != "a-2" { + t.Fatalf("agent-a order = %q,%q, want a-3,a-2 (started_at DESC)", a[0].ID, a[1].ID) + } + if a[0].TaskID != "t-2" { + t.Errorf("TaskID = %q, want t-2", a[0].TaskID) + } + if a[0].AgentProfileID != "agent-a" { + t.Errorf("AgentProfileID = %q, want agent-a", a[0].AgentProfileID) + } + if a[0].State != "IDLE" { + t.Errorf("State = %q, want IDLE", a[0].State) + } + if a[0].StartedAt != "2026-01-03T00:00:00Z" { + t.Errorf("StartedAt = %q, want 2026-01-03T00:00:00Z", a[0].StartedAt) + } + if a[0].UpdatedAt != "2026-01-03T04:00:00Z" { + t.Errorf("UpdatedAt = %q, want 2026-01-03T04:00:00Z — office IDLE sessions rely on it", a[0].UpdatedAt) + } + if a[0].CompletedAt != nil { + t.Errorf("CompletedAt = %v, want nil", *a[0].CompletedAt) + } + if a[1].CompletedAt != nil { + t.Errorf("a-2 CompletedAt = %v, want nil", *a[1].CompletedAt) + } + if b := out["agent-b"]; len(b) != 1 || b[0].ID != "b-1" { + t.Errorf("agent-b = %+v, want just b-1", b) + } +} + +func TestListRecentSessionsByAgentBatch_DefaultsAndEmptyInput(t *testing.T) { + repo := newTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + out, err := repo.ListRecentSessionsByAgentBatch(ctx, nil, 5) + if err != nil { + t.Fatalf("empty input: %v", err) + } + if out == nil { + t.Fatal("returned nil map, want empty non-nil") + } + if len(out) != 0 { + t.Errorf("len = %d, want 0", len(out)) + } + + // A non-positive per-agent limit falls back to 5. + for i := 0; i < 7; i++ { + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions (id, task_id, agent_profile_id, state, started_at, updated_at) + VALUES (?, 't-1', 'agent-d', 'COMPLETED', ?, ?) + `, fmt.Sprintf("d-%d", i), + fmt.Sprintf("2026-01-%02d 00:00:00", i+1), + fmt.Sprintf("2026-01-%02d 00:00:00", i+1)); err != nil { + t.Fatalf("seed session %d: %v", i, err) + } + } + out, err = repo.ListRecentSessionsByAgentBatch(ctx, []string{"agent-d"}, 0) + if err != nil { + t.Fatalf("zero limit: %v", err) + } + if len(out["agent-d"]) != 5 { + t.Errorf("agent-d rows = %d, want the default 5", len(out["agent-d"])) + } +} + +func TestCountToolCallMessagesBySession(t *testing.T) { + repo := newTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_session_messages (id, task_session_id, type, created_at) VALUES + ('m-1', 's-1', 'tool_call', datetime('now')), + ('m-2', 's-1', 'tool_call', datetime('now')), + ('m-3', 's-1', 'message', datetime('now')), + ('m-4', 's-2', 'message', datetime('now')), + ('m-5', 's-3', 'tool_call', datetime('now')) + `); err != nil { + t.Fatalf("seed messages: %v", err) + } + + got, err := repo.CountToolCallMessagesBySession(ctx, []string{"s-1", "s-2", "s-missing"}) + if err != nil { + t.Fatalf("CountToolCallMessagesBySession: %v", err) + } + if len(got) != 1 { + t.Fatalf("map = %+v, want only s-1 (zero-tool-call sessions omitted)", got) + } + if got["s-1"] != 2 { + t.Errorf("s-1 = %d, want 2", got["s-1"]) + } + if _, ok := got["s-3"]; ok { + t.Error("s-3 leaked in despite not being requested") + } +} + +func TestCountToolCallMessagesBySession_EmptyInput(t *testing.T) { + repo := newTestRepo(t) + ensureSessionTables(t, repo) + + got, err := repo.CountToolCallMessagesBySession(context.Background(), nil) + if err != nil { + t.Fatalf("CountToolCallMessagesBySession(nil): %v", err) + } + if got == nil { + t.Fatal("returned nil map, want empty non-nil") + } + if len(got) != 0 { + t.Errorf("len = %d, want 0", len(got)) + } +} + +func TestBucketTaskBreakdown(t *testing.T) { + got := sqlite.BucketTaskBreakdown([]sqlite.TaskBreakdownRow{ + {State: "COMPLETED", Count: 3}, + {State: "IN_PROGRESS", Count: 2}, + {State: "SCHEDULING", Count: 1}, + {State: "BLOCKED", Count: 4}, + {State: "TODO", Count: 5}, + {State: "", Count: 6}, + {State: "REVIEW", Count: 7}, + }) + want := models.TaskBreakdown{Done: 3, InProgress: 3, Blocked: 4, Open: 18} + if got != want { + t.Errorf("BucketTaskBreakdown = %+v, want %+v", got, want) + } +} + +func TestBucketTaskBreakdown_EmptyInput(t *testing.T) { + if got := sqlite.BucketTaskBreakdown(nil); got != (models.TaskBreakdown{}) { + t.Errorf("BucketTaskBreakdown(nil) = %+v, want zero value", got) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/failure_test.go b/apps/backend/internal/office/repository/sqlite/failure_test.go new file mode 100644 index 0000000000..59aa41afd3 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/failure_test.go @@ -0,0 +1,617 @@ +package sqlite_test + +import ( + "context" + "database/sql" + "errors" + "testing" + "time" + + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// seedFailureAgent inserts an agent_profiles row with the failure-handling +// columns set explicitly, so the inbox queries have something to join to. +func seedFailureAgent( + t *testing.T, db *sqlx.DB, + id, workspaceID, name, pauseReason string, consecutiveFailures, threshold int, deleted bool, +) { + t.Helper() + now := time.Now().UTC() + var deletedAt interface{} + if deleted { + deletedAt = now + } + if _, err := db.Exec(`INSERT INTO agent_profiles + (id, agent_id, name, agent_display_name, workspace_id, role, + pause_reason, consecutive_failures, failure_threshold, deleted_at, + created_at, updated_at) + VALUES (?, 'agent', ?, ?, ?, '', ?, ?, ?, ?, ?, ?)`, + id, name, name, workspaceID, pauseReason, consecutiveFailures, threshold, + deletedAt, now, now); err != nil { + t.Fatalf("seed agent_profile %s: %v", id, err) + } +} + +func TestIncrementAndResetAgentConsecutiveFailures(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "agent-a", "ws-1", "A", "", 0, 0, false) + seedFailureAgent(t, db, "agent-b", "ws-1", "B", "", 0, 0, false) + + for want := 1; want <= 3; want++ { + got, err := repo.IncrementAgentConsecutiveFailures(ctx, "agent-a") + if err != nil { + t.Fatalf("increment #%d: %v", want, err) + } + if got != want { + t.Fatalf("increment #%d returned %d, want the post-increment value %d", want, got, want) + } + } + + // The other agent's counter must not move. + other, err := repo.GetEffectiveFailureThreshold(ctx, "agent-b") + if err != nil { + t.Fatalf("threshold for agent-b: %v", err) + } + if other != sqlite.DefaultAgentFailureThreshold { + t.Errorf("agent-b threshold = %d, want default", other) + } + var bFailures int + if err := db.Get(&bFailures, + `SELECT consecutive_failures FROM agent_profiles WHERE id = 'agent-b'`); err != nil { + t.Fatalf("read agent-b failures: %v", err) + } + if bFailures != 0 { + t.Errorf("agent-b consecutive_failures = %d, want 0", bFailures) + } + + if err := repo.ResetAgentConsecutiveFailures(ctx, "agent-a"); err != nil { + t.Fatalf("reset: %v", err) + } + var aFailures int + if err := db.Get(&aFailures, + `SELECT consecutive_failures FROM agent_profiles WHERE id = 'agent-a'`); err != nil { + t.Fatalf("read agent-a failures: %v", err) + } + if aFailures != 0 { + t.Errorf("consecutive_failures after reset = %d, want 0", aFailures) + } + + // A reset then increment starts the count over from 1. + n, err := repo.IncrementAgentConsecutiveFailures(ctx, "agent-a") + if err != nil { + t.Fatalf("increment after reset: %v", err) + } + if n != 1 { + t.Errorf("increment after reset = %d, want 1", n) + } +} + +func TestIncrementAgentConsecutiveFailures_MissingAgent(t *testing.T) { + repo, _ := newTestRepoWithDB(t) + + // The UPDATE matches nothing, so the follow-up SELECT has no row. + _, err := repo.IncrementAgentConsecutiveFailures(context.Background(), "ghost") + if err == nil { + t.Fatal("increment on a missing agent = nil error, want sql.ErrNoRows") + } + if !errors.Is(err, sql.ErrNoRows) { + t.Errorf("error = %v, want sql.ErrNoRows", err) + } +} + +func TestGetEffectiveFailureThreshold_PrecedenceChain(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "agent-override", "ws-1", "Override", "", 0, 9, false) + seedFailureAgent(t, db, "agent-inherit", "ws-1", "Inherit", "", 0, 0, false) + seedFailureAgent(t, db, "agent-no-ws", "", "NoWorkspace", "", 0, 0, false) + + // No workspace row yet → the global default. + got, err := repo.GetEffectiveFailureThreshold(ctx, "agent-inherit") + if err != nil { + t.Fatalf("threshold (no workspace row): %v", err) + } + if got != sqlite.DefaultAgentFailureThreshold { + t.Errorf("got %d, want the global default %d", got, sqlite.DefaultAgentFailureThreshold) + } + + if err := repo.SetWorkspaceAgentFailureThreshold(ctx, "ws-1", 5); err != nil { + t.Fatalf("set workspace threshold: %v", err) + } + + // Workspace override now applies to the agent with no per-agent value. + got, err = repo.GetEffectiveFailureThreshold(ctx, "agent-inherit") + if err != nil { + t.Fatalf("threshold (workspace override): %v", err) + } + if got != 5 { + t.Errorf("got %d, want the workspace override 5", got) + } + + // The per-agent override wins over the workspace value. + got, err = repo.GetEffectiveFailureThreshold(ctx, "agent-override") + if err != nil { + t.Fatalf("threshold (agent override): %v", err) + } + if got != 9 { + t.Errorf("got %d, want the per-agent override 9", got) + } + + // A workspace-less agent falls through to the '' workspace, which has + // no settings row, so the global default applies. + got, err = repo.GetEffectiveFailureThreshold(ctx, "agent-no-ws") + if err != nil { + t.Fatalf("threshold (no workspace): %v", err) + } + if got != sqlite.DefaultAgentFailureThreshold { + t.Errorf("got %d, want the global default", got) + } + + if _, err := repo.GetEffectiveFailureThreshold(ctx, "ghost"); err == nil { + t.Error("threshold for a missing agent = nil error, want sql.ErrNoRows") + } else if !errors.Is(err, sql.ErrNoRows) { + t.Errorf("error = %v, want sql.ErrNoRows", err) + } +} + +func TestWorkspaceAgentFailureThreshold_UpsertAndClamp(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + got, err := repo.GetWorkspaceAgentFailureThreshold(ctx, "ws-none") + if err != nil { + t.Fatalf("get (missing row): %v", err) + } + if got != sqlite.DefaultAgentFailureThreshold { + t.Errorf("missing row = %d, want the default", got) + } + + if err := repo.SetWorkspaceAgentFailureThreshold(ctx, "ws-1", 7); err != nil { + t.Fatalf("set 7: %v", err) + } + if got, err = repo.GetWorkspaceAgentFailureThreshold(ctx, "ws-1"); err != nil || got != 7 { + t.Fatalf("get after set = %d, %v; want 7, nil", got, err) + } + + // Second write on the same workspace updates in place (ON CONFLICT). + if err := repo.SetWorkspaceAgentFailureThreshold(ctx, "ws-1", 11); err != nil { + t.Fatalf("set 11: %v", err) + } + if got, err = repo.GetWorkspaceAgentFailureThreshold(ctx, "ws-1"); err != nil || got != 11 { + t.Fatalf("get after upsert = %d, %v; want 11, nil", got, err) + } + var rowCount int + if err := repo.ReaderDB().Get(&rowCount, + `SELECT COUNT(*) FROM office_workspace_settings WHERE workspace_id = 'ws-1'`); err != nil { + t.Fatalf("count settings rows: %v", err) + } + if rowCount != 1 { + t.Errorf("settings rows = %d, want 1 (upsert, not insert)", rowCount) + } + + // A non-positive threshold is normalised to the default on write… + if err := repo.SetWorkspaceAgentFailureThreshold(ctx, "ws-1", 0); err != nil { + t.Fatalf("set 0: %v", err) + } + if got, err = repo.GetWorkspaceAgentFailureThreshold(ctx, "ws-1"); err != nil || + got != sqlite.DefaultAgentFailureThreshold { + t.Fatalf("get after set 0 = %d, %v; want the default", got, err) + } + + // …and a non-positive value already in the column is normalised on read. + if _, err := repo.ExecRaw(ctx, + `UPDATE office_workspace_settings SET agent_failure_threshold = -4 WHERE workspace_id = 'ws-1'`, + ); err != nil { + t.Fatalf("force negative threshold: %v", err) + } + if got, err = repo.GetWorkspaceAgentFailureThreshold(ctx, "ws-1"); err != nil || + got != sqlite.DefaultAgentFailureThreshold { + t.Fatalf("get with negative column = %d, %v; want the default", got, err) + } +} + +func TestMarkRunFailed_StampsMessageAndPreservesFinishedAt(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedSummaryRun(t, repo, "mr-open", "agent-a", "claimed", "2026-01-01 09:00:00", "2026-01-01 10:00:00", "", "{}") + seedSummaryRun(t, repo, "mr-done", "agent-a", "finished", + "2026-01-02 09:00:00", "2026-01-02 10:00:00", "2026-01-02 11:00:00", "{}") + seedSummaryRun(t, repo, "mr-other", "agent-a", "queued", "2026-01-03 09:00:00", "", "", "{}") + + if err := repo.MarkRunFailed(ctx, "mr-open", "provider exploded"); err != nil { + t.Fatalf("MarkRunFailed: %v", err) + } + run, err := repo.GetRun(ctx, "mr-open") + if err != nil { + t.Fatalf("GetRun: %v", err) + } + if run.Status != "failed" { + t.Errorf("Status = %q, want failed", run.Status) + } + if run.ErrorMessage != "provider exploded" { + t.Errorf("ErrorMessage = %q, want the verbatim message", run.ErrorMessage) + } + if run.FinishedAt == nil { + t.Error("FinishedAt is nil, want it stamped") + } + + // Re-marking is idempotent and must not move an existing finished_at. + if err := repo.MarkRunFailed(ctx, "mr-done", "later failure"); err != nil { + t.Fatalf("MarkRunFailed (already finished): %v", err) + } + run, err = repo.GetRun(ctx, "mr-done") + if err != nil { + t.Fatalf("GetRun: %v", err) + } + if run.FinishedAt == nil || run.FinishedAt.Format("2006-01-02 15:04:05") != "2026-01-02 11:00:00" { + t.Errorf("FinishedAt = %v, want the original 2026-01-02 11:00:00", run.FinishedAt) + } + if run.ErrorMessage != "later failure" { + t.Errorf("ErrorMessage = %q, want it overwritten", run.ErrorMessage) + } + + // An untouched run keeps its status. + if run, err = repo.GetRun(ctx, "mr-other"); err != nil { + t.Fatalf("GetRun(mr-other): %v", err) + } + if run.Status != "queued" { + t.Errorf("mr-other status = %q, want queued", run.Status) + } + + // Marking a missing run is a silent no-op, not an error. + if err := repo.MarkRunFailed(ctx, "no-such-run", "x"); err != nil { + t.Errorf("MarkRunFailed(missing) = %v, want nil", err) + } +} + +func TestInboxDismissals_UpsertQueryAndList(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + dismissed, err := repo.IsInboxItemDismissed(ctx, "user-1", "agent_run_failed", "run-1") + if err != nil { + t.Fatalf("IsInboxItemDismissed: %v", err) + } + if dismissed { + t.Fatal("item reported dismissed before any dismissal was recorded") + } + + if err := repo.DismissInboxItem(ctx, "user-1", "agent_run_failed", "run-1"); err != nil { + t.Fatalf("DismissInboxItem: %v", err) + } + if dismissed, err = repo.IsInboxItemDismissed(ctx, "user-1", "agent_run_failed", "run-1"); err != nil || + !dismissed { + t.Fatalf("IsInboxItemDismissed = %v, %v; want true, nil", dismissed, err) + } + + // Each part of the natural key is significant. + for _, tc := range []struct{ user, kind, item string }{ + {"user-2", "agent_run_failed", "run-1"}, + {"user-1", "agent_paused_after_failures", "run-1"}, + {"user-1", "agent_run_failed", "run-2"}, + } { + got, err := repo.IsInboxItemDismissed(ctx, tc.user, tc.kind, tc.item) + if err != nil { + t.Fatalf("IsInboxItemDismissed(%v): %v", tc, err) + } + if got { + t.Errorf("IsInboxItemDismissed(%s, %s, %s) = true, want false", tc.user, tc.kind, tc.item) + } + } + + // Second dismiss of the same triple is accepted and stays one row. + if err := repo.DismissInboxItem(ctx, "user-1", "agent_run_failed", "run-1"); err != nil { + t.Fatalf("second DismissInboxItem: %v", err) + } + var count int + if err := repo.ReaderDB().Get(&count, `SELECT COUNT(*) FROM office_inbox_dismissals`); err != nil { + t.Fatalf("count dismissals: %v", err) + } + if count != 1 { + t.Errorf("dismissal rows = %d, want 1 (idempotent upsert)", count) + } + + if err := repo.DismissInboxItem(ctx, "user-1", "agent_run_failed", "run-3"); err != nil { + t.Fatalf("DismissInboxItem run-3: %v", err) + } + if err := repo.DismissInboxItem(ctx, "user-1", "agent_paused_after_failures", "agent-x"); err != nil { + t.Fatalf("DismissInboxItem paused: %v", err) + } + if err := repo.DismissInboxItem(ctx, "user-2", "agent_run_failed", "run-9"); err != nil { + t.Fatalf("DismissInboxItem other user: %v", err) + } + + ids, err := repo.ListDismissedInboxItemIDs(ctx, "user-1", "agent_run_failed") + if err != nil { + t.Fatalf("ListDismissedInboxItemIDs: %v", err) + } + got := map[string]bool{} + for _, id := range ids { + got[id] = true + } + if len(ids) != 2 || !got["run-1"] || !got["run-3"] { + t.Errorf("ids = %v, want exactly run-1 and run-3 (kind- and user-scoped)", ids) + } + + empty, err := repo.ListDismissedInboxItemIDs(ctx, "user-1", "no_such_kind") + if err != nil { + t.Fatalf("ListDismissedInboxItemIDs(unknown kind): %v", err) + } + if len(empty) != 0 { + t.Errorf("ids = %v, want none", empty) + } +} + +func TestListFailedRunsForInbox(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "agent-live", "ws-1", "Live Agent", "", 2, 0, false) + seedFailureAgent(t, db, "agent-paused", "ws-1", "Paused Agent", "Auto-paused: too many failures", 3, 0, false) + seedFailureAgent(t, db, "agent-manual", "ws-1", "Manual Pause", "user paused me", 0, 0, false) + seedFailureAgent(t, db, "agent-elsewhere", "ws-2", "Other WS", "", 0, 0, false) + + seedSummaryRun(t, repo, "f-old", "agent-live", "failed", + "2026-01-01 09:00:00", "", "2026-01-01 10:00:00", `{"task_id":"t-1"}`) + seedSummaryRun(t, repo, "f-new", "agent-live", "failed", + "2026-01-02 09:00:00", "", "2026-01-02 10:00:00", `{"task_id":"t-2"}`) + // No payload task_id → COALESCE to "". + seedSummaryRun(t, repo, "f-notask", "agent-manual", "failed", + "2026-01-03 09:00:00", "", "2026-01-03 10:00:00", `{}`) + // Excluded: not failed / auto-paused agent / other workspace. + seedSummaryRun(t, repo, "f-ok", "agent-live", "finished", + "2026-01-04 09:00:00", "", "2026-01-04 10:00:00", `{}`) + seedSummaryRun(t, repo, "f-autopaused", "agent-paused", "failed", + "2026-01-05 09:00:00", "", "2026-01-05 10:00:00", `{}`) + seedSummaryRun(t, repo, "f-otherws", "agent-elsewhere", "failed", + "2026-01-06 09:00:00", "", "2026-01-06 10:00:00", `{}`) + if _, err := repo.ExecRaw(ctx, + `UPDATE runs SET error_message = 'kaboom' WHERE id = 'f-new'`); err != nil { + t.Fatalf("set error message: %v", err) + } + + rows, err := repo.ListFailedRunsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListFailedRunsForInbox: %v", err) + } + ids := make([]string, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row.RunID) + } + if len(rows) != 3 { + t.Fatalf("rows = %v, want f-notask, f-new, f-old", ids) + } + // ORDER BY failed_at DESC. + if ids[0] != "f-notask" || ids[1] != "f-new" || ids[2] != "f-old" { + t.Fatalf("order = %v, want f-notask, f-new, f-old", ids) + } + newest := rows[1] + if newest.AgentProfileID != "agent-live" { + t.Errorf("AgentProfileID = %q, want agent-live", newest.AgentProfileID) + } + if newest.AgentName != "Live Agent" { + t.Errorf("AgentName = %q, want 'Live Agent' from the join", newest.AgentName) + } + if newest.WorkspaceID != "ws-1" { + t.Errorf("WorkspaceID = %q, want ws-1", newest.WorkspaceID) + } + if newest.TaskID != "t-2" { + t.Errorf("TaskID = %q, want t-2 extracted from the payload", newest.TaskID) + } + if newest.ErrorMessage != "kaboom" { + t.Errorf("ErrorMessage = %q, want kaboom", newest.ErrorMessage) + } + if newest.FailedAtRaw != "2026-01-02 10:00:00" { + t.Errorf("FailedAtRaw = %q, want the stored finished_at", newest.FailedAtRaw) + } + if newest.FailedAt.Format(time.RFC3339) != "2026-01-02T10:00:00Z" { + t.Errorf("FailedAt = %v, want the parsed 2026-01-02T10:00:00Z", newest.FailedAt) + } + if rows[0].TaskID != "" { + t.Errorf("payload without task_id → TaskID = %q, want empty", rows[0].TaskID) + } + + // A user dismissal hides the row for that user only. + if err := repo.DismissInboxItem(ctx, "user-1", "agent_run_failed", "f-new"); err != nil { + t.Fatalf("dismiss f-new: %v", err) + } + rows, err = repo.ListFailedRunsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListFailedRunsForInbox after dismiss: %v", err) + } + for _, row := range rows { + if row.RunID == "f-new" { + t.Fatal("dismissed run still returned for the dismissing user") + } + } + rows, err = repo.ListFailedRunsForInbox(ctx, "ws-1", "user-2") + if err != nil { + t.Fatalf("ListFailedRunsForInbox other user: %v", err) + } + if len(rows) != 3 { + t.Errorf("other user rows = %d, want 3 — a dismissal is per-user", len(rows)) + } + + // The '_auto' sentinel hides the row from everyone. + if err := repo.DismissInboxItem(ctx, "_auto", "agent_run_failed", "f-old"); err != nil { + t.Fatalf("auto-dismiss f-old: %v", err) + } + rows, err = repo.ListFailedRunsForInbox(ctx, "ws-1", "user-2") + if err != nil { + t.Fatalf("ListFailedRunsForInbox after auto-dismiss: %v", err) + } + for _, row := range rows { + if row.RunID == "f-old" { + t.Fatal("_auto dismissal did not hide the run from other users") + } + } +} + +func TestListFailedRunsForInbox_FallsBackToRequestedAt(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "agent-live", "ws-1", "Live", "", 0, 0, false) + seedSummaryRun(t, repo, "f-nofinish", "agent-live", "failed", "2026-03-04 05:06:07", "", "", "{}") + + rows, err := repo.ListFailedRunsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListFailedRunsForInbox: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1", len(rows)) + } + if rows[0].FailedAtRaw != "2026-03-04 05:06:07" { + t.Errorf("FailedAtRaw = %q, want the requested_at fallback", rows[0].FailedAtRaw) + } + if rows[0].FailedAt.Format(time.RFC3339) != "2026-03-04T05:06:07Z" { + t.Errorf("FailedAt = %v, want the parsed fallback", rows[0].FailedAt) + } +} + +// An unparseable timestamp must degrade to the zero time rather than +// failing the whole inbox query. +func TestListFailedRunsForInbox_UnparseableTimestampIsZeroTime(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "agent-live", "ws-1", "Live", "", 0, 0, false) + seedSummaryRun(t, repo, "f-bad", "agent-live", "failed", "2026-01-01 09:00:00", "", "", "{}") + if _, err := repo.ExecRaw(ctx, + `UPDATE runs SET finished_at = 'not-a-timestamp' WHERE id = 'f-bad'`); err != nil { + t.Fatalf("corrupt finished_at: %v", err) + } + + rows, err := repo.ListFailedRunsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListFailedRunsForInbox: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1", len(rows)) + } + if rows[0].FailedAtRaw != "not-a-timestamp" { + t.Errorf("FailedAtRaw = %q, want the raw value preserved", rows[0].FailedAtRaw) + } + if !rows[0].FailedAt.IsZero() { + t.Errorf("FailedAt = %v, want the zero time", rows[0].FailedAt) + } +} + +func TestListAutoPausedAgentsForInbox(t *testing.T) { + repo, db := newTestRepoWithDB(t) + ctx := context.Background() + + seedFailureAgent(t, db, "ap-1", "ws-1", "Auto One", "Auto-paused: 3 consecutive failures", 3, 0, false) + seedFailureAgent(t, db, "ap-2", "ws-1", "Auto Two", "Auto-paused: provider down", 5, 0, false) + seedFailureAgent(t, db, "manual", "ws-1", "Manual", "user paused", 1, 0, false) + seedFailureAgent(t, db, "healthy", "ws-1", "Healthy", "", 0, 0, false) + seedFailureAgent(t, db, "deleted", "ws-1", "Deleted", "Auto-paused: gone", 9, 0, true) + seedFailureAgent(t, db, "otherws", "ws-2", "Other", "Auto-paused: elsewhere", 4, 0, false) + seedFailureAgent(t, db, "nows", "", "No Workspace", "Auto-paused: unscoped", 4, 0, false) + + // Deterministic ordering: updated_at DESC. + if _, err := repo.ExecRaw(ctx, + `UPDATE agent_profiles SET updated_at = '2026-01-01 10:00:00' WHERE id = 'ap-1'`); err != nil { + t.Fatalf("stamp ap-1: %v", err) + } + if _, err := repo.ExecRaw(ctx, + `UPDATE agent_profiles SET updated_at = '2026-01-02 10:00:00' WHERE id = 'ap-2'`); err != nil { + t.Fatalf("stamp ap-2: %v", err) + } + + rows, err := repo.ListAutoPausedAgentsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListAutoPausedAgentsForInbox: %v", err) + } + if len(rows) != 2 { + ids := make([]string, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row.AgentID) + } + t.Fatalf("rows = %v, want ap-2 and ap-1 only", ids) + } + if rows[0].AgentID != "ap-2" || rows[1].AgentID != "ap-1" { + t.Fatalf("order = %q,%q, want ap-2,ap-1 (updated_at DESC)", rows[0].AgentID, rows[1].AgentID) + } + if rows[0].AgentName != "Auto Two" { + t.Errorf("AgentName = %q, want 'Auto Two'", rows[0].AgentName) + } + if rows[0].WorkspaceID != "ws-1" { + t.Errorf("WorkspaceID = %q, want ws-1", rows[0].WorkspaceID) + } + if rows[0].PauseReason != "Auto-paused: provider down" { + t.Errorf("PauseReason = %q, want the stored reason", rows[0].PauseReason) + } + if rows[0].ConsecutiveFailures != 5 { + t.Errorf("ConsecutiveFailures = %d, want 5", rows[0].ConsecutiveFailures) + } + if rows[0].UpdatedAt.Format("2006-01-02 15:04:05") != "2026-01-02 10:00:00" { + t.Errorf("UpdatedAt = %v, want 2026-01-02 10:00:00", rows[0].UpdatedAt) + } + + if err := repo.DismissInboxItem(ctx, "_auto", "agent_paused_after_failures", "ap-2"); err != nil { + t.Fatalf("dismiss ap-2: %v", err) + } + rows, err = repo.ListAutoPausedAgentsForInbox(ctx, "ws-1", "user-1") + if err != nil { + t.Fatalf("ListAutoPausedAgentsForInbox after dismiss: %v", err) + } + if len(rows) != 1 || rows[0].AgentID != "ap-1" { + t.Errorf("rows = %+v, want only ap-1", rows) + } +} + +func TestListFailedRunsForAgent(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedSummaryRun(t, repo, "fa-1", "agent-a", "failed", + "2026-01-01 09:00:00", "", "2026-01-01 10:00:00", "{}") + seedSummaryRun(t, repo, "fa-2", "agent-a", "failed", + "2026-01-02 09:00:00", "", "2026-01-02 10:00:00", "{}") + seedSummaryRun(t, repo, "fa-ok", "agent-a", "finished", + "2026-01-03 09:00:00", "", "2026-01-03 10:00:00", "{}") + seedSummaryRun(t, repo, "fa-other", "agent-b", "failed", + "2026-01-04 09:00:00", "", "2026-01-04 10:00:00", "{}") + + ids, err := repo.ListFailedRunsForAgent(ctx, "agent-a") + if err != nil { + t.Fatalf("ListFailedRunsForAgent: %v", err) + } + if len(ids) != 2 { + t.Fatalf("ids = %v, want the two failed runs for agent-a", ids) + } + if ids[0] != "fa-2" || ids[1] != "fa-1" { + t.Errorf("order = %v, want fa-2,fa-1 (finished_at DESC)", ids) + } + + none, err := repo.ListFailedRunsForAgent(ctx, "agent-clean") + if err != nil { + t.Fatalf("ListFailedRunsForAgent(clean): %v", err) + } + if len(none) != 0 { + t.Errorf("ids = %v, want none", none) + } +} + +func TestGetRun_MissingRowReturnsNoRows(t *testing.T) { + repo := newTestRepo(t) + + got, err := repo.GetRun(context.Background(), "no-such-run") + if err == nil { + t.Fatal("GetRun(missing) = nil error, want sql.ErrNoRows") + } + if got != nil { + t.Errorf("got %+v, want nil", got) + } + if !errors.Is(err, sql.ErrNoRows) { + t.Errorf("error = %v, want sql.ErrNoRows", err) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/participants_ops_test.go b/apps/backend/internal/office/repository/sqlite/participants_ops_test.go new file mode 100644 index 0000000000..c4473485f1 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/participants_ops_test.go @@ -0,0 +1,306 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// seedParticipantTask inserts a task bound to the given workflow step. +func seedParticipantTask(t *testing.T, repo *sqlite.Repository, taskID, stepID string) { + t.Helper() + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO tasks (id, workspace_id, workflow_step_id, title, created_at, updated_at) + VALUES (?, 'ws-1', ?, 'Task', datetime('now'), datetime('now')) + `, taskID, stepID); err != nil { + t.Fatalf("seed task %s: %v", taskID, err) + } +} + +func TestGetTaskWorkflowStepID(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "wp-bound", "step-1") + seedParticipantTask(t, repo, "wp-unbound", "") + + cases := []struct { + name string + taskID string + want string + }{ + {"bound to a step", "wp-bound", "step-1"}, + {"empty step", "wp-unbound", ""}, + {"missing task", "wp-missing", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.GetTaskWorkflowStepID(ctx, tc.taskID) + if err != nil { + t.Fatalf("GetTaskWorkflowStepID: %v", err) + } + if got != tc.want { + t.Errorf("got %q, want %q", got, tc.want) + } + }) + } +} + +func TestAddTaskParticipant_IsIdempotentPerNaturalKey(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "ap-1", "step-1") + + if err := repo.AddTaskParticipant(ctx, "ap-1", "agent-r", "reviewer"); err != nil { + t.Fatalf("AddTaskParticipant: %v", err) + } + got, err := repo.ListTaskParticipants(ctx, "ap-1", "reviewer") + if err != nil { + t.Fatalf("ListTaskParticipants: %v", err) + } + if len(got) != 1 { + t.Fatalf("participants = %+v, want 1", got) + } + want := sqlite.Participant{TaskID: "ap-1", AgentProfileID: "agent-r", Role: "reviewer", DecisionRequired: true} + if got[0] != want { + t.Errorf("participant = %+v, want %+v", got[0], want) + } + + // A second identical call adds no row. + if err := repo.AddTaskParticipant(ctx, "ap-1", "agent-r", "reviewer"); err != nil { + t.Fatalf("AddTaskParticipant (repeat): %v", err) + } + if n := participantRowCount(t, repo, "ap-1"); n != 1 { + t.Errorf("rows = %d, want 1 (idempotent)", n) + } + + // A different role or agent is a distinct participant. + if err := repo.AddTaskParticipant(ctx, "ap-1", "agent-r", "approver"); err != nil { + t.Fatalf("AddTaskParticipant (other role): %v", err) + } + if err := repo.AddTaskParticipant(ctx, "ap-1", "agent-s", "reviewer"); err != nil { + t.Fatalf("AddTaskParticipant (other agent): %v", err) + } + if n := participantRowCount(t, repo, "ap-1"); n != 3 { + t.Errorf("rows = %d, want 3", n) + } +} + +// A task with no workflow step cannot own a participant row, so the write +// is silently skipped rather than erroring. +func TestAddTaskParticipant_SkipsTasksWithoutAStep(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "ap-nostep", "") + + if err := repo.AddTaskParticipant(ctx, "ap-nostep", "agent-r", "reviewer"); err != nil { + t.Fatalf("AddTaskParticipant = %v, want nil", err) + } + if n := participantRowCount(t, repo, "ap-nostep"); n != 0 { + t.Errorf("rows = %d, want 0", n) + } + + // Same for a task that does not exist at all. + if err := repo.AddTaskParticipant(ctx, "ap-ghost", "agent-r", "reviewer"); err != nil { + t.Fatalf("AddTaskParticipant(missing task) = %v, want nil", err) + } + if n := participantRowCount(t, repo, "ap-ghost"); n != 0 { + t.Errorf("rows = %d, want 0", n) + } +} + +func TestRemoveTaskParticipant(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "rp-1", "step-1") + for _, spec := range []struct{ agent, role string }{ + {"agent-r", "reviewer"}, + {"agent-r", "approver"}, + {"agent-s", "reviewer"}, + } { + if err := repo.AddTaskParticipant(ctx, "rp-1", spec.agent, spec.role); err != nil { + t.Fatalf("AddTaskParticipant(%v): %v", spec, err) + } + } + // A template-level row for the same step must survive per-task removal. + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES ('tpl-row', 'step-1', '', 'reviewer', 'agent-r', 0, 0) + `); err != nil { + t.Fatalf("seed template row: %v", err) + } + + if err := repo.RemoveTaskParticipant(ctx, "rp-1", "agent-r", "reviewer"); err != nil { + t.Fatalf("RemoveTaskParticipant: %v", err) + } + if n := participantRowCount(t, repo, "rp-1"); n != 2 { + t.Errorf("per-task rows = %d, want 2", n) + } + var templateRows int + if err := repo.ReaderDB().Get(&templateRows, + `SELECT COUNT(*) FROM workflow_step_participants WHERE task_id = ''`); err != nil { + t.Fatalf("count template rows: %v", err) + } + if templateRows != 1 { + t.Errorf("template rows = %d, want the template row untouched", templateRows) + } + + // Removing a row that is not there is not an error. + if err := repo.RemoveTaskParticipant(ctx, "rp-1", "agent-nobody", "reviewer"); err != nil { + t.Fatalf("RemoveTaskParticipant(missing) = %v, want nil", err) + } + if n := participantRowCount(t, repo, "rp-1"); n != 2 { + t.Errorf("per-task rows = %d, want 2 after a no-op delete", n) + } +} + +func TestListTaskParticipants_FiltersRoleAndMergesTemplateRows(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "lp-1", "step-1") + seedParticipantTask(t, repo, "lp-other", "step-2") + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES + -- template rows for the same step + ('t-rev-shared', 'step-1', '', 'reviewer', 'agent-shared', 0, 0), + ('t-rev-only', 'step-1', '', 'reviewer', 'agent-tpl', 0, 2), + ('t-app', 'step-1', '', 'approver', 'agent-app', 0, 0), + -- per-task row that overrides the shared template entry + ('z-rev-shared', 'step-1', 'lp-1', 'reviewer', 'agent-shared', 1, 1), + -- another task's row on a different step + ('o-rev', 'step-2', 'lp-other','reviewer','agent-other', 1, 0) + `); err != nil { + t.Fatalf("seed participants: %v", err) + } + + got, err := repo.ListTaskParticipants(ctx, "lp-1", "reviewer") + if err != nil { + t.Fatalf("ListTaskParticipants: %v", err) + } + if len(got) != 2 { + t.Fatalf("participants = %+v, want 2 (shared merged, approver filtered out)", got) + } + // position ASC then id ASC: the template shared row (pos 0) is seen + // first and then replaced in place by the per-task row. + if got[0].AgentProfileID != "agent-shared" || !got[0].DecisionRequired { + t.Errorf("first = %+v, want agent-shared with the per-task decision_required", got[0]) + } + if got[1].AgentProfileID != "agent-tpl" || got[1].DecisionRequired { + t.Errorf("second = %+v, want the template-only agent-tpl", got[1]) + } + for _, p := range got { + if p.TaskID != "lp-1" { + t.Errorf("TaskID = %q, want every row projected onto lp-1", p.TaskID) + } + if p.Role != "reviewer" { + t.Errorf("Role = %q, want reviewer", p.Role) + } + if !p.CreatedAt.IsZero() { + t.Errorf("CreatedAt = %v, want the zero time (not stored on the step table)", p.CreatedAt) + } + } + + approvers, err := repo.ListTaskParticipants(ctx, "lp-1", "approver") + if err != nil { + t.Fatalf("ListTaskParticipants(approver): %v", err) + } + if len(approvers) != 1 || approvers[0].AgentProfileID != "agent-app" { + t.Errorf("approvers = %+v, want just agent-app", approvers) + } + + unknown, err := repo.ListTaskParticipants(ctx, "lp-1", "nosuchrole") + if err != nil { + t.Fatalf("ListTaskParticipants(unknown role): %v", err) + } + if unknown == nil { + t.Fatal("returned nil slice, want empty non-nil") + } + if len(unknown) != 0 { + t.Errorf("participants = %+v, want none", unknown) + } +} + +func TestListTaskParticipants_TaskWithoutAStepIsEmpty(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "lp-nostep", "") + // A row keyed on the empty step must not leak into an unstepped task. + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES ('n-1', '', 'lp-nostep', 'reviewer', 'agent-r', 1, 0) + `); err != nil { + t.Fatalf("seed participant: %v", err) + } + + got, err := repo.ListTaskParticipants(ctx, "lp-nostep", "reviewer") + if err != nil { + t.Fatalf("ListTaskParticipants: %v", err) + } + if len(got) != 0 { + t.Errorf("participants = %+v, want none for a task with no workflow step", got) + } + + all, err := repo.ListAllTaskParticipants(ctx, "lp-nostep") + if err != nil { + t.Fatalf("ListAllTaskParticipants: %v", err) + } + if len(all) != 0 { + t.Errorf("participants = %+v, want none", all) + } +} + +func TestListAllTaskParticipants_SpansRoles(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + seedParticipantTask(t, repo, "la-1", "step-1") + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES + ('r-1', 'step-1', 'la-1', 'reviewer', 'agent-rev', 1, 0), + ('a-1', 'step-1', 'la-1', 'approver', 'agent-app', 0, 0), + ('n-1', 'step-1', 'la-1', 'runner', 'agent-run', 0, 0) + `); err != nil { + t.Fatalf("seed participants: %v", err) + } + + got, err := repo.ListAllTaskParticipants(ctx, "la-1") + if err != nil { + t.Fatalf("ListAllTaskParticipants: %v", err) + } + if len(got) != 3 { + t.Fatalf("participants = %+v, want all three roles", got) + } + // ORDER BY role ASC. + roles := []string{got[0].Role, got[1].Role, got[2].Role} + if roles[0] != "approver" || roles[1] != "reviewer" || roles[2] != "runner" { + t.Errorf("roles = %v, want approver,reviewer,runner", roles) + } + if !got[1].DecisionRequired { + t.Error("reviewer DecisionRequired = false, want true") + } + if got[0].DecisionRequired { + t.Error("approver DecisionRequired = true, want false") + } +} + +func participantRowCount(t *testing.T, repo *sqlite.Repository, taskID string) int { + t.Helper() + var n int + if err := repo.ReaderDB().Get(&n, + `SELECT COUNT(*) FROM workflow_step_participants WHERE task_id = ?`, taskID); err != nil { + t.Fatalf("count participants: %v", err) + } + return n +} diff --git a/apps/backend/internal/office/repository/sqlite/projects_test.go b/apps/backend/internal/office/repository/sqlite/projects_test.go new file mode 100644 index 0000000000..397b9f8774 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/projects_test.go @@ -0,0 +1,419 @@ +package sqlite_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/kandev/kandev/internal/office/models" +) + +// fullProject builds a Project with every persisted column set to a +// distinct non-zero value. Every field is asserted on read-back so a +// column dropped from the INSERT or the SELECT projection fails loudly +// instead of silently defaulting. +func fullProject(id, workspaceID, name string) *models.Project { + return &models.Project{ + ID: id, + WorkspaceID: workspaceID, + Name: name, + Description: "ship the thing", + Status: models.ProjectStatus("archived"), + LeadAgentProfileID: "agent-lead-7", + Color: "#ff00aa", + BudgetCents: 123456, + Repositories: `["kdlbs/kandev","kdlbs/other"]`, + ExecutorConfig: `{"type":"local_docker"}`, + } +} + +// assertProjectEquals compares every persisted field of a project. +func assertProjectEquals(t *testing.T, got, want *models.Project) { + t.Helper() + if got.ID != want.ID { + t.Errorf("ID = %q, want %q", got.ID, want.ID) + } + if got.WorkspaceID != want.WorkspaceID { + t.Errorf("WorkspaceID = %q, want %q", got.WorkspaceID, want.WorkspaceID) + } + if got.Name != want.Name { + t.Errorf("Name = %q, want %q", got.Name, want.Name) + } + if got.Description != want.Description { + t.Errorf("Description = %q, want %q", got.Description, want.Description) + } + if got.Status != want.Status { + t.Errorf("Status = %q, want %q", got.Status, want.Status) + } + if got.LeadAgentProfileID != want.LeadAgentProfileID { + t.Errorf("LeadAgentProfileID = %q, want %q", got.LeadAgentProfileID, want.LeadAgentProfileID) + } + if got.Color != want.Color { + t.Errorf("Color = %q, want %q", got.Color, want.Color) + } + if got.BudgetCents != want.BudgetCents { + t.Errorf("BudgetCents = %d, want %d", got.BudgetCents, want.BudgetCents) + } + if got.Repositories != want.Repositories { + t.Errorf("Repositories = %q, want %q", got.Repositories, want.Repositories) + } + if got.ExecutorConfig != want.ExecutorConfig { + t.Errorf("ExecutorConfig = %q, want %q", got.ExecutorConfig, want.ExecutorConfig) + } + if !got.CreatedAt.Equal(want.CreatedAt) { + t.Errorf("CreatedAt = %v, want %v", got.CreatedAt, want.CreatedAt) + } + if !got.UpdatedAt.Equal(want.UpdatedAt) { + t.Errorf("UpdatedAt = %v, want %v", got.UpdatedAt, want.UpdatedAt) + } +} + +func TestCreateProject_RoundTripsEveryField(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + want := fullProject("proj-full", "ws-1", "Apollo") + before := time.Now().UTC().Add(-time.Second) + if err := repo.CreateProject(ctx, want); err != nil { + t.Fatalf("CreateProject: %v", err) + } + if want.CreatedAt.Before(before) || want.UpdatedAt.Before(before) { + t.Fatalf("CreateProject did not stamp timestamps: %v / %v", want.CreatedAt, want.UpdatedAt) + } + + got, err := repo.GetProject(ctx, "proj-full") + if err != nil { + t.Fatalf("GetProject: %v", err) + } + assertProjectEquals(t, got, want) +} + +func TestCreateProject_GeneratesIDWhenEmpty(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + project := fullProject("", "ws-1", "Generated") + if err := repo.CreateProject(ctx, project); err != nil { + t.Fatalf("CreateProject: %v", err) + } + if project.ID == "" { + t.Fatal("CreateProject left ID empty") + } + if _, err := repo.GetProject(ctx, project.ID); err != nil { + t.Fatalf("GetProject(generated id): %v", err) + } +} + +func TestGetProject_NotFound(t *testing.T) { + repo := newTestRepo(t) + + got, err := repo.GetProject(context.Background(), "missing") + if err == nil { + t.Fatal("GetProject(missing) = nil error, want not-found error") + } + if got != nil { + t.Errorf("GetProject(missing) returned %+v, want nil", got) + } + if !strings.Contains(err.Error(), "project not found: missing") { + t.Errorf("error = %q, want it to name the missing project", err) + } +} + +func TestGetProjectByName_ScopedToWorkspace(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + want := fullProject("proj-a", "ws-a", "Shared Name") + if err := repo.CreateProject(ctx, want); err != nil { + t.Fatalf("create ws-a project: %v", err) + } + other := fullProject("proj-b", "ws-b", "Shared Name") + if err := repo.CreateProject(ctx, other); err != nil { + t.Fatalf("create ws-b project: %v", err) + } + + got, err := repo.GetProjectByName(ctx, "ws-a", "Shared Name") + if err != nil { + t.Fatalf("GetProjectByName: %v", err) + } + assertProjectEquals(t, got, want) +} + +func TestGetProjectByName_NotFound(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateProject(ctx, fullProject("proj-a", "ws-a", "Apollo")); err != nil { + t.Fatalf("create project: %v", err) + } + + got, err := repo.GetProjectByName(ctx, "ws-other", "Apollo") + if err == nil { + t.Fatal("GetProjectByName(wrong workspace) = nil error, want not-found") + } + if got != nil { + t.Errorf("returned %+v, want nil", got) + } + if !strings.Contains(err.Error(), "project not found: Apollo") { + t.Errorf("error = %q, want it to name the project", err) + } +} + +func TestListProjects_ScopesAndOrdersByName(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + for _, p := range []*models.Project{ + fullProject("p-zulu", "ws-1", "Zulu"), + fullProject("p-alpha", "ws-1", "Alpha"), + fullProject("p-mike", "ws-1", "Mike"), + fullProject("p-other", "ws-2", "Bravo"), + } { + if err := repo.CreateProject(ctx, p); err != nil { + t.Fatalf("create %s: %v", p.ID, err) + } + } + + scoped, err := repo.ListProjects(ctx, "ws-1") + if err != nil { + t.Fatalf("ListProjects(ws-1): %v", err) + } + gotNames := make([]string, 0, len(scoped)) + for _, p := range scoped { + gotNames = append(gotNames, p.Name) + } + if strings.Join(gotNames, ",") != "Alpha,Mike,Zulu" { + t.Errorf("ListProjects(ws-1) names = %v, want Alpha,Mike,Zulu in that order", gotNames) + } + + all, err := repo.ListProjects(ctx, "") + if err != nil { + t.Fatalf("ListProjects(all): %v", err) + } + if len(all) != 4 { + t.Fatalf("ListProjects(\"\") returned %d rows, want 4 (all workspaces)", len(all)) + } + if all[0].Name != "Alpha" || all[1].Name != "Bravo" { + t.Errorf("ListProjects(\"\") not ordered by name: %q, %q", all[0].Name, all[1].Name) + } +} + +func TestListProjects_EmptyIsNonNilSlice(t *testing.T) { + repo := newTestRepo(t) + + got, err := repo.ListProjects(context.Background(), "ws-empty") + if err != nil { + t.Fatalf("ListProjects: %v", err) + } + if got == nil { + t.Fatal("ListProjects returned nil slice, want empty non-nil") + } + if len(got) != 0 { + t.Errorf("len = %d, want 0", len(got)) + } +} + +func TestUpdateProject_PersistsEveryMutableField(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + project := &models.Project{ + ID: "proj-upd", + WorkspaceID: "ws-1", + Name: "Before", + Status: models.ProjectStatus("active"), + } + if err := repo.CreateProject(ctx, project); err != nil { + t.Fatalf("CreateProject: %v", err) + } + createdAt := project.CreatedAt + + project.Name = "After" + project.Description = "new description" + project.Status = models.ProjectStatus("paused") + project.LeadAgentProfileID = "agent-new" + project.Color = "#00ff00" + project.BudgetCents = 999 + project.Repositories = `["kdlbs/updated"]` + project.ExecutorConfig = `{"type":"local_pc"}` + if err := repo.UpdateProject(ctx, project); err != nil { + t.Fatalf("UpdateProject: %v", err) + } + + got, err := repo.GetProject(ctx, "proj-upd") + if err != nil { + t.Fatalf("GetProject: %v", err) + } + assertProjectEquals(t, got, project) + if !got.CreatedAt.Equal(createdAt) { + t.Errorf("UpdateProject moved CreatedAt: %v, want %v", got.CreatedAt, createdAt) + } + if !got.UpdatedAt.After(createdAt) && !got.UpdatedAt.Equal(createdAt) { + t.Errorf("UpdatedAt = %v, want >= CreatedAt %v", got.UpdatedAt, createdAt) + } +} + +func TestUpdateProject_DoesNotTouchOtherRows(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + target := fullProject("proj-target", "ws-1", "Target") + bystander := fullProject("proj-bystander", "ws-1", "Bystander") + for _, p := range []*models.Project{target, bystander} { + if err := repo.CreateProject(ctx, p); err != nil { + t.Fatalf("create %s: %v", p.ID, err) + } + } + + target.Name = "Renamed" + if err := repo.UpdateProject(ctx, target); err != nil { + t.Fatalf("UpdateProject: %v", err) + } + + got, err := repo.GetProject(ctx, "proj-bystander") + if err != nil { + t.Fatalf("GetProject(bystander): %v", err) + } + assertProjectEquals(t, got, bystander) +} + +func TestDeleteProject_RemovesOnlyTargetRow(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + for _, p := range []*models.Project{ + fullProject("p-del", "ws-1", "Doomed"), + fullProject("p-keep", "ws-1", "Kept"), + } { + if err := repo.CreateProject(ctx, p); err != nil { + t.Fatalf("create %s: %v", p.ID, err) + } + } + + if err := repo.DeleteProject(ctx, "p-del"); err != nil { + t.Fatalf("DeleteProject: %v", err) + } + + remaining, err := repo.ListProjects(ctx, "ws-1") + if err != nil { + t.Fatalf("ListProjects: %v", err) + } + if len(remaining) != 1 { + t.Fatalf("remaining projects = %d, want 1: %+v", len(remaining), remaining) + } + if remaining[0].ID != "p-keep" { + t.Errorf("survivor = %q, want p-keep", remaining[0].ID) + } + if _, err := repo.GetProject(ctx, "p-del"); err == nil { + t.Error("GetProject(deleted) = nil error, want not-found") + } +} + +func TestDeleteProject_MissingRowIsNotAnError(t *testing.T) { + repo := newTestRepo(t) + + if err := repo.DeleteProject(context.Background(), "never-existed"); err != nil { + t.Fatalf("DeleteProject(missing) = %v, want nil", err) + } +} + +func TestListProjectsWithCounts_BucketsTaskStates(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + busy := fullProject("p-busy", "ws-1", "Busy") + idle := fullProject("p-idle", "ws-1", "Idle") + elsewhere := fullProject("p-elsewhere", "ws-2", "Elsewhere") + for _, p := range []*models.Project{busy, idle, elsewhere} { + if err := repo.CreateProject(ctx, p); err != nil { + t.Fatalf("create %s: %v", p.ID, err) + } + } + + // 6 tasks on p-busy: 2 in-progress buckets, 1 done, 1 blocked, 2 other. + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, project_id, state, title, created_at, updated_at) VALUES + ('t-inprog', 'ws-1', 'p-busy', 'IN_PROGRESS', 'a', datetime('now'), datetime('now')), + ('t-sched', 'ws-1', 'p-busy', 'SCHEDULING', 'b', datetime('now'), datetime('now')), + ('t-done', 'ws-1', 'p-busy', 'COMPLETED', 'c', datetime('now'), datetime('now')), + ('t-blocked', 'ws-1', 'p-busy', 'BLOCKED', 'd', datetime('now'), datetime('now')), + ('t-todo', 'ws-1', 'p-busy', 'TODO', 'e', datetime('now'), datetime('now')), + ('t-review', 'ws-1', 'p-busy', 'REVIEW', 'f', datetime('now'), datetime('now')), + ('t-noproject','ws-1', '', 'TODO', 'g', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + got, err := repo.ListProjectsWithCounts(ctx, "ws-1") + if err != nil { + t.Fatalf("ListProjectsWithCounts: %v", err) + } + if len(got) != 2 { + t.Fatalf("projects = %d, want 2 (ws-1 only): %+v", len(got), got) + } + + byID := map[string]*models.ProjectWithCounts{} + for _, p := range got { + byID[p.ID] = p + } + busyCounts := byID["p-busy"].TaskCounts + want := models.TaskCounts{Total: 6, InProgress: 2, Done: 1, Blocked: 1} + if busyCounts != want { + t.Errorf("p-busy counts = %+v, want %+v", busyCounts, want) + } + // A project with zero tasks must still appear, with all counts at 0 + // (that is the point of the LEFT JOIN). + if idleCounts := byID["p-idle"].TaskCounts; idleCounts != (models.TaskCounts{}) { + t.Errorf("p-idle counts = %+v, want all zero", idleCounts) + } + // The embedded Project must be fully hydrated, not just the id. + assertProjectEquals(t, &byID["p-busy"].Project, busy) +} + +func TestListProjectsWithCounts_EmptyWorkspace(t *testing.T) { + repo := newSearchTestRepo(t) + + got, err := repo.ListProjectsWithCounts(context.Background(), "ws-nothing") + if err != nil { + t.Fatalf("ListProjectsWithCounts: %v", err) + } + if got == nil { + t.Fatal("returned nil slice, want empty non-nil") + } + if len(got) != 0 { + t.Errorf("len = %d, want 0", len(got)) + } +} + +// GetProjectWorkspaceID lives in tasks.go but reads office_projects, so it +// is exercised alongside the project CRUD it depends on. +func TestGetProjectWorkspaceID(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + if err := repo.CreateProject(ctx, fullProject("p-ws", "ws-lookup", "Lookup")); err != nil { + t.Fatalf("CreateProject: %v", err) + } + + cases := []struct { + name string + projectID string + want string + }{ + {"existing project", "p-ws", "ws-lookup"}, + {"missing project", "p-nope", ""}, + {"empty id short-circuits", "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.GetProjectWorkspaceID(ctx, tc.projectID) + if err != nil { + t.Fatalf("GetProjectWorkspaceID: %v", err) + } + if got != tc.want { + t.Errorf("got %q, want %q", got, tc.want) + } + }) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/runtime_cleanup_test.go b/apps/backend/internal/office/repository/sqlite/runtime_cleanup_test.go new file mode 100644 index 0000000000..6daf5a999f --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/runtime_cleanup_test.go @@ -0,0 +1,260 @@ +package sqlite_test + +import ( + "context" + "sort" + "strings" + "testing" + + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +// seedRoutine inserts an office_routines row plus a trigger and a routine +// run for it, so the per-routine cleanup deletes have something to remove. +func seedRoutine(t *testing.T, repo *sqlite.Repository, routineID string) { + t.Helper() + ctx := context.Background() + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO office_routines (id, workspace_id, name, created_at, updated_at) + VALUES (?, 'ws-1', ?, datetime('now'), datetime('now')) + `, routineID, routineID); err != nil { + t.Fatalf("seed routine %s: %v", routineID, err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO office_routine_triggers (id, routine_id, kind, created_at, updated_at) + VALUES (?, ?, 'cron', datetime('now'), datetime('now')) + `, "trg-"+routineID, routineID); err != nil { + t.Fatalf("seed trigger for %s: %v", routineID, err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO office_routine_runs (id, routine_id, source, created_at) + VALUES (?, ?, 'cron', datetime('now')) + `, "run-"+routineID, routineID); err != nil { + t.Fatalf("seed routine run for %s: %v", routineID, err) + } +} + +func TestListDistinctTriggerRoutineIDs(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + ids, err := repo.ListDistinctTriggerRoutineIDs(ctx) + if err != nil { + t.Fatalf("ListDistinctTriggerRoutineIDs: %v", err) + } + if len(ids) != 0 { + t.Fatalf("ids = %v, want none on a clean database", ids) + } + + seedRoutine(t, repo, "rt-a") + seedRoutine(t, repo, "rt-b") + // A second trigger for rt-a must not produce a duplicate id. + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO office_routine_triggers (id, routine_id, kind, created_at, updated_at) + VALUES ('trg-rt-a-2', 'rt-a', 'webhook', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed second trigger: %v", err) + } + + ids, err = repo.ListDistinctTriggerRoutineIDs(ctx) + if err != nil { + t.Fatalf("ListDistinctTriggerRoutineIDs: %v", err) + } + sort.Strings(ids) + if strings.Join(ids, ",") != "rt-a,rt-b" { + t.Errorf("ids = %v, want rt-a,rt-b exactly once each", ids) + } +} + +func TestDeleteTriggersAndRunsByRoutineID(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedRoutine(t, repo, "rt-target") + seedRoutine(t, repo, "rt-keep") + + if err := repo.DeleteTriggersByRoutineID(ctx, "rt-target"); err != nil { + t.Fatalf("DeleteTriggersByRoutineID: %v", err) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routine_triggers WHERE routine_id = 'rt-target'`); n != 0 { + t.Errorf("triggers for rt-target = %d, want 0", n) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routine_triggers WHERE routine_id = 'rt-keep'`); n != 1 { + t.Errorf("triggers for rt-keep = %d, want 1", n) + } + // Deleting triggers must not touch the routine's runs. + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routine_runs WHERE routine_id = 'rt-target'`); n != 1 { + t.Errorf("routine runs for rt-target = %d, want 1", n) + } + + if err := repo.DeleteRunsByRoutineID(ctx, "rt-target"); err != nil { + t.Fatalf("DeleteRunsByRoutineID: %v", err) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routine_runs WHERE routine_id = 'rt-target'`); n != 0 { + t.Errorf("routine runs for rt-target = %d, want 0", n) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routine_runs WHERE routine_id = 'rt-keep'`); n != 1 { + t.Errorf("routine runs for rt-keep = %d, want 1", n) + } + // The routine row itself is not this method's business. + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_routines WHERE id = 'rt-target'`); n != 1 { + t.Errorf("routine rows = %d, want the routine itself preserved", n) + } + + // Unknown routine ids are no-ops. + if err := repo.DeleteTriggersByRoutineID(ctx, "rt-ghost"); err != nil { + t.Errorf("DeleteTriggersByRoutineID(ghost) = %v, want nil", err) + } + if err := repo.DeleteRunsByRoutineID(ctx, "rt-ghost"); err != nil { + t.Errorf("DeleteRunsByRoutineID(ghost) = %v, want nil", err) + } +} + +func seedBudgetPolicy(t *testing.T, repo *sqlite.Repository, id, scopeType, scopeID string) { + t.Helper() + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO office_budget_policies + (id, workspace_id, scope_type, scope_id, limit_subcents, period, created_at, updated_at) + VALUES (?, 'ws-1', ?, ?, 1000, 'monthly', datetime('now'), datetime('now')) + `, id, scopeType, scopeID); err != nil { + t.Fatalf("seed budget policy %s: %v", id, err) + } +} + +func TestDeleteBudgetPoliciesForRemovedScopes(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedBudgetPolicy(t, repo, "bp-agent-live", "agent", "agent-live") + seedBudgetPolicy(t, repo, "bp-agent-gone", "agent", "agent-gone") + seedBudgetPolicy(t, repo, "bp-agent-gone2", "agent", "agent-gone-2") + seedBudgetPolicy(t, repo, "bp-project", "project", "proj-1") + + removed, err := repo.DeleteBudgetPoliciesForRemovedScopes(ctx, "agent", []string{"agent-live"}) + if err != nil { + t.Fatalf("DeleteBudgetPoliciesForRemovedScopes: %v", err) + } + if removed != 2 { + t.Errorf("rows affected = %d, want 2", removed) + } + // Assert identity, not just the count: deleting the wrong two rows + // leaves the same total behind. + if got := scopeIDs(t, repo, "agent"); strings.Join(got, ",") != "agent-live" { + t.Errorf("surviving agent scopes = %v, want only agent-live", got) + } + // A different scope_type is out of scope for this call. + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_budget_policies WHERE scope_type = 'project'`); n != 1 { + t.Errorf("project policies = %d, want 1 (untouched)", n) + } + + // Every id still valid → nothing to delete. + removed, err = repo.DeleteBudgetPoliciesForRemovedScopes(ctx, "agent", []string{"agent-live"}) + if err != nil { + t.Fatalf("second call: %v", err) + } + if removed != 0 { + t.Errorf("rows affected = %d, want 0", removed) + } + + // An empty valid-id list wipes the whole scope type. + removed, err = repo.DeleteBudgetPoliciesForRemovedScopes(ctx, "agent", nil) + if err != nil { + t.Fatalf("empty valid ids: %v", err) + } + if removed != 1 { + t.Errorf("rows affected = %d, want 1", removed) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_budget_policies WHERE scope_type = 'agent'`); n != 0 { + t.Errorf("agent policies = %d, want 0", n) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_budget_policies WHERE scope_type = 'project'`); n != 1 { + t.Errorf("project policies = %d, want the other scope type preserved", n) + } +} + +func seedChannel(t *testing.T, repo *sqlite.Repository, id, agentID string) { + t.Helper() + if _, err := repo.ExecRaw(context.Background(), ` + INSERT INTO office_channels + (id, workspace_id, agent_profile_id, platform, created_at, updated_at) + VALUES (?, 'ws-1', ?, 'slack', datetime('now'), datetime('now')) + `, id, agentID); err != nil { + t.Fatalf("seed channel %s: %v", id, err) + } +} + +func TestDeleteChannelsForRemovedAgents(t *testing.T) { + repo := newTestRepo(t) + ctx := context.Background() + + seedChannel(t, repo, "ch-live", "agent-live") + seedChannel(t, repo, "ch-live-2", "agent-live") + seedChannel(t, repo, "ch-gone", "agent-gone") + + removed, err := repo.DeleteChannelsForRemovedAgents(ctx, []string{"agent-live"}) + if err != nil { + t.Fatalf("DeleteChannelsForRemovedAgents: %v", err) + } + if removed != 1 { + t.Errorf("rows affected = %d, want 1", removed) + } + // Both of the live agent's channels must survive and the removed + // agent's must be gone — a count of 2 alone does not say which. + if got := channelIDs(t, repo); strings.Join(got, ",") != "ch-live,ch-live-2" { + t.Errorf("surviving channels = %v, want ch-live,ch-live-2", got) + } + + // Nothing left to remove. + removed, err = repo.DeleteChannelsForRemovedAgents(ctx, []string{"agent-live"}) + if err != nil { + t.Fatalf("second call: %v", err) + } + if removed != 0 { + t.Errorf("rows affected = %d, want 0", removed) + } + + // An empty valid-agent list wipes every channel. + removed, err = repo.DeleteChannelsForRemovedAgents(ctx, nil) + if err != nil { + t.Fatalf("empty valid ids: %v", err) + } + if removed != 2 { + t.Errorf("rows affected = %d, want 2", removed) + } + if n := countRows(t, repo, `SELECT COUNT(*) FROM office_channels`); n != 0 { + t.Errorf("channels = %d, want 0", n) + } +} + +// scopeIDs returns the surviving budget-policy scope ids for a scope type, +// sorted, so tests can assert which rows a cleanup preserved. +func scopeIDs(t *testing.T, repo *sqlite.Repository, scopeType string) []string { + t.Helper() + var ids []string + if err := repo.ReaderDB().Select(&ids, + `SELECT scope_id FROM office_budget_policies WHERE scope_type = ? ORDER BY scope_id`, + scopeType); err != nil { + t.Fatalf("select scope ids: %v", err) + } + return ids +} + +// channelIDs returns the surviving channel ids, sorted. +func channelIDs(t *testing.T, repo *sqlite.Repository) []string { + t.Helper() + var ids []string + if err := repo.ReaderDB().Select(&ids, + `SELECT id FROM office_channels ORDER BY id`); err != nil { + t.Fatalf("select channel ids: %v", err) + } + return ids +} + +func countRows(t *testing.T, repo *sqlite.Repository, query string) int { + t.Helper() + var n int + if err := repo.ReaderDB().Get(&n, query); err != nil { + t.Fatalf("count query %q: %v", query, err) + } + return n +} diff --git a/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go b/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go index b80d2d58fe..eb4c8e2ae9 100644 --- a/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go +++ b/apps/backend/internal/office/repository/sqlite/tasks_filtered_test.go @@ -2,6 +2,7 @@ package sqlite_test import ( "context" + "fmt" "testing" "github.com/kandev/kandev/internal/office/repository/sqlite" @@ -200,6 +201,186 @@ func TestListTasksFiltered_RejectsInvalidSort(t *testing.T) { } } +func TestListTasksFiltered_AssigneeAndProjectFilters(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks + (id, workspace_id, workflow_step_id, project_id, title, state, priority, created_at, updated_at) + VALUES + ('af-1', 'ws-1', 'step-1', 'proj-a', 'One', 'TODO', 'medium', '2026-04-01T12:00:00Z', '2026-04-01T12:00:00Z'), + ('af-2', 'ws-1', 'step-2', 'proj-a', 'Two', 'TODO', 'medium', '2026-04-02T12:00:00Z', '2026-04-02T12:00:00Z'), + ('af-3', 'ws-1', 'step-3', 'proj-b', 'Three', 'TODO', 'medium', '2026-04-03T12:00:00Z', '2026-04-03T12:00:00Z') + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants (id, step_id, task_id, role, agent_profile_id, position) + VALUES + ('p-1', 'step-1', 'af-1', 'runner', 'agent-x', 0), + ('p-2', 'step-2', 'af-2', 'runner', 'agent-y', 0), + ('p-3', 'step-3', 'af-3', 'runner', 'agent-x', 0) + `); err != nil { + t.Fatalf("seed runners: %v", err) + } + + // The sort is stated explicitly rather than relying on the zero-value + // default, so a change of default surfaces as a sort failure elsewhere + // instead of a confusing "wrong ids" failure here. + ascByUpdated := sqlite.ListTasksOptions{SortField: sqlite.TaskSortUpdatedAt, SortDesc: false} + + opts := ascByUpdated + opts.AssigneeID = "agent-x" + page, err := repo.ListTasksFiltered(ctx, "ws-1", opts) + if err != nil { + t.Fatalf("filter by assignee: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 2 || got[0] != "af-1" || got[1] != "af-3" { + t.Fatalf("assignee filter = %v, want [af-1 af-3]", got) + } + if page.Tasks[0].AssigneeAgentProfileID != "agent-x" { + t.Errorf("assignee = %q, want agent-x projected onto the row", page.Tasks[0].AssigneeAgentProfileID) + } + + opts = ascByUpdated + opts.ProjectID = "proj-a" + page, err = repo.ListTasksFiltered(ctx, "ws-1", opts) + if err != nil { + t.Fatalf("filter by project: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 2 || got[0] != "af-1" || got[1] != "af-2" { + t.Fatalf("project filter = %v, want [af-1 af-2]", got) + } + + opts = ascByUpdated + opts.AssigneeID = "agent-x" + opts.ProjectID = "proj-b" + page, err = repo.ListTasksFiltered(ctx, "ws-1", opts) + if err != nil { + t.Fatalf("combined filter: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 1 || got[0] != "af-3" { + t.Fatalf("combined filter = %v, want [af-3]", got) + } +} + +// The cursor value is read off the sort column, so each sort field needs +// its own round-trip: a created_at cursor fed into a priority sort would +// silently return the wrong page. +func TestListTasksFiltered_CursorPerSortField(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, state, priority, created_at, updated_at) VALUES + ('cs-crit', 'ws-1', 'a', 'TODO', 'critical', '2026-04-03T12:00:00Z', '2026-04-01T12:00:00Z'), + ('cs-high', 'ws-1', 'b', 'TODO', 'high', '2026-04-02T12:00:00Z', '2026-04-02T12:00:00Z'), + ('cs-low', 'ws-1', 'c', 'TODO', 'low', '2026-04-01T12:00:00Z', '2026-04-03T12:00:00Z') + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + // created_at DESC is the reverse of updated_at DESC for this fixture, + // so a wrong sort column would be visible. + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sqlite.TaskSortCreatedAt, SortDesc: true, Limit: 2, + }) + if err != nil { + t.Fatalf("created_at page 1: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 2 || got[0] != "cs-crit" || got[1] != "cs-high" { + t.Fatalf("created_at page 1 = %v, want [cs-crit cs-high]", got) + } + if page.NextCursor != page.Tasks[1].CreatedAt { + t.Errorf("NextCursor = %q, want the tail row's created_at %q", page.NextCursor, page.Tasks[1].CreatedAt) + } + if page.NextID != "cs-high" { + t.Errorf("NextID = %q, want cs-high", page.NextID) + } + page2, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sqlite.TaskSortCreatedAt, SortDesc: true, Limit: 2, + CursorValue: page.NextCursor, CursorID: page.NextID, + }) + if err != nil { + t.Fatalf("created_at page 2: %v", err) + } + if got := taskIDs(page2.Tasks); len(got) != 1 || got[0] != "cs-low" { + t.Fatalf("created_at page 2 = %v, want [cs-low]", got) + } + + // priority sorts lexically on the column value: critical < high < low. + page, err = repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sqlite.TaskSortPriority, Limit: 2, + }) + if err != nil { + t.Fatalf("priority page 1: %v", err) + } + if got := taskIDs(page.Tasks); len(got) != 2 || got[0] != "cs-crit" || got[1] != "cs-high" { + t.Fatalf("priority page 1 = %v, want [cs-crit cs-high] ascending", got) + } + if page.NextCursor != "high" { + t.Errorf("NextCursor = %q, want the tail row's priority 'high'", page.NextCursor) + } + page2, err = repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{ + SortField: sqlite.TaskSortPriority, Limit: 2, + CursorValue: page.NextCursor, CursorID: page.NextID, + }) + if err != nil { + t.Fatalf("priority page 2: %v", err) + } + if got := taskIDs(page2.Tasks); len(got) != 1 || got[0] != "cs-low" { + t.Fatalf("priority page 2 = %v, want [cs-low]", got) + } + if page2.NextCursor != "" { + t.Errorf("NextCursor = %q, want empty on the final page", page2.NextCursor) + } +} + +// An out-of-range limit is clamped to 100 rather than rejected. Seeding 101 +// rows is what makes the clamp observable: with fewer rows than the clamp, +// every limit ≥ the row count returns the same page and the assertion would +// hold no matter what resolveListTasksOptions did. +func TestListTasksFiltered_ClampsLimit(t *testing.T) { + repo := newTestRepo(t) + ensureTasksTable(t, repo) + ctx := context.Background() + + for i := 0; i < 101; i++ { + insertTaskRow(t, repo, + fmt.Sprintf("cl-%03d", i), "ws-1", "TODO", "medium", + fmt.Sprintf("2026-04-01T12:%02d:00Z", i%60)) + } + + for _, limit := range []int{0, -5, 501} { + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{Limit: limit}) + if err != nil { + t.Fatalf("limit %d: %v", limit, err) + } + if len(page.Tasks) != 100 { + t.Errorf("limit %d returned %d rows, want the clamped 100", limit, len(page.Tasks)) + } + // 101 rows against a clamp of 100 means there is a next page. + if page.NextCursor == "" { + t.Errorf("limit %d NextCursor is empty, want the 101st row to be reachable", limit) + } + if page.NextID == "" { + t.Errorf("limit %d NextID is empty, want the tail row id", limit) + } + } + + // An in-range limit is honoured verbatim, so the clamp is not blanket. + page, err := repo.ListTasksFiltered(ctx, "ws-1", sqlite.ListTasksOptions{Limit: 7}) + if err != nil { + t.Fatalf("limit 7: %v", err) + } + if len(page.Tasks) != 7 { + t.Errorf("limit 7 returned %d rows, want 7", len(page.Tasks)) + } +} + func taskIDs(tasks []*sqlite.TaskRow) []string { out := make([]string, len(tasks)) for i, t := range tasks { diff --git a/apps/backend/internal/office/repository/sqlite/tasks_ops_test.go b/apps/backend/internal/office/repository/sqlite/tasks_ops_test.go new file mode 100644 index 0000000000..b92f8c3881 --- /dev/null +++ b/apps/backend/internal/office/repository/sqlite/tasks_ops_test.go @@ -0,0 +1,753 @@ +package sqlite_test + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/kandev/kandev/internal/office/models" + "github.com/kandev/kandev/internal/office/repository/sqlite" +) + +func TestGetTaskProjectID(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, project_id, title, created_at, updated_at) VALUES + ('tp-with', 'ws-1', 'proj-9', 'a', datetime('now'), datetime('now')), + ('tp-none', 'ws-1', '', 'b', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, + `UPDATE tasks SET project_id = NULL WHERE id = 'tp-none'`); err != nil { + t.Fatalf("null out project_id: %v", err) + } + + got, err := repo.GetTaskProjectID(ctx, "tp-with") + if err != nil { + t.Fatalf("GetTaskProjectID: %v", err) + } + if got != "proj-9" { + t.Errorf("got %q, want proj-9", got) + } + + // A NULL project_id reads back as the empty string, not an error. + got, err = repo.GetTaskProjectID(ctx, "tp-none") + if err != nil { + t.Fatalf("GetTaskProjectID (NULL column): %v", err) + } + if got != "" { + t.Errorf("got %q, want empty", got) + } + + if _, err = repo.GetTaskProjectID(ctx, "missing"); err == nil { + t.Error("GetTaskProjectID(missing) = nil error, want not-found") + } else if !strings.Contains(err.Error(), "task not found: missing") { + t.Errorf("error = %q, want it to name the task", err) + } +} + +func TestGetTaskWorkspaceID(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertTask(t, repo, ctx, "tw-1", "ws-lookup", "Title", "", "KAN-1") + + cases := []struct { + name string + taskID string + want string + }{ + {"existing task", "tw-1", "ws-lookup"}, + {"missing task", "tw-nope", ""}, + {"empty id short-circuits", "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := repo.GetTaskWorkspaceID(ctx, tc.taskID) + if err != nil { + t.Fatalf("GetTaskWorkspaceID: %v", err) + } + if got != tc.want { + t.Errorf("got %q, want %q", got, tc.want) + } + }) + } +} + +func TestUpdateTaskState(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertTask(t, repo, ctx, "us-1", "ws-1", "Title", "", "KAN-1") + insertTask(t, repo, ctx, "us-2", "ws-1", "Other", "", "KAN-2") + + if err := repo.UpdateTaskState(ctx, "us-1", "IN_PROGRESS"); err != nil { + t.Fatalf("UpdateTaskState: %v", err) + } + row, err := repo.GetTaskByID(ctx, "us-1") + if err != nil { + t.Fatalf("GetTaskByID: %v", err) + } + if row.Status != "IN_PROGRESS" { + t.Errorf("state = %q, want IN_PROGRESS", row.Status) + } + // The neighbouring row keeps its state. + if other, err := repo.GetTaskByID(ctx, "us-2"); err != nil { + t.Fatalf("GetTaskByID(us-2): %v", err) + } else if other.Status != "TODO" { + t.Errorf("us-2 state = %q, want the untouched TODO", other.Status) + } + + err = repo.UpdateTaskState(ctx, "missing", "COMPLETED") + if err == nil { + t.Fatal("UpdateTaskState(missing) = nil error, want not-found") + } + if !strings.Contains(err.Error(), "task not found: missing") { + t.Errorf("error = %q, want it to name the task", err) + } +} + +func TestUpdateTaskPriorityAndProjectID(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertTask(t, repo, ctx, "sc-1", "ws-1", "Title", "", "KAN-1") + + if err := repo.UpdateTaskPriority(ctx, "sc-1", "critical"); err != nil { + t.Fatalf("UpdateTaskPriority: %v", err) + } + if err := repo.UpdateTaskProjectID(ctx, "sc-1", "proj-7"); err != nil { + t.Fatalf("UpdateTaskProjectID: %v", err) + } + row, err := repo.GetTaskByID(ctx, "sc-1") + if err != nil { + t.Fatalf("GetTaskByID: %v", err) + } + if row.Priority != "critical" { + t.Errorf("priority = %q, want critical", row.Priority) + } + if row.ProjectID != "proj-7" { + t.Errorf("project_id = %q, want proj-7", row.ProjectID) + } + + // An empty project id clears the assignment. + if err := repo.UpdateTaskProjectID(ctx, "sc-1", ""); err != nil { + t.Fatalf("UpdateTaskProjectID(clear): %v", err) + } + if row, err = repo.GetTaskByID(ctx, "sc-1"); err != nil { + t.Fatalf("GetTaskByID: %v", err) + } + if row.ProjectID != "" { + t.Errorf("project_id = %q, want it cleared", row.ProjectID) + } + + for _, tc := range []struct { + name string + call func() error + }{ + {"priority", func() error { return repo.UpdateTaskPriority(ctx, "missing", "low") }}, + {"project id", func() error { return repo.UpdateTaskProjectID(ctx, "missing", "p") }}, + } { + t.Run(tc.name+" on a missing task", func(t *testing.T) { + err := tc.call() + if err == nil { + t.Fatal("got nil error, want not-found") + } + if !strings.Contains(err.Error(), "task not found: missing") { + t.Errorf("error = %q, want it to name the task", err) + } + }) + } +} + +func TestUpdateTaskParentID_NormalisesInheritParentWorkspace(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, parent_id, title, metadata, created_at, updated_at) VALUES + ('pa-inherit', 'ws-1', 'old-parent', 'a', '{"workspace":{"mode":"inherit_parent"}}', + datetime('now'), datetime('now')), + ('pa-shared', 'ws-1', 'old-parent', 'b', '{"workspace":{"mode":"new_workspace"}}', + datetime('now'), datetime('now')), + ('pa-badjson', 'ws-1', 'old-parent', 'c', 'not json', + datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + if err := repo.UpdateTaskParentID(ctx, "pa-inherit", "new-parent"); err != nil { + t.Fatalf("UpdateTaskParentID: %v", err) + } + row, err := repo.GetTaskByID(ctx, "pa-inherit") + if err != nil { + t.Fatalf("GetTaskByID: %v", err) + } + if row.ParentID != "new-parent" { + t.Errorf("parent_id = %q, want new-parent", row.ParentID) + } + if mode := taskWorkspaceMode(t, repo, "pa-inherit"); mode != "shared_group" { + t.Errorf("workspace.mode = %q, want shared_group after re-parenting", mode) + } + + // A non-inherit mode is left alone. + if err := repo.UpdateTaskParentID(ctx, "pa-shared", "new-parent"); err != nil { + t.Fatalf("UpdateTaskParentID(pa-shared): %v", err) + } + if mode := taskWorkspaceMode(t, repo, "pa-shared"); mode != "new_workspace" { + t.Errorf("workspace.mode = %q, want new_workspace untouched", mode) + } + + // Invalid JSON metadata is left verbatim rather than erroring. + if err := repo.UpdateTaskParentID(ctx, "pa-badjson", "new-parent"); err != nil { + t.Fatalf("UpdateTaskParentID(pa-badjson): %v", err) + } + var raw string + if err := repo.ReaderDB().Get(&raw, `SELECT metadata FROM tasks WHERE id = 'pa-badjson'`); err != nil { + t.Fatalf("read metadata: %v", err) + } + if raw != "not json" { + t.Errorf("metadata = %q, want it preserved verbatim", raw) + } + + err = repo.UpdateTaskParentID(ctx, "missing", "p") + if err == nil { + t.Fatal("UpdateTaskParentID(missing) = nil error, want not-found") + } + if !strings.Contains(err.Error(), "task not found: missing") { + t.Errorf("error = %q, want it to name the task", err) + } +} + +// A repeated PATCH with the same parent must not rewrite the workspace mode. +func TestUpdateTaskParentID_SameParentIsANoOpForWorkspaceMode(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, parent_id, title, metadata, created_at, updated_at) + VALUES ('pa-same', 'ws-1', 'parent-1', 'a', '{"workspace":{"mode":"inherit_parent"}}', + datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + + if err := repo.UpdateTaskParentID(ctx, "pa-same", "parent-1"); err != nil { + t.Fatalf("UpdateTaskParentID: %v", err) + } + if mode := taskWorkspaceMode(t, repo, "pa-same"); mode != "inherit_parent" { + t.Errorf("workspace.mode = %q, want inherit_parent kept when the parent does not change", mode) + } +} + +func taskWorkspaceMode(t *testing.T, repo *sqlite.Repository, taskID string) string { + t.Helper() + var mode string + if err := repo.ReaderDB().Get(&mode, + `SELECT COALESCE(json_extract(metadata, '$.workspace.mode'), '') FROM tasks WHERE id = ?`, + taskID); err != nil { + t.Fatalf("read workspace mode for %s: %v", taskID, err) + } + return mode +} + +func TestGetTaskBasicInfo(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, description, identifier, priority, project_id, created_at, updated_at) + VALUES ('bi-1', 'ws-1', 'Ship it', 'the description', 'KAN-7', 'high', 'proj-2', + datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + + got, err := repo.GetTaskBasicInfo(ctx, "bi-1") + if err != nil { + t.Fatalf("GetTaskBasicInfo: %v", err) + } + if got == nil { + t.Fatal("got nil, want the task info") + } + want := sqlite.TaskBasicInfo{ + Title: "Ship it", Description: "the description", + Identifier: "KAN-7", Priority: "high", ProjectID: "proj-2", + } + if *got != want { + t.Errorf("got %+v, want %+v", *got, want) + } + + // A missing task is nil, nil — not an error. + got, err = repo.GetTaskBasicInfo(ctx, "missing") + if err != nil { + t.Fatalf("GetTaskBasicInfo(missing) = %v, want nil error", err) + } + if got != nil { + t.Errorf("got %+v, want nil", got) + } +} + +func TestGetTaskBasicInfo_NullColumnsCoalesce(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, title, created_at, updated_at) + VALUES ('bi-null', 'ws-1', 'Bare', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + UPDATE tasks SET description = NULL, identifier = NULL, project_id = NULL + WHERE id = 'bi-null' + `); err != nil { + t.Fatalf("null out columns: %v", err) + } + + got, err := repo.GetTaskBasicInfo(ctx, "bi-null") + if err != nil { + t.Fatalf("GetTaskBasicInfo: %v", err) + } + want := sqlite.TaskBasicInfo{Title: "Bare", Priority: "medium"} + if *got != want { + t.Errorf("got %+v, want %+v (NULL columns coalesced to empty strings)", *got, want) + } +} + +func TestUpdateTaskAssignee_WritesUpdatesAndClearsRunnerRow(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_step_id, title, created_at, updated_at) + VALUES ('as-1', 'ws-1', 'step-1', 'Assign me', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + + if err := repo.UpdateTaskAssignee(ctx, "as-1", "agent-one"); err != nil { + t.Fatalf("UpdateTaskAssignee (insert): %v", err) + } + if got := taskRunner(t, repo, "as-1"); got != "agent-one" { + t.Fatalf("runner = %q, want agent-one", got) + } + if n := runnerRowCount(t, repo, "as-1"); n != 1 { + t.Fatalf("runner rows = %d, want 1", n) + } + + // A second assignment updates the existing row instead of adding one. + if err := repo.UpdateTaskAssignee(ctx, "as-1", "agent-two"); err != nil { + t.Fatalf("UpdateTaskAssignee (update): %v", err) + } + if got := taskRunner(t, repo, "as-1"); got != "agent-two" { + t.Errorf("runner = %q, want agent-two", got) + } + if n := runnerRowCount(t, repo, "as-1"); n != 1 { + t.Errorf("runner rows = %d, want the row updated in place", n) + } + + // An empty assignee deletes the runner row. + if err := repo.UpdateTaskAssignee(ctx, "as-1", ""); err != nil { + t.Fatalf("UpdateTaskAssignee (clear): %v", err) + } + if n := runnerRowCount(t, repo, "as-1"); n != 0 { + t.Errorf("runner rows = %d, want 0 after clearing", n) + } + if got := taskRunner(t, repo, "as-1"); got != "" { + t.Errorf("runner = %q, want empty after clearing", got) + } + + err := repo.UpdateTaskAssignee(ctx, "missing", "agent-one") + if err == nil { + t.Fatal("UpdateTaskAssignee(missing) = nil error, want not-found") + } + if !strings.Contains(err.Error(), "task not found: missing") { + t.Errorf("error = %q, want it to name the task", err) + } +} + +// Tasks created outside a workflow have no workflow_step_id; the runner row +// is keyed on the empty step so the projection still resolves it. +func TestUpdateTaskAssignee_WorksWithoutAWorkflowStep(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_step_id, title, created_at, updated_at) + VALUES ('as-nostep', 'ws-1', '', 'Channel task', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed task: %v", err) + } + + if err := repo.UpdateTaskAssignee(ctx, "as-nostep", "agent-channel"); err != nil { + t.Fatalf("UpdateTaskAssignee: %v", err) + } + if got := taskRunner(t, repo, "as-nostep"); got != "agent-channel" { + t.Errorf("runner = %q, want agent-channel", got) + } +} + +// Only the target task's runner row moves. +func TestUpdateTaskAssignee_LeavesOtherTasksAlone(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_step_id, title, created_at, updated_at) VALUES + ('as-a', 'ws-1', 'step-shared', 'A', datetime('now'), datetime('now')), + ('as-b', 'ws-1', 'step-shared', 'B', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + if err := repo.UpdateTaskAssignee(ctx, "as-a", "agent-a"); err != nil { + t.Fatalf("assign as-a: %v", err) + } + if err := repo.UpdateTaskAssignee(ctx, "as-b", "agent-b"); err != nil { + t.Fatalf("assign as-b: %v", err) + } + if err := repo.UpdateTaskAssignee(ctx, "as-b", ""); err != nil { + t.Fatalf("clear as-b: %v", err) + } + + if got := taskRunner(t, repo, "as-a"); got != "agent-a" { + t.Errorf("as-a runner = %q, want agent-a to survive as-b's clear", got) + } + if got := taskRunner(t, repo, "as-b"); got != "" { + t.Errorf("as-b runner = %q, want empty", got) + } +} + +func taskRunner(t *testing.T, repo *sqlite.Repository, taskID string) string { + t.Helper() + fields, err := repo.GetTaskExecutionFields(context.Background(), taskID) + if err != nil { + t.Fatalf("GetTaskExecutionFields(%s): %v", taskID, err) + } + return fields.AssigneeAgentProfileID +} + +func runnerRowCount(t *testing.T, repo *sqlite.Repository, taskID string) int { + t.Helper() + var n int + if err := repo.ReaderDB().Get(&n, + `SELECT COUNT(*) FROM workflow_step_participants WHERE task_id = ? AND role = 'runner'`, + taskID); err != nil { + t.Fatalf("count runner rows: %v", err) + } + return n +} + +func TestGetTaskExecutionFields_NotFoundSentinel(t *testing.T) { + repo := newSearchTestRepo(t) + + got, err := repo.GetTaskExecutionFields(context.Background(), "missing") + if err == nil { + t.Fatal("GetTaskExecutionFields(missing) = nil error, want ErrTaskNotFound") + } + if !errors.Is(err, sqlite.ErrTaskNotFound) { + t.Errorf("error = %v, want it to wrap ErrTaskNotFound", err) + } + if got != nil { + t.Errorf("got %+v, want nil", got) + } +} + +func TestGetTaskExecutionFields_ProjectsOfficeOrigin(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workspaces (id, office_workflow_id) VALUES ('ws-office', 'wf-office'), ('ws-plain', '') + `); err != nil { + t.Fatalf("seed workspaces: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks (id, workspace_id, workflow_id, state, title, created_at, updated_at) VALUES + ('ef-office', 'ws-office', 'wf-office', 'IN_PROGRESS', 'Office', datetime('now'), datetime('now')), + ('ef-plain', 'ws-plain', 'wf-plain', 'TODO', 'Plain', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + + office, err := repo.GetTaskExecutionFields(ctx, "ef-office") + if err != nil { + t.Fatalf("GetTaskExecutionFields(office): %v", err) + } + if office.ID != "ef-office" || office.State != "IN_PROGRESS" || office.WorkspaceID != "ws-office" { + t.Errorf("got %+v, want the office task's own fields", *office) + } + if !office.IsFromOffice { + t.Error("IsFromOffice = false, want true for a task in the office workflow") + } + + plain, err := repo.GetTaskExecutionFields(ctx, "ef-plain") + if err != nil { + t.Fatalf("GetTaskExecutionFields(plain): %v", err) + } + if plain.IsFromOffice { + t.Error("IsFromOffice = true, want false for a plain Kanban task") + } +} + +func TestListChildTasks(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO tasks + (id, workspace_id, parent_id, workflow_step_id, title, description, state, priority, + project_id, labels, identifier, is_ephemeral, origin, created_at, updated_at) + VALUES + ('c-first', 'ws-1', 'parent-1', 'step-c', 'First', 'desc one', 'TODO', 'high', + 'proj-1', '["a"]', 'KAN-1', 0, 'manual', '2026-01-01 00:00:00', '2026-01-01 00:00:00'), + ('c-second', 'ws-1', 'parent-1', 'step-c', 'Second', '', 'COMPLETED', 'low', + '', '[]', 'KAN-2', 0, 'manual', '2026-01-02 00:00:00', '2026-01-02 00:00:00'), + ('c-eph', 'ws-1', 'parent-1', 'step-c', 'Eph', '', 'TODO', 'medium', + '', '[]', 'KAN-3', 1, 'manual', '2026-01-03 00:00:00', '2026-01-03 00:00:00'), + ('c-auto', 'ws-1', 'parent-1', 'step-c', 'Auto', '', 'TODO', 'medium', + '', '[]', 'KAN-4', 0, 'automation_run', '2026-01-04 00:00:00', '2026-01-04 00:00:00'), + ('c-arch', 'ws-1', 'parent-1', 'step-c', 'Arch', '', 'TODO', 'medium', + '', '[]', 'KAN-5', 0, 'manual', '2026-01-05 00:00:00', '2026-01-05 00:00:00'), + ('c-other', 'ws-1', 'parent-2', 'step-c', 'Other', '', 'TODO', 'medium', + '', '[]', 'KAN-6', 0, 'manual', '2026-01-06 00:00:00', '2026-01-06 00:00:00') + `); err != nil { + t.Fatalf("seed tasks: %v", err) + } + if _, err := repo.ExecRaw(ctx, + `UPDATE tasks SET archived_at = '2026-01-06 00:00:00' WHERE id = 'c-arch'`); err != nil { + t.Fatalf("archive c-arch: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO workflow_step_participants + (id, step_id, task_id, role, agent_profile_id, decision_required, position) + VALUES ('p-c-first', 'step-c', 'c-first', 'runner', 'agent-child', 0, 0) + `); err != nil { + t.Fatalf("seed runner: %v", err) + } + + rows, err := repo.ListChildTasks(ctx, "parent-1") + if err != nil { + t.Fatalf("ListChildTasks: %v", err) + } + ids := make([]string, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row.ID) + } + if strings.Join(ids, ",") != "c-first,c-second" { + t.Fatalf("ids = %v, want c-first,c-second (created_at ASC; ephemeral, automation and archived excluded)", ids) + } + + first := rows[0] + want := sqlite.TaskRow{ + ID: "c-first", WorkspaceID: "ws-1", Identifier: "KAN-1", Title: "First", + Description: "desc one", Status: "TODO", Priority: "high", ParentID: "parent-1", + ProjectID: "proj-1", AssigneeAgentProfileID: "agent-child", Labels: `["a"]`, + CreatedAt: first.CreatedAt, UpdatedAt: first.UpdatedAt, + } + if *first != want { + t.Errorf("first child = %+v, want %+v", *first, want) + } + if first.CreatedAt == "" || first.UpdatedAt == "" { + t.Error("timestamps are empty, want them projected") + } + + none, err := repo.ListChildTasks(ctx, "parent-without-children") + if err != nil { + t.Fatalf("ListChildTasks(no children): %v", err) + } + if len(none) != 0 { + t.Errorf("rows = %+v, want none", none) + } +} + +func TestCheckoutTask_ExclusiveLockLifecycle(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertTask(t, repo, ctx, "co-1", "ws-1", "Lock me", "", "KAN-1") + + acquired, err := repo.CheckoutTask(ctx, "co-1", "agent-a") + if err != nil { + t.Fatalf("CheckoutTask: %v", err) + } + if !acquired { + t.Fatal("first checkout = false, want the lock acquired") + } + if got := checkoutAgent(t, repo, "co-1"); got != "agent-a" { + t.Errorf("checkout_agent_id = %q, want agent-a", got) + } + if at := checkoutAt(t, repo, "co-1"); at == "" { + t.Error("checkout_at is empty, want it stamped") + } + + // The holder can re-acquire its own lock. + if acquired, err = repo.CheckoutTask(ctx, "co-1", "agent-a"); err != nil || !acquired { + t.Fatalf("re-checkout by holder = %v, %v; want true, nil", acquired, err) + } + + // A different agent is refused. + if acquired, err = repo.CheckoutTask(ctx, "co-1", "agent-b"); err != nil { + t.Fatalf("CheckoutTask(other agent): %v", err) + } + if acquired { + t.Error("second agent acquired a held lock") + } + if got := checkoutAgent(t, repo, "co-1"); got != "agent-a" { + t.Errorf("checkout_agent_id = %q, want agent-a to keep the lock", got) + } + + // Releasing clears both columns and re-opens the lock. + if err = repo.ReleaseTaskCheckout(ctx, "co-1"); err != nil { + t.Fatalf("ReleaseTaskCheckout: %v", err) + } + if got := checkoutAgent(t, repo, "co-1"); got != "" { + t.Errorf("checkout_agent_id = %q, want it cleared", got) + } + if at := checkoutAt(t, repo, "co-1"); at != "" { + t.Errorf("checkout_at = %q, want it cleared", at) + } + if acquired, err = repo.CheckoutTask(ctx, "co-1", "agent-b"); err != nil || !acquired { + t.Fatalf("checkout after release = %v, %v; want true, nil", acquired, err) + } + + // A missing task yields false, not an error. + if acquired, err = repo.CheckoutTask(ctx, "missing", "agent-a"); err != nil { + t.Fatalf("CheckoutTask(missing): %v", err) + } + if acquired { + t.Error("CheckoutTask(missing) = true, want false") + } + if err = repo.ReleaseTaskCheckout(ctx, "missing"); err != nil { + t.Errorf("ReleaseTaskCheckout(missing) = %v, want nil", err) + } +} + +// An empty-string checkout_agent_id counts as unheld, same as NULL. +func TestCheckoutTask_TreatsEmptyHolderAsFree(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + insertTask(t, repo, ctx, "co-empty", "ws-1", "Lock", "", "KAN-1") + if _, err := repo.ExecRaw(ctx, + `UPDATE tasks SET checkout_agent_id = '' WHERE id = 'co-empty'`); err != nil { + t.Fatalf("blank the holder: %v", err) + } + + acquired, err := repo.CheckoutTask(ctx, "co-empty", "agent-a") + if err != nil { + t.Fatalf("CheckoutTask: %v", err) + } + if !acquired { + t.Error("CheckoutTask on an empty-string holder = false, want the lock acquired") + } +} + +func checkoutAgent(t *testing.T, repo *sqlite.Repository, taskID string) string { + t.Helper() + var got string + if err := repo.ReaderDB().Get(&got, + `SELECT COALESCE(checkout_agent_id, '') FROM tasks WHERE id = ?`, taskID); err != nil { + t.Fatalf("read checkout_agent_id: %v", err) + } + return got +} + +func checkoutAt(t *testing.T, repo *sqlite.Repository, taskID string) string { + t.Helper() + var got string + if err := repo.ReaderDB().Get(&got, + `SELECT COALESCE(CAST(checkout_at AS TEXT), '') FROM tasks WHERE id = ?`, taskID); err != nil { + t.Fatalf("read checkout_at: %v", err) + } + return got +} + +func TestGetCheckoutAgentBySession(t *testing.T) { + repo := newSearchTestRepo(t) + ensureSessionTables(t, repo) + ctx := context.Background() + + insertTask(t, repo, ctx, "cs-held", "ws-1", "Held", "", "KAN-1") + insertTask(t, repo, ctx, "cs-free", "ws-1", "Free", "", "KAN-2") + if _, err := repo.CheckoutTask(ctx, "cs-held", "agent-holder"); err != nil { + t.Fatalf("CheckoutTask: %v", err) + } + if _, err := repo.ExecRaw(ctx, ` + INSERT INTO task_sessions (id, task_id, state, started_at, updated_at) VALUES + ('sess-held', 'cs-held', 'RUNNING', datetime('now'), datetime('now')), + ('sess-free', 'cs-free', 'RUNNING', datetime('now'), datetime('now')) + `); err != nil { + t.Fatalf("seed sessions: %v", err) + } + + got, err := repo.GetCheckoutAgentBySession(ctx, "sess-held") + if err != nil { + t.Fatalf("GetCheckoutAgentBySession: %v", err) + } + if got != "agent-holder" { + t.Errorf("got %q, want agent-holder", got) + } + + // A task with no checkout resolves to the empty string. + if got, err = repo.GetCheckoutAgentBySession(ctx, "sess-free"); err != nil { + t.Fatalf("GetCheckoutAgentBySession(free): %v", err) + } + if got != "" { + t.Errorf("got %q, want empty", got) + } + + // An unknown session surfaces sql.ErrNoRows. + if _, err = repo.GetCheckoutAgentBySession(ctx, "sess-missing"); err == nil { + t.Error("GetCheckoutAgentBySession(missing) = nil error, want sql.ErrNoRows") + } +} + +func TestHasOfficeAdoption(t *testing.T) { + repo := newSearchTestRepo(t) + ctx := context.Background() + + adopted, err := repo.HasOfficeAdoption(ctx) + if err != nil { + t.Fatalf("HasOfficeAdoption: %v", err) + } + if adopted { + t.Fatal("HasOfficeAdoption = true on a clean database, want false") + } + + // A workspace row with an empty office_workflow_id is not adoption. + if _, err := repo.ExecRaw(ctx, + `INSERT INTO workspaces (id, office_workflow_id) VALUES ('ws-plain', '')`); err != nil { + t.Fatalf("seed workspace: %v", err) + } + if adopted, err = repo.HasOfficeAdoption(ctx); err != nil || adopted { + t.Fatalf("HasOfficeAdoption = %v, %v; want false for an unconfigured workspace", adopted, err) + } + + // An office project alone is enough. + if err := repo.CreateProject(ctx, &models.Project{ + ID: "p-adopt", WorkspaceID: "ws-plain", Name: "Adopted", Status: models.ProjectStatus("active"), + }); err != nil { + t.Fatalf("CreateProject: %v", err) + } + if adopted, err = repo.HasOfficeAdoption(ctx); err != nil || !adopted { + t.Fatalf("HasOfficeAdoption = %v, %v; want true once a project exists", adopted, err) + } + + // So is a workspace with an office workflow, with no projects at all. + if err := repo.DeleteProject(ctx, "p-adopt"); err != nil { + t.Fatalf("DeleteProject: %v", err) + } + if _, err := repo.ExecRaw(ctx, + `UPDATE workspaces SET office_workflow_id = 'wf-1' WHERE id = 'ws-plain'`); err != nil { + t.Fatalf("set office workflow: %v", err) + } + if adopted, err = repo.HasOfficeAdoption(ctx); err != nil || !adopted { + t.Fatalf("HasOfficeAdoption = %v, %v; want true for a configured workspace", adopted, err) + } +} diff --git a/apps/backend/internal/office/repository/sqlite/tasks_test.go b/apps/backend/internal/office/repository/sqlite/tasks_test.go index ec965e7ed7..df486a9df1 100644 --- a/apps/backend/internal/office/repository/sqlite/tasks_test.go +++ b/apps/backend/internal/office/repository/sqlite/tasks_test.go @@ -44,6 +44,9 @@ func newSearchTestRepo(t *testing.T) *sqlite.Repository { identifier TEXT DEFAULT '', is_ephemeral INTEGER DEFAULT 0, origin TEXT DEFAULT 'manual', + metadata TEXT DEFAULT '{}', + checkout_agent_id TEXT, + checkout_at TIMESTAMP, archived_at TIMESTAMP, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP