Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
test(server): add internal/testutil and migrate the eight heaviest handler suites (MUL-6361) (#7160)
Jiayuan Zhang877a71568f6d
diff --git a/CLAUDE.md b/CLAUDE.mdindex ac9b47bace..ebf0cfed95 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -215,6 +215,9 @@ Rules:- Mock `@multica/core/api` for API calls.- E2E tests should use `TestApiClient` for setup/teardown.- Prefer writing the failing test in the correct package before implementation when the change is behavioral.+- DB-backed Go tests build their rows through `server/internal/testutil` (`dbfx.Issue`, `dbfx.Task`, `dbfx.Insert`) and drive handlers through `testutil.Call(h, req).Want(status).JSON(&out)`. Do not open-code an `INSERT ... RETURNING id` with its matching `t.Cleanup(DELETE ...)`, or a `httptest.NewRecorder()` / status-check / decode quartet, in a new test. `internal/handler` held ~1000 of the first and ~1200 of the second before the shared fixtures landed, and every change to a shared contract had to be made once per copy.+- Keep an assertion where the test wrote it when its message says something the shared one cannot. `.Want()` prints the request line, both statuses and the response body; it does not know which case in a loop was running.+- Helpers in `internal/testutil` insert rows, run handlers and report mismatches. They must not assert a product rule on a test's behalf — a helper that knows what a correct response looks like has taken the assertion away from the test making it.- Default tests must never resolve or execute user-installed agent CLIs. Pass a test-created fake executable path or a test-created missing path to agent subprocess code.- Real-agent smoke tests belong behind the `agentintegration` build tag and must check `MULTICA_RUN_REAL_AGENT_SMOKE=1` before executable lookup or account access.- Run an explicitly authorized real-agent smoke test with `(cd server && MULTICA_RUN_REAL_AGENT_SMOKE=1 go test -tags=agentintegration ./pkg/agent -run '<test-name>' -count=1 -v)`. This command may access an authenticated account and consume quota.diff --git a/server/internal/handler/cancel_task_by_user_test.go b/server/internal/handler/cancel_task_by_user_test.goindex ed75f7e118..7b9813b360 100644--- a/server/internal/handler/cancel_task_by_user_test.go+++ b/server/internal/handler/cancel_task_by_user_test.go@@ -8,6 +8,7 @@ import ("testing""time"+ "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/protocol")@@ -23,11 +24,9 @@ import (func taskStatus(t *testing.T, taskID string) string {t.Helper()var status string- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT status FROM agent_task_queue WHERE id = $1`, taskID,- ).Scan(&status); err != nil {- t.Fatalf("read task status: %v", err)- }+ ).Scan(&status)return status}@@ -38,43 +37,31 @@ func taskStatus(t *testing.T, taskID string) string {// too.func createAutopilotRunOnlyTask(t *testing.T, agentID string) string {t.Helper()- ctx := context.Background()var workspaceID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT workspace_id, runtime_id FROM agent WHERE id = $1`, agentID,- ).Scan(&workspaceID, &runtimeID); err != nil {- t.Fatalf("load agent workspace/runtime: %v", err)- }-- var autopilotID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)- VALUES ($1, 'cancel-runonly-ap', $2, 'run_only', 'member', $3)- RETURNING id- `, workspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {- t.Fatalf("create autopilot: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })+ ).Scan(&workspaceID, &runtimeID)++ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": workspaceID,+ "title": "cancel-runonly-ap",+ "assignee_id": agentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })- var runID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot_run (autopilot_id, source, status)- VALUES ($1, 'manual', 'running')- RETURNING id- `, autopilotID).Scan(&runID); err != nil {- t.Fatalf("create autopilot_run: %v", err)- }+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "running",+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, autopilot_run_id)- VALUES ($1, $2, 'queued', 0, $3)- RETURNING id- `, agentID, runtimeID, runID).Scan(&taskID); err != nil {- t.Fatalf("create run_only task: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "autopilot_run_id": runID,+ })return taskID}@@ -82,35 +69,36 @@ func createAutopilotRunOnlyTask(t *testing.T, agentID string) string {// and returns the agent ID, for cross-tenant cancel tests.func createForeignWorkspaceAgent(t *testing.T) string {t.Helper()- ctx := context.Background()- var workspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ('Foreign Cancel WS', 'foreign-cancel-ws', 'cross-tenant cancel test', 'FCW')- RETURNING id- `).Scan(&workspaceID); err != nil {- t.Fatalf("create foreign workspace: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID) })+ workspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Foreign Cancel WS",+ "slug": "foreign-cancel-ws",+ "description": "cross-tenant cancel test",+ "issue_prefix": "FCW",+ })- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at)- VALUES ($1, NULL, 'Foreign Cancel Runtime', 'cloud', 'foreign_runtime', 'online', 'Foreign runtime', '{}'::jsonb, now())- RETURNING id- `, workspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("create foreign runtime: %v", err)- }+ runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": workspaceID,+ "daemon_id": nil,+ "name": "Foreign Cancel Runtime",+ "runtime_mode": "cloud",+ "provider": "foreign_runtime",+ "status": "online",+ "device_info": "Foreign runtime",+ "metadata": testutil.Raw("'{}'::jsonb"),+ "last_seen_at": testutil.Raw("now()"),+ })- var agentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks)- VALUES ($1, 'Foreign Cancel Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1)- RETURNING id- `, workspaceID, runtimeID).Scan(&agentID); err != nil {- t.Fatalf("create foreign agent: %v", err)- }+ agentID := dbfx.Insert(t, "agent", testutil.Cols{+ "workspace_id": workspaceID,+ "name": "Foreign Cancel Agent",+ "description": "",+ "runtime_mode": "cloud",+ "runtime_config": testutil.Raw("'{}'::jsonb"),+ "runtime_id": runtimeID,+ "visibility": "workspace",+ "max_concurrent_tasks": 1,+ })return agentID}@@ -119,21 +107,16 @@ func createForeignWorkspaceAgent(t *testing.T) string {// deleted (member.user_id ON DELETE CASCADE).func createWorkspaceMemberUser(t *testing.T, name, email string) string {t.Helper()- ctx := context.Background()var userID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`, name, email,- ).Scan(&userID); err != nil {- t.Fatalf("create user %s: %v", email, err)- }+ ).Scan(&userID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })- if _, err := testPool.Exec(ctx,+ dbfx.Exec(t,`INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, testWorkspaceID, userID,- ); err != nil {- t.Fatalf("add member %s: %v", email, err)- }+ )return userID}@@ -213,7 +196,7 @@ func TestCancelTaskByUser_QueuedEditPersistsDraftRestore(t *testing.T) {}var restoreCount int- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT count(*)FROM chat_draft_restoreWHERE id = $1@@ -221,9 +204,7 @@ func TestCancelTaskByUser_QueuedEditPersistsDraftRestore(t *testing.T) {AND task_id = $3AND content = 'edit this queued prompt'AND $4::uuid = ANY(attachment_ids)- `, messageID, sessionID, taskID, attachmentID).Scan(&restoreCount); err != nil {- t.Fatalf("read durable queued edit restore: %v", err)- }+ `, messageID, sessionID, taskID, attachmentID).Scan(&restoreCount)if restoreCount != 1 {t.Fatalf("queued edit created %d durable restore rows", restoreCount)}@@ -265,12 +246,10 @@ func TestCancelTaskByUser_QueuedEditRollsBackOnRestoreFailure(t *testing.T) {sessionID,"do not lose this queued prompt",)- if _, err := testPool.Exec(context.Background(), `+ dbfx.Exec(t, `INSERT INTO chat_draft_restore (id, chat_session_id, task_id, content, attachment_ids)VALUES ($1, $2, $3, 'collision', '{}'::uuid[])- `, messageID, sessionID, taskID); err != nil {- t.Fatalf("seed restore collision: %v", err)- }+ `, messageID, sessionID, taskID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM chat_draft_restore WHERE id = $1`, messageID)})@@ -288,14 +267,12 @@ func TestCancelTaskByUser_QueuedEditRollsBackOnRestoreFailure(t *testing.T) {}var bindingCount int- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT count(*)FROM chat_message AS messageJOIN attachment ON attachment.chat_message_id = message.idWHERE message.id = $1 AND attachment.id = $2- `, messageID, attachmentID).Scan(&bindingCount); err != nil {- t.Fatalf("read rolled back queued input: %v", err)- }+ `, messageID, attachmentID).Scan(&bindingCount)if bindingCount != 1 {t.Fatalf("failed queued edit did not roll back input binding: count = %d", bindingCount)}@@ -328,13 +305,11 @@ func TestCancelTaskByUser_QueuedRemoveDeletesAttachment(t *testing.T) {}var rows int- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT(SELECT count(*) FROM chat_message WHERE id = $1) +(SELECT count(*) FROM attachment WHERE id = $2)- `, messageID, attachmentID).Scan(&rows); err != nil {- t.Fatalf("count discarded queued input rows: %v", err)- }+ `, messageID, attachmentID).Scan(&rows)if rows != 0 {t.Fatalf("queued remove left %d message/attachment rows", rows)}@@ -345,33 +320,27 @@ func TestCancelTaskByUser_QueuedRemoveDeletesAttachment(t *testing.T) {// still empty, plus the user message that triggered it.func createStartedEmptyChatTask(t *testing.T, sessionID, agentID, content string) (taskID, userMessageID string) {t.Helper()- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id, started_at)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2, now())RETURNING id- `, agentID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("create started chat task: %v", err)- }+ `, agentID, sessionID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO chat_message (chat_session_id, role, content, task_id)VALUES ($1, 'user', $2, $3)RETURNING id- `, sessionID, content, taskID).Scan(&userMessageID); err != nil {- t.Fatalf("create linked user chat message: %v", err)- }+ `, sessionID, content, taskID).Scan(&userMessageID)return taskID, userMessageID}func chatFinalizeDeferredAt(t *testing.T, taskID string) *time.Time {t.Helper()var at *time.Time- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1- `, taskID).Scan(&at); err != nil {- t.Fatalf("read chat_finalize_deferred_at: %v", err)- }+ `, taskID).Scan(&at)return at}@@ -413,10 +382,8 @@ func TestCancelTaskByUser_StartedEmptyChat_WithDraftRestoreCapability_Defers(t *// The judgment is deferred, so the user message must still be there for the// daemon ack / sweeper to settle.var count int- if err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&count); err != nil {- t.Fatalf("count user chat message: %v", err)- }+ dbfx.QueryRow(t,+ `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&count)if count != 1 {t.Fatalf("expected the user message to survive the deferral, got %d rows", count)}@@ -457,18 +424,14 @@ func TestCancelTaskByUser_StartedEmptyChat_LegacyClient_StillGetsSynchronousRest// Legacy semantics all the way: the message is settled synchronously, and no// durable restore row is written for a client that could never read it.var messages int- if err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&messages); err != nil {- t.Fatalf("count user chat message: %v", err)- }+ dbfx.QueryRow(t,+ `SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID).Scan(&messages)if messages != 0 {t.Fatalf("expected the user message to be deleted synchronously, got %d rows", messages)}var restores int- if err := testPool.QueryRow(context.Background(),- `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID).Scan(&restores); err != nil {- t.Fatalf("count draft restores: %v", err)- }+ dbfx.QueryRow(t,+ `SELECT count(*) FROM chat_draft_restore WHERE chat_session_id = $1`, sessionID).Scan(&restores)if restores != 0 {t.Fatalf("expected no durable restore for a legacy cancel, got %d", restores)}@@ -527,14 +490,12 @@ func TestCancelTaskByUser_QuickCreate_Succeeds(t *testing.T) {agentID := createHandlerTestAgent(t, "CancelQuickCreateAgent", []byte("[]"))var taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, context)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL,'{"type":"quick_create","workspace_id":"ws","prompt":"do a thing"}'::jsonb)RETURNING id- `, agentID).Scan(&taskID); err != nil {- t.Fatalf("create quick_create task: %v", err)- }+ `, agentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })w := httptest.NewRecorder()@@ -559,14 +520,12 @@ func TestCancelTaskByUser_RetryClone_Autopilot_Succeeds(t *testing.T) {parentID := createAutopilotRunOnlyTask(t, agentID)var cloneID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, autopilot_run_id, parent_task_id, attempt)SELECT agent_id, runtime_id, 'queued', priority, autopilot_run_id, id, 1FROM agent_task_queue WHERE id = $1RETURNING id- `, parentID).Scan(&cloneID); err != nil {- t.Fatalf("create retry clone: %v", err)- }+ `, parentID).Scan(&cloneID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, cloneID) })w := httptest.NewRecorder()@@ -589,22 +548,18 @@ func TestCancelTaskByUser_IssueTask_Succeeds(t *testing.T) {agentID := createHandlerTestAgent(t, "CancelIssueTaskAgent", []byte("[]"))var issueID, taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)VALUES ($1, 'cancel-byid-issue', 'todo', 'medium', $2, 'member', 92001, 0)RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'queued', 0, $2)RETURNING id- `, agentID, issueID).Scan(&taskID); err != nil {- t.Fatalf("create issue task: %v", err)- }+ `, agentID, issueID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })w := httptest.NewRecorder()@@ -622,44 +577,33 @@ func TestCancelTaskByUser_DelegatedFailureRecoveryAcknowledgesSignal(t *testing.t.Skip("database not available")}- ctx := context.Background()agentID := createHandlerTestAgent(t, "CancelRecoveryTaskAgent", []byte("[]"))- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'cancel-recovery-task', 'in_progress', 'medium', $2, 'member', 92004, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "cancel-recovery-task", testutil.Cols{+ "status": "in_progress",+ "priority": "medium",+ "number": 92004,+ })var sourceTaskID, failedTaskID, recoveryCommentID, recoveryTaskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, completed_at)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'completed', 0, now())RETURNING id- `, agentID, issueID).Scan(&sourceTaskID); err != nil {- t.Fatalf("create source task: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, agentID, issueID).Scan(&sourceTaskID)+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, completed_at,delegated_from_task_id, trigger_evidence_kind)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'failed', 0, now(), $3, 'comment')RETURNING id- `, agentID, issueID, sourceTaskID).Scan(&failedTaskID); err != nil {- t.Fatalf("create failed task: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, agentID, issueID, sourceTaskID).Scan(&failedTaskID)+ dbfx.QueryRow(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, source_task_id)VALUES ($1, $2, 'system', $3, 'resume delegated coordination', 'progress_update', $4)RETURNING id- `, issueID, testWorkspaceID, testUserID, failedTaskID).Scan(&recoveryCommentID); err != nil {- t.Fatalf("create recovery comment: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, issueID, testWorkspaceID, testUserID, failedTaskID).Scan(&recoveryCommentID)+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,trigger_evidence_kind, trigger_evidence_ref_id@@ -667,9 +611,7 @@ func TestCancelTaskByUser_DelegatedFailureRecoveryAcknowledgesSignal(t *testing.VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3,'delegated_failure', $4)RETURNING id- `, agentID, issueID, recoveryCommentID, failedTaskID).Scan(&recoveryTaskID); err != nil {- t.Fatalf("create recovery task: %v", err)- }+ `, agentID, issueID, recoveryCommentID, failedTaskID).Scan(&recoveryTaskID)w := httptest.NewRecorder()testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, recoveryTaskID))@@ -678,12 +620,10 @@ func TestCancelTaskByUser_DelegatedFailureRecoveryAcknowledgesSignal(t *testing.}var status stringvar acknowledged bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT status, $2::uuid = ANY(delivered_comment_ids)FROM agent_task_queue WHERE id = $1- `, recoveryTaskID, recoveryCommentID).Scan(&status, &acknowledged); err != nil {- t.Fatalf("read cancelled recovery task: %v", err)- }+ `, recoveryTaskID, recoveryCommentID).Scan(&status, &acknowledged)if status != "cancelled" || !acknowledged {t.Fatalf("cancelled recovery status/ack = %q/%v, want cancelled/true", status, acknowledged)}@@ -701,13 +641,11 @@ func TestCancelTaskByUser_ChatTask_NonCreator_Returns403(t *testing.T) {otherUserID := createWorkspaceMemberUser(t, "Chat Bystander", "[email protected]")var taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2)RETURNING id- `, agentID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("create chat task: %v", err)- }+ `, agentID, sessionID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })w := httptest.NewRecorder()@@ -729,27 +667,21 @@ func TestCancelTaskByUser_ChatTaskWithTranscript_PersistsAssistantSnapshot(t *tesessionID := createHandlerTestChatSession(t, agentID)var taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id, created_at)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2, now() - interval '5 seconds')RETURNING id- `, agentID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("create chat task: %v", err)- }+ `, agentID, sessionID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })- if _, err := testPool.Exec(context.Background(), `+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content, task_id)VALUES ($1, 'user', 'please answer', $2)- `, sessionID, taskID); err != nil {- t.Fatalf("create linked user chat message: %v", err)- }- if _, err := testPool.Exec(context.Background(), `+ `, sessionID, taskID)+ dbfx.Exec(t, `INSERT INTO task_message (task_id, seq, type, content)VALUES ($1, 1, 'text', 'partial answer')- `, taskID); err != nil {- t.Fatalf("create task message: %v", err)- }+ `, taskID)w := httptest.NewRecorder()testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, taskID))@@ -768,13 +700,11 @@ func TestCancelTaskByUser_ChatTaskWithTranscript_PersistsAssistantSnapshot(t *te}var role, content, messageTaskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT role, content, COALESCE(task_id::text, '')FROM chat_messageWHERE chat_session_id = $1 AND role = 'assistant'- `, sessionID).Scan(&role, &content, &messageTaskID); err != nil {- t.Fatalf("read cancelled assistant chat message: %v", err)- }+ `, sessionID).Scan(&role, &content, &messageTaskID)if role != "assistant" || content != "Stopped." || messageTaskID != taskID {t.Fatalf("assistant snapshot mismatch: role=%q content=%q task_id=%q", role, content, messageTaskID)}@@ -789,24 +719,20 @@ func TestCancelTaskByUser_ChatTaskWithoutTranscript_RestoresUserDraft(t *testingsessionID := createHandlerTestChatSession(t, agentID)var taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2)RETURNING id- `, agentID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("create chat task: %v", err)- }+ `, agentID, sessionID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })var userMessageID stringconst userContent = "keep this prompt"- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO chat_message (chat_session_id, role, content, task_id)VALUES ($1, 'user', $2, $3)RETURNING id- `, sessionID, userContent, taskID).Scan(&userMessageID); err != nil {- t.Fatalf("create linked user chat message: %v", err)- }+ `, sessionID, userContent, taskID).Scan(&userMessageID)w := httptest.NewRecorder()testHandler.CancelTaskByUser(w, cancelTaskByUserRequest(t, testUserID, taskID))@@ -827,21 +753,17 @@ func TestCancelTaskByUser_ChatTaskWithoutTranscript_RestoresUserDraft(t *testing}var count int- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_messageWHERE chat_session_id = $1 AND role = 'assistant'- `, sessionID).Scan(&count); err != nil {- t.Fatalf("count assistant chat messages: %v", err)- }+ `, sessionID).Scan(&count)if count != 0 {t.Fatalf("expected no assistant snapshot for empty transcript, got %d", count)}- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_messageWHERE id = $1- `, userMessageID).Scan(&count); err != nil {- t.Fatalf("count deleted user chat message: %v", err)- }+ `, userMessageID).Scan(&count)if count != 0 {t.Fatalf("expected linked user message to be deleted, got %d", count)}@@ -855,15 +777,13 @@ func TestCancelTaskByUser_ChatRetryRestoresRootInput(t *testing.T) {agentID := createHandlerTestAgent(t, "CancelChatRetryAgent", []byte("[]"))sessionID := createHandlerTestChatSession(t, agentID)var rootTaskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id, completed_at)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'completed', 0, $2, now())RETURNING id- `, agentID, sessionID).Scan(&rootTaskID); err != nil {- t.Fatalf("create root chat task: %v", err)- }+ `, agentID, sessionID).Scan(&rootTaskID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, rootTaskID)})@@ -877,16 +797,14 @@ func TestCancelTaskByUser_ChatRetryRestoresRootInput(t *testing.T) {var messageID stringconst content = "restore the retry input"- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO chat_message (chat_session_id, role, content, task_id)VALUES ($1, 'user', $2, $3)RETURNING id- `, sessionID, content, rootTaskID).Scan(&messageID); err != nil {- t.Fatalf("create root chat message: %v", err)- }+ `, sessionID, content, rootTaskID).Scan(&messageID)var retryTaskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id,parent_task_id, retry_of_task_id, chat_input_task_id, attempt@@ -896,9 +814,7 @@ func TestCancelTaskByUser_ChatRetryRestoresRootInput(t *testing.T) {$3, $3, $3, 1)RETURNING id- `, agentID, sessionID, rootTaskID).Scan(&retryTaskID); err != nil {- t.Fatalf("create retry chat task: %v", err)- }+ `, agentID, sessionID, rootTaskID).Scan(&retryTaskID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, retryTaskID)})@@ -953,36 +869,30 @@ func TestCancelTaskByUser_ChatTaskWithBoundAttachment_SurvivesCancelAndRebinds(tsessionID := createHandlerTestChatSession(t, agentID)var taskID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, chat_session_id)VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, NULL, $2)RETURNING id- `, agentID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("create chat task: %v", err)- }+ `, agentID, sessionID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })var userMessageID stringconst userContent = "look at this attachment"- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO chat_message (chat_session_id, role, content, task_id)VALUES ($1, 'user', $2, $3)RETURNING id- `, sessionID, userContent, taskID).Scan(&userMessageID); err != nil {- t.Fatalf("create linked user chat message: %v", err)- }+ `, sessionID, userContent, taskID).Scan(&userMessageID)// Bind an attachment to that user message, exactly as a real send does:// workspace-scoped, uploaded by the session creator, pointing at both the// session and the message.var attachmentID string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `INSERT INTO attachment (workspace_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, chat_session_id, chat_message_id)VALUES ($1, 'member', $2, 'cancel-survive.png', 'https://cdn.example.com/cancel-survive.png', 'image/png', 9, $3, $4)RETURNING id::text- `, testWorkspaceID, testUserID, sessionID, userMessageID).Scan(&attachmentID); err != nil {- t.Fatalf("seed bound attachment: %v", err)- }+ `, testWorkspaceID, testUserID, sessionID, userMessageID).Scan(&attachmentID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID) })// Cancel the empty chat task (no transcript) — this deletes the user message.@@ -1014,20 +924,16 @@ func TestCancelTaskByUser_ChatTaskWithBoundAttachment_SurvivesCancelAndRebinds(t// (a) The row survived the ON DELETE CASCADE: still present, detached from// the deleted message, but still scoped to the session.var count int- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT count(*) FROM attachment WHERE id = $1`, attachmentID,- ).Scan(&count); err != nil {- t.Fatalf("count attachment: %v", err)- }+ ).Scan(&count)if count != 1 {t.Fatalf("attachment was cascade-deleted on cancel: count = %d", count)}var dbMessageID, dbSessionID *string- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT chat_message_id::text, chat_session_id::text FROM attachment WHERE id = $1`, attachmentID,- ).Scan(&dbMessageID, &dbSessionID); err != nil {- t.Fatalf("read attachment after cancel: %v", err)- }+ ).Scan(&dbMessageID, &dbSessionID)if dbMessageID != nil {t.Fatalf("expected chat_message_id detached to NULL, got %q", *dbMessageID)}@@ -1036,11 +942,9 @@ func TestCancelTaskByUser_ChatTaskWithBoundAttachment_SurvivesCancelAndRebinds(t}// Sanity: the empty-cancel still deleted the user message itself.- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT count(*) FROM chat_message WHERE id = $1`, userMessageID,- ).Scan(&count); err != nil {- t.Fatalf("count user message: %v", err)- }+ ).Scan(&count)if count != 0 {t.Fatalf("expected linked user message to be deleted, got %d", count)}@@ -1076,11 +980,9 @@ func TestCancelTaskByUser_ChatTaskWithBoundAttachment_SurvivesCancelAndRebinds(tif !rebound {t.Fatalf("attachment not re-bound on resend: %#v", sendResp.AttachmentIDs)}- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT chat_message_id::text FROM attachment WHERE id = $1`, attachmentID,- ).Scan(&dbMessageID); err != nil {- t.Fatalf("read attachment after resend: %v", err)- }+ ).Scan(&dbMessageID)if dbMessageID == nil || *dbMessageID != sendResp.MessageID {t.Fatalf("expected attachment re-bound to new message %q, got %v", sendResp.MessageID, dbMessageID)}diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.goindex efc89b668b..3c1da1c96a 100644--- a/server/internal/handler/comment_reconcile_test.go+++ b/server/internal/handler/comment_reconcile_test.go@@ -9,6 +9,7 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -32,11 +33,9 @@ func completeTaskViaHandler(t *testing.T, taskID, output string) *httptest.Respofunc pendingTaskCountForAgentIssue(t *testing.T, issueID, agentID string) int {t.Helper()var n int- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')`,- issueID, agentID).Scan(&n); err != nil {- t.Fatalf("count pending tasks: %v", err)- }+ issueID, agentID).Scan(&n)return n}@@ -46,11 +45,9 @@ func pendingTaskCountForAgentIssue(t *testing.T, issueID, agentID string) int {func queuedTaskCountForAgentIssue(t *testing.T, issueID, agentID string) int {t.Helper()var n int- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,- issueID, agentID).Scan(&n); err != nil {- t.Fatalf("count queued tasks: %v", err)- }+ issueID, agentID).Scan(&n)return n}@@ -65,51 +62,37 @@ func TestCompleteTask_ReconcilesMemberCommentPostedDuringRun(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ testWorkspaceID).Scan(&agentID, &runtimeID)// Issue assigned to the agent so a plain member comment routes to it.- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'reconcile-e2e fixture', 'in_progress', 'none', $2, 'member', 999001, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "reconcile-e2e fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999001,+ "assignee_type": "agent",+ "assignee_id": agentID,+ })// Trigger comment created BEFORE the run starts.- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })// A running task whose started_at is in the past.var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })// A deliberate member comment that arrived DURING the run (after started_at).- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'member', $3, 'wait, also handle this', 'comment', now() - interval '1 minute')- `, issueID, testWorkspaceID, testUserID); err != nil {- t.Fatalf("setup: mid-run member comment: %v", err)- }+ `, issueID, testWorkspaceID, testUserID)if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())@@ -131,39 +114,27 @@ func TestCompleteTask_NoReconcileWhenNoNewMemberComment(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'reconcile-negative fixture', 'in_progress', 'none', $2, 'member', 999002, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "reconcile-negative fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999002,+ "assignee_type": "agent",+ "assignee_id": agentID,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'the only request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "the only request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {@@ -191,54 +162,40 @@ func TestCompleteTask_DoesNotReTriggerOtherAgentMentionedDuringRun(t *testing.T)ctx := context.Background()var agentA, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&agentA, &runtimeID); err != nil {- t.Fatalf("setup: get agent A: %v", err)- }+ testWorkspaceID).Scan(&agentA, &runtimeID)// A second, workspace-invocable agent that a member can @mention.agentB := createHandlerTestAgent(t, "Reconcile Other Agent B", nil)// Issue assigned to A so A's completion is the one that reconciles.- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'reconcile-other-agent fixture', 'in_progress', 'none', $2, 'member', 999003, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentA).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "reconcile-other-agent fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999003,+ "assignee_type": "agent",+ "assignee_id": agentA,+ })// A's trigger comment, created before the run starts.- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })// A running task for A whose started_at is in the past.var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id- `, agentA, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentA, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })// A member comment posted DURING A's run that @-mentions agent B.mention := "[@B](mention://agent/" + agentB + ") please take a look"- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'member', $3, $4, 'comment', now() - interval '1 minute')- `, issueID, testWorkspaceID, testUserID, mention); err != nil {- t.Fatalf("setup: mid-run @B comment: %v", err)- }+ `, issueID, testWorkspaceID, testUserID, mention)if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())@@ -282,26 +239,21 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.ctx := context.Background()var runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: get runtime: %v", err)- }+ testWorkspaceID).Scan(&runtimeID)// Two workspace-invocable agents: A authors the mention, B is the target// (and the agent whose run completes / reconciles).agentA := createHandlerTestAgent(t, "Reconcile A2A Author A", nil)agentB := createHandlerTestAgent(t, "Reconcile A2A Target B", nil)// Issue assigned to B so B's completion is the one that reconciles.- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'reconcile-a2a-mention fixture', 'in_progress', 'none', $2, 'member', 999007, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentB).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "reconcile-a2a-mention fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999007,+ "assignee_type": "agent",+ "assignee_id": agentB,+ })t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID) })issue, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(issueID))@@ -310,26 +262,19 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.}// B's trigger comment, created before the run starts.- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })// B's task is DISPATCHED (claim response already built, not yet running) —// the state that makes an incoming mention hit the merge-miss + active-task// drop at creation time.var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'dispatched', 0, now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id- `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: dispatched task: %v", err)- }+ `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })// Agent A posts an explicit @B mention through the real trigger path while@@ -337,13 +282,11 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.// as the CreateComment handler would for an agent-authored comment.var mentionCommentID stringmention := "[@B](mention://agent/" + agentB + ") please also handle this"- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)VALUES ($1, $2, 'agent', $3, $4, 'comment')RETURNING id- `, issueID, testWorkspaceID, agentA, mention).Scan(&mentionCommentID); err != nil {- t.Fatalf("setup: agent @B comment: %v", err)- }+ `, issueID, testWorkspaceID, agentA, mention).Scan(&mentionCommentID)mentionComment, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(mentionCommentID))if err != nil {t.Fatalf("setup: load mention comment: %v", err)@@ -357,9 +300,7 @@ func TestCompleteTask_ReconcilesAgentAuthoredMentionToCompletedAgent(t *testing.}// B's task progresses dispatched → running, then completes.- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '1 minute' WHERE id = $1`, taskID); err != nil {- t.Fatalf("advance task to running: %v", err)- }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '1 minute' WHERE id = $1`, taskID)if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())}@@ -386,50 +327,36 @@ func TestCompleteTask_DoesNotReconcilePlainAgentReply(t *testing.T) {ctx := context.Background()var runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: get runtime: %v", err)- }+ testWorkspaceID).Scan(&runtimeID)agentA := createHandlerTestAgent(t, "Reconcile PlainReply Author A", nil)agentB := createHandlerTestAgent(t, "Reconcile PlainReply Target B", nil)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'reconcile-plain-agent-reply fixture', 'in_progress', 'none', $2, 'member', 999008, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentB).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "reconcile-plain-agent-reply fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999008,+ "assignee_type": "agent",+ "assignee_id": agentB,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes')RETURNING id- `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentB, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })// A plain agent-authored reply during B's run — NO mention of anyone.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'agent', $3, 'thanks, looks good to me', 'comment', now() - interval '1 minute')- `, issueID, testWorkspaceID, agentA); err != nil {- t.Fatalf("setup: plain agent reply: %v", err)- }+ `, issueID, testWorkspaceID, agentA)if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())@@ -457,7 +384,6 @@ func TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue(t *testing.T)if testHandler == nil || testPool == nil {t.Skip("database not available")}- ctx := context.Background()fx := newSquadCommentTriggerFixture(t)issueID := uuidToString(fx.Issue.ID)t.Cleanup(func() {@@ -466,28 +392,25 @@ func TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue(t *testing.T)})var leaderRuntimeID string- if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&leaderRuntimeID); err != nil {- t.Fatalf("setup: load leader runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, fx.LeaderID).Scan(&leaderRuntimeID)// A running leader task whose completion drives reconcile.- var leaderTaskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, squad_id, priority, created_at, started_at)- VALUES ($1, $2, $3, 'running', TRUE, $4, 0, now() - interval '10 minutes', now() - interval '5 minutes')- RETURNING id- `, fx.LeaderID, leaderRuntimeID, issueID, fx.SquadID).Scan(&leaderTaskID); err != nil {- t.Fatalf("setup: leader task: %v", err)- }+ leaderTaskID := dbfx.Task(t, fx.LeaderID, testutil.Cols{+ "runtime_id": leaderRuntimeID,+ "issue_id": issueID,+ "status": "running",+ "is_leader_task": true,+ "squad_id": fx.SquadID,+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ "started_at": testutil.Raw("now() - interval '5 minutes'"),+ })// A plain worker-agent reply (no mention) posted during the leader's run.// At create time this WOULD route to the leader via the squad-leader// fallback; reconcile must not replay it.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'agent', $3, 'done — pushed the change', 'comment', now() - interval '1 minute')- `, issueID, testWorkspaceID, fx.OtherID); err != nil {- t.Fatalf("setup: plain worker reply: %v", err)- }+ `, issueID, testWorkspaceID, fx.OtherID)if w := completeTaskViaHandler(t, leaderTaskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())@@ -504,17 +427,12 @@ func TestCompleteTask_DoesNotReconcilePlainWorkerReplyOnSquadIssue(t *testing.T)// the user id (for a second distinct originator).func handlerWorkspaceMember(t *testing.T, slug string) string {t.Helper()- ctx := context.Background()var userID stringemail := slug + "-" + time.Now().Format("150405.000000") + "@example.test"- if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,- "Reconcile Test "+slug, email).Scan(&userID); err != nil {- t.Fatalf("create user: %v", err)- }- if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`,- testWorkspaceID, userID); err != nil {- t.Fatalf("create member: %v", err)- }+ dbfx.QueryRow(t, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,+ "Reconcile Test "+slug, email).Scan(&userID)+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`,+ testWorkspaceID, userID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM member WHERE user_id = $1`, userID)testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)@@ -539,21 +457,17 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {ctx := context.Background()var agentID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL ORDER BY created_at ASC LIMIT 1`,- testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ testWorkspaceID).Scan(&agentID)userB := handlerWorkspaceMember(t, "originatorB")- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'diff-originator fixture', 'in_progress', 'none', $2, 'member', 999004, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }+ issueID := dbfx.Issue(t, "diff-originator fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999004,+ "assignee_type": "agent",+ "assignee_id": agentID,+ })t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)testPool.Exec(ctx, `DELETE FROM comment WHERE issue_id = $1`, issueID)@@ -567,13 +481,9 @@ func TestConsecutiveCommentsDifferentOriginatorsFullEnqueuePath(t *testing.T) {insertMemberComment := func(authorID, content string) db.Comment {t.Helper()- var id string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, $4, 'comment') RETURNING id- `, issueID, testWorkspaceID, authorID, content).Scan(&id); err != nil {- t.Fatalf("insert comment: %v", err)- }+ id := dbfx.Comment(t, issueID, content, testutil.Cols{+ "author_id": authorID,+ })c, err := testHandler.Queries.GetComment(ctx, util.MustParseUUID(id))if err != nil {t.Fatalf("load comment: %v", err)@@ -622,51 +532,37 @@ func TestCompleteTask_ReconcilesDispatchedWindowComment(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'dispatched-window fixture', 'in_progress', 'none', $2, 'member', 999005, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "dispatched-window fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999005,+ "assignee_type": "agent",+ "assignee_id": agentID,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)- VALUES ($1, $2, 'member', $3, 'initial request', 'comment', now() - interval '10 minutes')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "initial request", testutil.Cols{+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ })// Running task: dispatched 5m ago, started 2m ago. The claim response was// built at dispatch.var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, delivered_comment_ids, status, priority, created_at, dispatched_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$4::uuid], 'running', 0, now() - interval '10 minutes', now() - interval '5 minutes', now() - interval '2 minutes')RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })// A member comment in the dispatch→start window: after dispatched_at// (5m ago), before started_at (2m ago). A started_at anchor would miss it.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'member', $3, 'squeezed in before start', 'comment', now() - interval '3 minutes')- `, issueID, testWorkspaceID, testUserID); err != nil {- t.Fatalf("setup: dispatch-window comment: %v", err)- }+ `, issueID, testWorkspaceID, testUserID)if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())@@ -683,7 +579,7 @@ func taskTriggerOriginatorCoalesced(t *testing.T, issueID, agentID string) (strit.Helper()var trigger, originator stringvar coalesced []string- if err := testPool.QueryRow(context.Background(), `+ dbfx.QueryRow(t, `SELECT COALESCE(trigger_comment_id::text, ''),COALESCE(originator_user_id::text, ''),coalesced_comment_ids::text[]@@ -691,9 +587,7 @@ func taskTriggerOriginatorCoalesced(t *testing.T, issueID, agentID string) (striWHERE issue_id = $1 AND agent_id = $2ORDER BY created_at DESCLIMIT 1- `, issueID, agentID).Scan(&trigger, &originator, &coalesced); err != nil {- t.Fatalf("read task trigger/originator/coalesced: %v", err)- }+ `, issueID, agentID).Scan(&trigger, &originator, &coalesced)return trigger, originator, coalesced}@@ -721,21 +615,16 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,- testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)- VALUES ($1, 'pre-dispatch race fixture', 'in_progress', 'none', $2, 'member', 999006, 0, 'agent', $3)- RETURNING id- `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "pre-dispatch race fixture", testutil.Cols{+ "status": "in_progress",+ "number": 999006,+ "assignee_type": "agent",+ "assignee_id": agentID,+ })// Timeline: task created 10m ago; the run's trigger 10m ago; a delivered// pre-claim coalesced comment 8m ago; the RACE comment 7m ago (still before@@ -743,12 +632,10 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {insertComment := func(content, age string) string {t.Helper()var id string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'member', $3, $4, 'comment', now() - $5::interval) RETURNING id- `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id); err != nil {- t.Fatalf("insert comment: %v", err)- }+ `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id)return id}triggerCommentID := insertComment("initial request", "10 minutes")@@ -759,15 +646,13 @@ func TestCompleteTask_ReconcilesPreDispatchMergeRaceComment(t *testing.T) {// comment recorded in coalesced_comment_ids, dispatched after the race// comment, started later still.var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue(agent_id, runtime_id, issue_id, trigger_comment_id, coalesced_comment_ids, delivered_comment_ids, status, priority, created_at, dispatched_at, started_at)VALUES ($1, $2, $3, $4, ARRAY[$5::uuid], ARRAY[$4::uuid, $5::uuid], 'running', 0,now() - interval '10 minutes', now() - interval '6 minutes', now() - interval '5 minutes')RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID, deliveredCoalescedID).Scan(&taskID); err != nil {- t.Fatalf("setup: running task: %v", err)- }+ `, agentID, runtimeID, issueID, triggerCommentID, deliveredCoalescedID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {@@ -811,24 +696,20 @@ func TestCompleteTask_ReconcilesPlannedButUndeliveredComments(t *testing.T) {ctx := context.Background()runtimeID := createClaimReclaimRuntime(t, ctx, "Planned undelivered runtime "+tc.name)agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Planned undelivered agent "+tc.name)- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE issueSET assignee_type = 'agent', assignee_id = $2WHERE id = $1- `, issueID, agentID); err != nil {- t.Fatalf("assign issue: %v", err)- }+ `, issueID, agentID)insertComment := func(content, age string) string {t.Helper()var id string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, created_at)VALUES ($1, $2, 'member', $3, $4, 'comment', now() - $5::interval)RETURNING id- `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id); err != nil {- t.Fatalf("insert comment: %v", err)- }+ `, issueID, testWorkspaceID, testUserID, content, age).Scan(&id)return id}old1 := insertComment("planned old one", "10 minutes")@@ -840,7 +721,7 @@ func TestCompleteTask_ReconcilesPlannedButUndeliveredComments(t *testing.T) {}var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id,coalesced_comment_ids, delivered_comment_ids,@@ -852,9 +733,7 @@ func TestCompleteTask_ReconcilesPlannedButUndeliveredComments(t *testing.T) {'running', 0, now() - interval '5 minutes', now() - interval '4 minutes', now() - interval '3 minutes')RETURNING id- `, agentID, runtimeID, issueID, trigger, old1, old2, delivered).Scan(&taskID); err != nil {- t.Fatalf("insert running task: %v", err)- }+ `, agentID, runtimeID, issueID, trigger, old1, old2, delivered).Scan(&taskID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)})diff --git a/server/internal/handler/daemon_claim_cancelled_session_test.go b/server/internal/handler/daemon_claim_cancelled_session_test.goindex 1eb3de02b6..9959d1e1b4 100644--- a/server/internal/handler/daemon_claim_cancelled_session_test.go+++ b/server/internal/handler/daemon_claim_cancelled_session_test.go@@ -13,6 +13,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -39,31 +40,21 @@ func TestClaimTask_ChatResumesCancelledTurnSession(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)// A brand-new chat: no resume pointer of its own yet.- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)- VALUES ($1, $2, $3, 'cancelled first turn')- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancelled first turn",+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at, session_id, work_dir)VALUES ($1, $2, $3, 'cancelled', 0, now(), now(), 'cancelled-turn-session', '/tmp/cancelled-turn-workdir')- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create cancelled chat task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, chatSessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create follow-up chat task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "cancelled-turn-session" {@@ -85,43 +76,31 @@ func TestClaimTask_ChatCancelledSessionStaysExcludedWhenRetired(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)- VALUES ($1, $2, $3, 'cancelled retired turn')- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancelled retired turn",+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at, session_id, work_dir)VALUES ($1, $2, $3, 'cancelled', 0, now() - interval '5 minutes', now() - interval '4 minutes','retired-cancelled-session', '/tmp/retired-cancelled-workdir')- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create cancelled chat task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)// A later run resumed that session, could not use it, and retired it.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at, retired_session_id)VALUES ($1, $2, $3, 'completed', 0, now() - interval '2 minutes', now() - interval '1 minutes','retired-cancelled-session')- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create retiring chat task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, chatSessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create follow-up chat task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "" {@@ -139,31 +118,22 @@ func TestClaimTask_IssueResumesCancelledTaskSession(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'cancelled issue run fixture', 'in_progress', 'none', $2, 'member', 86340, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "cancelled issue run fixture", testutil.Cols{+ "status": "in_progress",+ "number": 86340,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, started_at, completed_at, session_id, work_dir)VALUES ($1, $2, $3, 'cancelled', 0, now(), now(), 'cancelled-issue-session', '/tmp/cancelled-issue-workdir')- `, agentID, runtimeID, issueID); err != nil {- t.Fatalf("setup: create cancelled issue task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, issueID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, issueID); err != nil {- t.Fatalf("setup: create follow-up issue task: %v", err)- }+ `, agentID, runtimeID, issueID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "cancelled-issue-session" {@@ -186,32 +156,22 @@ func TestCancelTask_AdvancesChatSessionResumePointer(t *testing.T) {ctx := context.Background()agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'cancel advances pointer', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel advances pointer",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })// Turn 2 is running and has already pinned its own session id.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, session_id, work_dir- )- VALUES ($1, $2, $3, 'running', 0, now(), 'turn2-session', '/tmp/turn2-workdir')- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "session_id": "turn2-session",+ "work_dir": "/tmp/turn2-workdir",+ })if _, err := testHandler.TaskService.CancelTaskWithResult(ctx, parseUUID(taskID),service.CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {@@ -219,11 +179,9 @@ func TestCancelTask_AdvancesChatSessionResumePointer(t *testing.T) {}var sessionID, workDir, pointerRuntimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT session_id, work_dir, runtime_id FROM chat_session WHERE id = $1- `, chatSessionID).Scan(&sessionID, &workDir, &pointerRuntimeID); err != nil {- t.Fatalf("read chat session pointer: %v", err)- }+ `, chatSessionID).Scan(&sessionID, &workDir, &pointerRuntimeID)if sessionID != "turn2-session" {t.Fatalf("chat_session.session_id = %q, want turn2-session (the cancelled turn owns the newest session)", sessionID)}@@ -246,28 +204,19 @@ func TestCancelTask_KeepsChatPointerWhenNoSessionEstablished(t *testing.T) {ctx := context.Background()agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'cancel keeps pointer', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel keeps pointer",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at)- VALUES ($1, $2, $3, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })if _, err := testHandler.TaskService.CancelTaskWithResult(ctx, parseUUID(taskID),service.CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {@@ -275,11 +224,9 @@ func TestCancelTask_KeepsChatPointerWhenNoSessionEstablished(t *testing.T) {}var sessionID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT session_id FROM chat_session WHERE id = $1- `, chatSessionID).Scan(&sessionID); err != nil {- t.Fatalf("read chat session pointer: %v", err)- }+ `, chatSessionID).Scan(&sessionID)if sessionID != "turn1-session" {t.Fatalf("chat_session.session_id = %q, want turn1-session (a session-less cancel must not touch the pointer)", sessionID)}@@ -302,39 +249,27 @@ func TestCancelTask_PointerAdvanceIsAtomicWithStatusFlip(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'cancel atomicity', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel atomicity",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, session_id, work_dir- )- VALUES ($1, $2, $3, 'running', 0, now(), 'turn2-session', '/tmp/turn2-workdir')- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "session_id": "turn2-session",+ "work_dir": "/tmp/turn2-workdir",+ })// The follow-up the user queued while the turn was still running.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create queued follow-up: %v", err)- }+ `, agentID, runtimeID, chatSessionID)// Hold the chat row from another connection so the pointer write blocks.blockTx := beginWarmedTx(t, ctx)@@ -371,9 +306,7 @@ func TestCancelTask_PointerAdvanceIsAtomicWithStatusFlip(t *testing.T) {}var pointer string- if err := testPool.QueryRow(ctx, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer); err != nil {- t.Fatalf("read chat session pointer: %v", err)- }+ dbfx.QueryRow(t, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer)if pointer != "turn2-session" {t.Fatalf("chat_session.session_id = %q, want turn2-session", pointer)}@@ -401,41 +334,28 @@ func TestPinTaskSession_LateCancelledPinAdvancesChatPointer(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'late pin', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "late pin",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })// Cancelled before the backend revealed its session.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, completed_at- )- VALUES ($1, $2, $3, 'cancelled', 0, now(), now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create cancelled chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "cancelled",+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ })pinTaskSessionViaAPI(t, taskID, daemonID, "turn2-session", "/tmp/turn2-workdir")- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create follow-up chat task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "turn2-session" {@@ -457,35 +377,24 @@ func TestPinTaskSession_LateCancelledPinYieldsToNewerTurn(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'late pin yields', 'turn3-session', '/tmp/turn3-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "late pin yields",+ "session_id": "turn3-session",+ "work_dir": "/tmp/turn3-workdir",+ "runtime_id": runtimeID,+ })- var cancelledID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, created_at, started_at, completed_at- )- VALUES ($1, $2, $3, 'cancelled', 0, now() - interval '10 minutes',- now() - interval '10 minutes', now() - interval '9 minutes')- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&cancelledID); err != nil {- t.Fatalf("setup: create cancelled chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, cancelledID) })+ cancelledID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "cancelled",+ "created_at": testutil.Raw("now() - interval '10 minutes'"),+ "started_at": testutil.Raw("now() - interval '10 minutes'"),+ "completed_at": testutil.Raw("now() - interval '9 minutes'"),+ })// A newer turn already ran to completion and owns the pointer.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, created_at, started_at, completed_at, session_id, work_dir@@ -493,16 +402,12 @@ func TestPinTaskSession_LateCancelledPinYieldsToNewerTurn(t *testing.T) {VALUES ($1, $2, $3, 'completed', 0, now() - interval '2 minutes',now() - interval '2 minutes', now() - interval '1 minutes','turn3-session', '/tmp/turn3-workdir')- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create newer completed task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)pinTaskSessionViaAPI(t, cancelledID, daemonID, "turn2-session", "/tmp/turn2-workdir")var pointer string- if err := testPool.QueryRow(ctx, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer); err != nil {- t.Fatalf("read chat session pointer: %v", err)- }+ dbfx.QueryRow(t, `SELECT session_id FROM chat_session WHERE id = $1`, chatSessionID).Scan(&pointer)if pointer != "turn3-session" {t.Fatalf("chat_session.session_id = %q, want turn3-session (a straggler pin must not rewind a newer turn)", pointer)}@@ -520,38 +425,25 @@ func TestPinTaskSession_PointerAdvanceIsAtomicWithPin(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'pin atomicity', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "pin atomicity",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, completed_at- )- VALUES ($1, $2, $3, 'cancelled', 0, now(), now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create cancelled chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "cancelled",+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create queued follow-up: %v", err)- }+ `, agentID, runtimeID, chatSessionID)blockTx := beginWarmedTx(t, ctx)if _, err := blockTx.Exec(ctx, `SELECT id FROM chat_session WHERE id = $1 FOR UPDATE`, chatSessionID); err != nil {@@ -618,31 +510,21 @@ func TestCancelTask_TakesChatSessionLockBeforeTask(t *testing.T) {ctx := context.Background()agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'cancel lock order', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel lock order",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, session_id, work_dir- )- VALUES ($1, $2, $3, 'running', 0, now(), 'turn2-session', '/tmp/turn2-workdir')- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "session_id": "turn2-session",+ "work_dir": "/tmp/turn2-workdir",+ })// Both transactions are opened and warmed BEFORE anything is locked: a// connection taken mid-hold can queue behind a sibling package's DDL.@@ -701,29 +583,21 @@ func TestCancelTask_ConcurrentWithChatSessionDelete(t *testing.T) {agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)for i := 0; i < 12; i++ {- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'cancel vs delete', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel vs delete",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id,- status, priority, started_at, session_id, work_dir- )- VALUES ($1, $2, $3, 'running', 0, now(), 'turn2-session', '/tmp/turn2-workdir')- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "session_id": "turn2-session",+ "work_dir": "/tmp/turn2-workdir",+ })start := make(chan struct{})cancelErr := make(chan error, 1)@@ -787,30 +661,19 @@ func TestTerminalReports_TakeChatSessionLockBeforeTask(t *testing.T) {ctx := context.Background()agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'report lock order', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })-- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id, status, priority, started_at- )- VALUES ($1, $2, $3, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "report lock order",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })++ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })// Opened and warmed before anything is locked; see beginWarmedTx.holderTx := beginWarmedTx(t, ctx)@@ -913,28 +776,19 @@ func TestCancelAndPin_ConcurrentWithTerminalReport(t *testing.T) {for _, c := range contenders {t.Run(c.name, func(t *testing.T) {for i := 0; i < 12; i++ {- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'race', 'turn1-session', '/tmp/turn1-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }-- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, chat_session_id, status, priority, started_at- )- VALUES ($1, $2, $3, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create running chat task: %v", err)- }+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "race",+ "session_id": "turn1-session",+ "work_dir": "/tmp/turn1-workdir",+ "runtime_id": runtimeID,+ })++ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })start := make(chan struct{})firstErr := make(chan error, 1)@@ -1080,24 +934,20 @@ func TestPinTaskSession_LateCancelledPin(t *testing.T) {if sessionID != "" {session = sessionID}- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, started_at, completed_at, session_id)VALUES ($1, $2, $3, 0, now(), now(), $4)RETURNING id- `, agentID, runtimeID, status, session).Scan(&id); err != nil {- t.Fatalf("setup: create %s task: %v", status, err)- }+ `, agentID, runtimeID, status, session).Scan(&id)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, id) })return id}readSession := func(taskID string) string {t.Helper()var sessionID *string- if err := testPool.QueryRow(ctx, `SELECT session_id FROM agent_task_queue WHERE id = $1`, taskID).Scan(&sessionID); err != nil {- t.Fatalf("read task session: %v", err)- }+ dbfx.QueryRow(t, `SELECT session_id FROM agent_task_queue WHERE id = $1`, taskID).Scan(&sessionID)if sessionID == nil {return ""}diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex f872877e39..ca73ebc83f 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -20,6 +20,7 @@ import ("github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/remotemcp"@@ -97,13 +98,9 @@ func setHandlerTestWorkspaceRepos(t *testing.T, repos []map[string]string) {if err != nil {t.Fatalf("marshal repos: %v", err)}- if _, err := testPool.Exec(context.Background(), `UPDATE workspace SET repos = $1 WHERE id = $2`, data, testWorkspaceID); err != nil {- t.Fatalf("update workspace repos: %v", err)- }+ dbfx.Exec(t, `UPDATE workspace SET repos = $1 WHERE id = $2`, data, testWorkspaceID)t.Cleanup(func() {- if _, err := testPool.Exec(context.Background(), `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte("[]"), testWorkspaceID); err != nil {- t.Fatalf("reset workspace repos: %v", err)- }+ dbfx.Exec(t, `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte("[]"), testWorkspaceID)})}@@ -148,17 +145,10 @@ func TestRemoteMCPDaemonTokenForClaim(t *testing.T) {}func TestListDaemonWorkspaces_UserScopedAndConditional(t *testing.T) {- w := httptest.NewRecorder()- req := newRequest(http.MethodGet, "/api/daemon/workspaces", nil)- testHandler.ListDaemonWorkspaces(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListDaemonWorkspaces: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ListDaemonWorkspaces, newRequest(http.MethodGet, "/api/daemon/workspaces", nil)).Want(http.StatusOK)var workspaces []DaemonWorkspaceResponse- if err := json.NewDecoder(w.Body).Decode(&workspaces); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&workspaces)if len(workspaces) == 0 {t.Fatal("expected at least one daemon workspace")}@@ -170,30 +160,19 @@ func TestListDaemonWorkspaces_UserScopedAndConditional(t *testing.T) {t.Fatal("expected ETag")}- w = httptest.NewRecorder()- req = newRequest(http.MethodGet, "/api/daemon/workspaces", nil)+ req := newRequest(http.MethodGet, "/api/daemon/workspaces", nil)req.Header.Set("If-None-Match", etag)- testHandler.ListDaemonWorkspaces(w, req)- if w.Code != http.StatusNotModified {- t.Fatalf("conditional ListDaemonWorkspaces: expected 304, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ListDaemonWorkspaces, req).Want(http.StatusNotModified)if w.Body.Len() != 0 {t.Fatalf("expected empty 304 body, got %q", w.Body.String())}}func TestListDaemonWorkspaces_DaemonTokenIsWorkspaceScoped(t *testing.T) {- w := httptest.NewRecorder()- req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/workspaces", nil, testWorkspaceID, "daemon-test")- testHandler.ListDaemonWorkspaces(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListDaemonWorkspaces: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ListDaemonWorkspaces, newDaemonTokenRequest(http.MethodGet, "/api/daemon/workspaces", nil, testWorkspaceID, "daemon-test")).Want(http.StatusOK)var workspaces []DaemonWorkspaceResponse- if err := json.NewDecoder(w.Body).Decode(&workspaces); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&workspaces)if len(workspaces) != 1 || workspaces[0].ID != testWorkspaceID {t.Fatalf("daemon-token workspaces = %+v, want only %s", workspaces, testWorkspaceID)}@@ -202,18 +181,9 @@ func TestListDaemonWorkspaces_DaemonTokenIsWorkspaceScoped(t *testing.T) {func createClaimReclaimRuntime(t *testing.T, ctx context.Context, name string) string {t.Helper()- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider,- status, device_info, metadata, last_seen_at, visibility, owner_id- )- VALUES ($1, NULL, $2, 'cloud', 'handler_test_runtime', 'online', 'claim reclaim fixture', '{}'::jsonb, now(), 'private', $3)- RETURNING id- `, testWorkspaceID, name, testUserID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: create runtime: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })+ runtimeID := dbfx.Runtime(t, name, testutil.Cols{+ "device_info": "claim reclaim fixture",+ })return runtimeID}@@ -221,21 +191,10 @@ func createClaimReclaimRuntime(t *testing.T, ctx context.Context, name string) sfunc createClaimReclaimAgentAndIssue(t *testing.T, ctx context.Context, runtimeID, name string) (string, string) {t.Helper()- var agentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent (- workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks, owner_id- )- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)- RETURNING id- `, testWorkspaceID, name, runtimeID, testUserID).Scan(&agentID); err != nil {- t.Fatalf("setup: create agent: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })+ agentID := dbfx.Agent(t, name, runtimeID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)VALUES ($1, $2, 'in_progress', 'none', $3, 'member',@@ -243,9 +202,7 @@ func createClaimReclaimAgentAndIssue(t *testing.T, ctx context.Context, runtimeI0)RETURNING id- `, testWorkspaceID, name+" issue", testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }+ `, testWorkspaceID, name+" issue", testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })return agentID, issueID@@ -255,15 +212,13 @@ func createDispatchedClaimFixtureTask(t *testing.T, ctx context.Context, agentIDt.Helper()var taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, dispatched_at, started_at)VALUES ($1, $2, $3, 'dispatched', 0, now() - ($4::interval), CASE WHEN $5::boolean THEN now() ELSE NULL END)RETURNING id- `, agentID, runtimeID, issueID, dispatchedAge, started).Scan(&taskID); err != nil {- t.Fatalf("setup: create dispatched task: %v", err)- }+ `, agentID, runtimeID, issueID, dispatchedAge, started).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })return taskID@@ -271,13 +226,11 @@ func createDispatchedClaimFixtureTask(t *testing.T, ctx context.Context, agentIDfunc setTaskPrepareLeaseForTest(t *testing.T, ctx context.Context, taskID, expiresIn string) {t.Helper()- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queueSET prepare_lease_expires_at = now() + ($2::interval)WHERE id = $1- `, taskID, expiresIn); err != nil {- t.Fatalf("setup: set prepare lease: %v", err)- }+ `, taskID, expiresIn)}func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {@@ -285,24 +238,17 @@ func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {}, string) {t.Helper()- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,testWorkspaceID, "claim-reclaim-review")req = withURLParam(req, "runtimeId", runtimeID)-- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {ID string `json:"id"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)return resp.Task, w.Body.String()}@@ -312,15 +258,10 @@ func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {func claimChatIntroForTest(t *testing.T, runtimeID string) (string, bool, string) {t.Helper()- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,testWorkspaceID, "chat-intro-review")req = withURLParam(req, "runtimeId", runtimeID)-- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {@@ -328,9 +269,7 @@ func claimChatIntroForTest(t *testing.T, runtimeID string) (string, bool, stringChatIntro bool `json:"chat_intro"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatalf("expected a claimable task, got none: %s", w.Body.String())}@@ -352,30 +291,19 @@ func TestClaimTaskByRuntime_ChatIntroGateClearsAfterUserReplies(t *testing.T) {agentID, _ := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Chat intro gate agent")// Allow more than one in-flight task so the second claim isn't blocked by// the first (which stays 'dispatched') on the concurrency limit.- if _, err := testPool.Exec(ctx, `UPDATE agent SET max_concurrent_tasks = 5 WHERE id = $1`, agentID); err != nil {- t.Fatalf("raise max_concurrent_tasks: %v", err)- }+ dbfx.Exec(t, `UPDATE agent SET max_concurrent_tasks = 5 WHERE id = $1`, agentID)- var sessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status, runtime_id, is_agent_intro)- VALUES ($1, $2, $3, '👋 intro', 'active', $4, true)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&sessionID); err != nil {- t.Fatalf("insert intro chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "👋 intro",+ "runtime_id": runtimeID,+ "is_agent_intro": true,+ })seedQueuedChatTask := func() string {- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id)- VALUES ($1, $2, 'queued', 0, $3)- RETURNING id- `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {- t.Fatalf("seed queued chat task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": sessionID,+ })return taskID}@@ -391,17 +319,13 @@ func TestClaimTaskByRuntime_ChatIntroGateClearsAfterUserReplies(t *testing.T) {// The intro run finishes. Chat tasks serialize on chat_session_id, so the// next turn only becomes claimable once this one leaves an in-flight state.- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, introTaskID); err != nil {- t.Fatalf("complete intro task: %v", err)- }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed' WHERE id = $1`, introTaskID)// The creator replies: persist a user message on the same session.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content)VALUES ($1, 'user', 'thanks! can you help me with X?')- `, sessionID); err != nil {- t.Fatalf("insert user reply: %v", err)- }+ `, sessionID)// Second turn on the same is_agent_intro session must NOT re-introduce.followupTaskID := seedQueuedChatTask()@@ -433,13 +357,11 @@ func TestClaimTaskByRuntime_ReclaimsStaleDispatchedTask(t *testing.T) {}var refreshed bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT dispatched_at > now() - interval '15 seconds'FROM agent_task_queueWHERE id = $1- `, taskID).Scan(&refreshed); err != nil {- t.Fatalf("load refreshed dispatched_at: %v", err)- }+ `, taskID).Scan(&refreshed)if !refreshed {t.Fatal("expected reclaimed task to refresh dispatched_at")}@@ -461,13 +383,11 @@ func TestClaimTaskByRuntime_DoesNotReclaimFreshDispatchedTask(t *testing.T) {}var stillFresh bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT dispatched_at < now() - interval '70 seconds'FROM agent_task_queueWHERE id = $1- `, taskID).Scan(&stillFresh); err != nil {- t.Fatalf("load fresh dispatched task: %v", err)- }+ `, taskID).Scan(&stillFresh)if !stillFresh {t.Fatal("expected fresh dispatched task to keep its original dispatched_at")}@@ -490,13 +410,11 @@ func TestClaimTaskByRuntime_DoesNotReclaimActivePrepareLease(t *testing.T) {}var leaseActive bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT prepare_lease_expires_at > now()FROM agent_task_queueWHERE id = $1- `, taskID).Scan(&leaseActive); err != nil {- t.Fatalf("load active prepare lease: %v", err)- }+ `, taskID).Scan(&leaseActive)if !leaseActive {t.Fatal("expected prepare lease to remain active")}@@ -522,13 +440,11 @@ func TestClaimTaskByRuntime_ReclaimsExpiredPrepareLease(t *testing.T) {}var leaseRefreshed bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT prepare_lease_expires_at > now()FROM agent_task_queueWHERE id = $1- `, taskID).Scan(&leaseRefreshed); err != nil {- t.Fatalf("load refreshed prepare lease: %v", err)- }+ `, taskID).Scan(&leaseRefreshed)if !leaseRefreshed {t.Fatal("expected reclaimed task to refresh prepare lease")}@@ -545,32 +461,22 @@ func TestExtendTaskPrepareLease(t *testing.T) {agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Extend prepare lease agent")taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+otherRuntimeID+"/tasks/"+taskID+"/prepare-lease", nil,testWorkspaceID, "extend-prepare-lease")req = withURLParams(req, "runtimeId", otherRuntimeID, "taskId", taskID)- testHandler.ExtendTaskPrepareLease(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("ExtendTaskPrepareLease wrong runtime: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.ExtendTaskPrepareLease, req).Want(http.StatusNotFound)- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/prepare-lease", nil,testWorkspaceID, "extend-prepare-lease")req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)- testHandler.ExtendTaskPrepareLease(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ExtendTaskPrepareLease: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.ExtendTaskPrepareLease, req).Want(http.StatusOK)var leaseActive bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT prepare_lease_expires_at > now()FROM agent_task_queueWHERE id = $1- `, taskID).Scan(&leaseActive); err != nil {- t.Fatalf("load extended prepare lease: %v", err)- }+ `, taskID).Scan(&leaseActive)if !leaseActive {t.Fatal("expected prepare lease to be extended")}@@ -592,13 +498,11 @@ func TestClaimTaskByRuntime_DoesNotReclaimAlreadyStartedTask(t *testing.T) {}var startedAtValid bool- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT started_at IS NOT NULLFROM agent_task_queueWHERE id = $1- `, taskID).Scan(&startedAtValid); err != nil {- t.Fatalf("load started dispatched task: %v", err)- }+ `, taskID).Scan(&startedAtValid)if !startedAtValid {t.Fatal("expected started dispatched task to keep started_at")}@@ -621,13 +525,11 @@ func TestClaimTaskByRuntime_DoesNotReclaimDifferentRuntimeTask(t *testing.T) {}var runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT runtime_id::textFROM agent_task_queueWHERE id = $1- `, taskID).Scan(&runtimeID); err != nil {- t.Fatalf("load other-runtime dispatched task: %v", err)- }+ `, taskID).Scan(&runtimeID)if runtimeID != owningRuntimeID {t.Fatalf("task runtime_id = %s, want %s", runtimeID, owningRuntimeID)}@@ -642,51 +544,36 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {runtimeID := createClaimReclaimRuntime(t, ctx, "Skill refs runtime")agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Skill refs agent")- var skillID string- if err := testPool.QueryRow(ctx, `- INSERT INTO skill (workspace_id, name, description, content, config, created_by)- VALUES ($1, 'deploy-skill-ref-test', 'Deploy safely', 'main skill content', '{}'::jsonb, $2)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&skillID); err != nil {- t.Fatalf("setup: create skill: %v", err)- }+ skillID := dbfx.Insert(t, "skill", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "name": "deploy-skill-ref-test",+ "description": "Deploy safely",+ "content": "main skill content",+ "config": testutil.Raw("'{}'::jsonb"),+ "created_by": testUserID,+ })t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM agent_skill WHERE skill_id = $1`, skillID)testPool.Exec(ctx, `DELETE FROM skill_file WHERE skill_id = $1`, skillID)testPool.Exec(ctx, `DELETE FROM skill WHERE id = $1`, skillID)})- if _, err := testPool.Exec(ctx, `INSERT INTO skill_file (skill_id, path, content) VALUES ($1, 'rules.md', 'rules content')`, skillID); err != nil {- t.Fatalf("setup: create skill file: %v", err)- }- if _, err := testPool.Exec(ctx, `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`, agentID, skillID); err != nil {- t.Fatalf("setup: bind skill: %v", err)- }+ dbfx.Exec(t, `INSERT INTO skill_file (skill_id, path, content) VALUES ($1, 'rules.md', 'rules content')`, skillID)+ dbfx.Exec(t, `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`, agentID, skillID)- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)- VALUES ($1, $2, $3, 'queued', 0)- RETURNING id- `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {- t.Fatalf("setup: create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ })- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "skill-refs-daemon")req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilitySkillBundlesV1)req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var claimResp struct {Task *AgentTaskResponse `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &claimResp); err != nil {- t.Fatalf("decode claim: %v", err)- }+ w.JSON(&claimResp)if claimResp.Task == nil || claimResp.Task.Agent == nil {t.Fatalf("missing task agent in response: %s", w.Body.String())}@@ -705,60 +592,38 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {}staleHashBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: "sha256:stale"}}}- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", staleHashBody, testWorkspaceID, "skill-refs-daemon")req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)- testHandler.ResolveTaskSkillBundles(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ResolveTaskSkillBundles with stale hash: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)var staleHashResp struct {Bundles []service.AgentSkillData `json:"bundles"`}- if err := json.Unmarshal(w.Body.Bytes(), &staleHashResp); err != nil {- t.Fatalf("decode stale hash resolve: %v", err)- }+ w.JSON(&staleHashResp)if len(staleHashResp.Bundles) != 1 || staleHashResp.Bundles[0].Hash != ref.Hash {t.Fatalf("stale hash resolve did not return current bundle: %+v", staleHashResp.Bundles)}invalidRefBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source}}}- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", invalidRefBody, testWorkspaceID, "skill-refs-daemon")req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)- testHandler.ResolveTaskSkillBundles(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("ResolveTaskSkillBundles with invalid ref: expected 400, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusBadRequest)resolveBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: ref.Hash}}}- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)- testHandler.ResolveTaskSkillBundles(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ResolveTaskSkillBundles: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)var resolveResp struct {Bundles []service.AgentSkillData `json:"bundles"`}- if err := json.Unmarshal(w.Body.Bytes(), &resolveResp); err != nil {- t.Fatalf("decode resolve: %v", err)- }+ w.JSON(&resolveResp)if len(resolveResp.Bundles) != 1 || resolveResp.Bundles[0].Content != "main skill content" || len(resolveResp.Bundles[0].Files) != 1 || resolveResp.Bundles[0].Files[0].Content != "rules content" {t.Fatalf("unexpected resolved bundles: %+v", resolveResp.Bundles)}- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID); err != nil {- t.Fatalf("setup: mark task running: %v", err)- }- w = httptest.NewRecorder()+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID)req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)- testHandler.ResolveTaskSkillBundles(w, req)- if w.Code != http.StatusConflict {- t.Fatalf("ResolveTaskSkillBundles for running task: expected 409, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusConflict)}// TestClaimTaskByRuntime_PopulatesWorkspaceContext verifies the claim@@ -774,12 +639,8 @@ func TestClaimTaskByRuntime_PopulatesWorkspaceContext(t *testing.T) {ctx := context.Background()const wsContext = "All comments must be in English. Prefer concise PR descriptions."var prior string- if err := testPool.QueryRow(ctx, `SELECT COALESCE(context, '') FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prior); err != nil {- t.Fatalf("read workspace.context: %v", err)- }- if _, err := testPool.Exec(ctx, `UPDATE workspace SET context = $1 WHERE id = $2`, wsContext, testWorkspaceID); err != nil {- t.Fatalf("set workspace.context: %v", err)- }+ dbfx.QueryRow(t, `SELECT COALESCE(context, '') FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prior)+ dbfx.Exec(t, `UPDATE workspace SET context = $1 WHERE id = $2`, wsContext, testWorkspaceID)t.Cleanup(func() {if prior == "" {testPool.Exec(ctx, `UPDATE workspace SET context = NULL WHERE id = $1`, testWorkspaceID)@@ -792,14 +653,10 @@ func TestClaimTaskByRuntime_PopulatesWorkspaceContext(t *testing.T) {agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Workspace context claim agent")taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,testWorkspaceID, "workspace-context-claim")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {@@ -807,9 +664,7 @@ func TestClaimTaskByRuntime_PopulatesWorkspaceContext(t *testing.T) {WorkspaceContext string `json:"workspace_context"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatalf("expected dispatched task %s to be claimed, got nil response: %s", taskID, w.Body.String())}@@ -833,12 +688,8 @@ func TestClaimTaskByRuntime_WorkspaceContextEmptyWhenUnset(t *testing.T) {ctx := context.Background()var prior string- if err := testPool.QueryRow(ctx, `SELECT COALESCE(context, '') FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prior); err != nil {- t.Fatalf("read workspace.context: %v", err)- }- if _, err := testPool.Exec(ctx, `UPDATE workspace SET context = NULL WHERE id = $1`, testWorkspaceID); err != nil {- t.Fatalf("clear workspace.context: %v", err)- }+ dbfx.QueryRow(t, `SELECT COALESCE(context, '') FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prior)+ dbfx.Exec(t, `UPDATE workspace SET context = NULL WHERE id = $1`, testWorkspaceID)t.Cleanup(func() {if prior == "" {testPool.Exec(ctx, `UPDATE workspace SET context = NULL WHERE id = $1`, testWorkspaceID)@@ -851,14 +702,10 @@ func TestClaimTaskByRuntime_WorkspaceContextEmptyWhenUnset(t *testing.T) {agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Workspace context empty claim agent")taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,testWorkspaceID, "workspace-context-empty-claim")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {@@ -866,9 +713,7 @@ func TestClaimTaskByRuntime_WorkspaceContextEmptyWhenUnset(t *testing.T) {WorkspaceContext string `json:"workspace_context"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatalf("expected dispatched task %s to be claimed, got nil: %s", taskID, w.Body.String())}@@ -883,38 +728,32 @@ func TestClaimTaskByRuntime_MissingRuntimeOwnerCancelsAndRejects(t *testing.T) {}ctx := context.Background()- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider,- status, device_info, metadata, last_seen_at, visibility- )- VALUES ($1, NULL, 'Missing owner claim runtime', 'cloud', 'handler_test_runtime', 'online', 'claim missing owner fixture', '{}'::jsonb, now(), 'private')- RETURNING id- `, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: create runtime: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })+ runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "daemon_id": nil,+ "name": "Missing owner claim runtime",+ "runtime_mode": "cloud",+ "provider": "handler_test_runtime",+ "status": "online",+ "device_info": "claim missing owner fixture",+ "metadata": testutil.Raw("'{}'::jsonb"),+ "last_seen_at": testutil.Raw("now()"),+ "visibility": "private",+ })agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Missing owner claim agent")taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,testWorkspaceID, "missing-owner-claim")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusInternalServerError {- t.Fatalf("ClaimTaskByRuntime: expected 500, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)if !strings.Contains(w.Body.String(), "runtime owner required to mint task token") {t.Fatalf("ClaimTaskByRuntime body = %q, want runtime owner error", w.Body.String())}var status string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {- t.Fatalf("read task status: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)if status != "cancelled" {t.Fatalf("task status = %q, want cancelled", status)}@@ -925,7 +764,6 @@ func TestDaemonRegister_WithDaemonToken(t *testing.T) {t.Skip("database not available")}- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": "test-daemon-mdt",@@ -934,11 +772,7 @@ func TestDaemonRegister_WithDaemonToken(t *testing.T) {{"name": "test-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},}, testWorkspaceID, "test-daemon-mdt")-- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister with daemon token: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]anyjson.NewDecoder(w.Body).Decode(&resp)@@ -963,7 +797,6 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {ctx := context.Background()profileID := insertRuntimeProfileFixture(t, ctx, "Missing Custom Codex", "codex", "missing-codex")- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": "test-daemon-profile-failure",@@ -977,23 +810,17 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {},}, testWorkspaceID, "test-daemon-profile-failure")req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityLocalWorktreeV1)-- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE profile_id = $1`, profileID)})var status stringvar metadata []byte- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT status, metadata FROM agent_runtimeWHERE workspace_id = $1 AND daemon_id = $2 AND profile_id = $3- `, testWorkspaceID, "test-daemon-profile-failure", profileID).Scan(&status, &metadata); err != nil {- t.Fatalf("read failed profile runtime row: %v", err)- }+ `, testWorkspaceID, "test-daemon-profile-failure", profileID).Scan(&status, &metadata)if status != "offline" {t.Fatalf("status = %q, want offline", status)}@@ -1052,7 +879,6 @@ func TestDaemonHeartbeat_WithDaemonToken_CrossWorkspace(t *testing.T) {}// First, register a runtime using PAT (existing flow).- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": "test-daemon-heartbeat",@@ -1061,10 +887,7 @@ func TestDaemonHeartbeat_WithDaemonToken_CrossWorkspace(t *testing.T) {{"name": "test-runtime-hb", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("Setup: DaemonRegister failed: %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var regResp map[string]anyjson.NewDecoder(w.Body).Decode(®Resp)runtimes := regResp["runtimes"].([]any)@@ -1072,15 +895,10 @@ func TestDaemonHeartbeat_WithDaemonToken_CrossWorkspace(t *testing.T) {defer testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)// Try heartbeat with a daemon token from a DIFFERENT workspace — should fail.- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": runtimeID,}, "00000000-0000-0000-0000-000000000000", "attacker-daemon")-- testHandler.DaemonHeartbeat(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("DaemonHeartbeat with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusNotFound)}// TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError pins the fix for@@ -1123,31 +941,16 @@ func TestHandleDaemonWSHeartbeat_AllowsAnyAuthorizedWorkspace(t *testing.T) {ctx := context.Background()slug := "handler-ws-heartbeat-" + uuid.New().String()- var workspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "WS Heartbeat Scope", slug, "Temporary workspace for WS heartbeat tests", "HWS").Scan(&workspaceID); err != nil {- t.Fatalf("setup: create workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, workspaceID)+ workspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "WS Heartbeat Scope",+ "slug": slug,+ "description": "Temporary workspace for WS heartbeat tests",+ "issue_prefix": "HWS",})- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider,- status, device_info, metadata, owner_id, last_seen_at- )- VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, $5, now())- RETURNING id- `, workspaceID, "WS Heartbeat Runtime", "handler_test_runtime", "WS heartbeat runtime", testUserID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: create runtime: %v", err)- }- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+ runtimeID := dbfx.Runtime(t, "WS Heartbeat Runtime", testutil.Cols{+ "workspace_id": workspaceID,+ "device_info": "WS heartbeat runtime",})ack, err := testHandler.HandleDaemonWSHeartbeat(ctx,@@ -1171,15 +974,10 @@ func TestDaemonHeartbeat_HTTPRuntimeGoneReturns404(t *testing.T) {}missingRuntime := uuid.New().String()- w := httptest.NewRecorder()req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{"runtime_id": missingRuntime,}, testWorkspaceID, "test-daemon")- testHandler.DaemonHeartbeat(w, req)-- if w.Code != http.StatusNotFound {- t.Fatalf("expected 404 for missing runtime, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusNotFound)if !strings.Contains(strings.ToLower(w.Body.String()), "runtime not found") {t.Fatalf("expected 'runtime not found' body, got %s", w.Body.String())}@@ -1246,15 +1044,10 @@ func TestDaemonHeartbeat_EmptyQueueSkipsPopPending(t *testing.T) {testHandler.LocalSkillImportStore = origImport})- w := httptest.NewRecorder()req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{"runtime_id": runtimeID,}, testWorkspaceID, "runtime-local-skills-daemon")-- testHandler.DaemonHeartbeat(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusOK)if listSpy.popCalls != 0 {t.Fatalf("expected 0 PopPending calls on empty list queue, got %d", listSpy.popCalls)}@@ -1335,15 +1128,10 @@ func TestGetTaskStatus_TransientDBError_Returns500(t *testing.T) {h := &Handler{}h.Queries = db.New(&mockDB{getUserErr: errors.New("connection reset by peer")})- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/tasks/00000000-0000-0000-0000-000000000001/status", nil,"00000000-0000-0000-0000-000000000000", "test-daemon")req = withURLParam(req, "taskId", "00000000-0000-0000-0000-000000000001")-- h.GetTaskStatus(w, req)- if w.Code != http.StatusInternalServerError {- t.Fatalf("transient DB error: expected 500, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, h.GetTaskStatus, req).Want(http.StatusInternalServerError)if strings.Contains(w.Body.String(), "task not found") {t.Fatalf("transient DB error must not surface as %q (daemon treats that as a deletion): %s", "task not found", w.Body.String())}@@ -1356,15 +1144,10 @@ func TestGetTaskStatus_ErrNoRows_Returns404(t *testing.T) {h := &Handler{}h.Queries = db.New(&mockDB{getUserErr: pgx.ErrNoRows})- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/tasks/00000000-0000-0000-0000-000000000001/status", nil,"00000000-0000-0000-0000-000000000000", "test-daemon")req = withURLParam(req, "taskId", "00000000-0000-0000-0000-000000000001")-- h.GetTaskStatus(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("ErrNoRows: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, h.GetTaskStatus, req).Want(http.StatusNotFound)if !strings.Contains(w.Body.String(), "task not found") {t.Fatalf("ErrNoRows: expected body to contain %q, got %s", "task not found", w.Body.String())}@@ -1390,34 +1173,22 @@ func TestGetIssueGCCheck_WithDaemonToken_CrossWorkspace(t *testing.T) {// Cross-workspace daemon token must be rejected with 404 — same status// code as "issue not found" so there is no UUID enumeration oracle.- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/issues/"+issueID+"/gc-check", nil,"00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "issueId", issueID)-- testHandler.GetIssueGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("GetIssueGCCheck with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusNotFound)// Same-workspace daemon token succeeds and returns status + updated_at.- w = httptest.NewRecorder()req = newDaemonTokenRequest("GET", "/api/daemon/issues/"+issueID+"/gc-check", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "issueId", issueID)-- testHandler.GetIssueGCCheck(w, req)- if w.Code != http.StatusOK {- t.Fatalf("GetIssueGCCheck with correct workspace token: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusOK)var resp struct {Status string `json:"status"`UpdatedAt string `json:"updated_at"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if resp.Status != "done" {t.Fatalf("expected status %q, got %q", "done", resp.Status)}@@ -1443,16 +1214,11 @@ func TestBatchIssueGCCheck_WithDaemonToken(t *testing.T) {defer testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)missingID := "00000000-0000-0000-0000-000000000099"- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": []string{issueID, missingID},}, testWorkspaceID, "legit-daemon")req = withURLParam(req, "workspaceId", testWorkspaceID)-- testHandler.BatchIssueGCCheck(w, req)- if w.Code != http.StatusOK {- t.Fatalf("BatchIssueGCCheck: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK)var resp struct {Issues []struct {ID string `json:"id"`@@ -1461,9 +1227,7 @@ func TestBatchIssueGCCheck_WithDaemonToken(t *testing.T) {UpdatedAt string `json:"updated_at"`} `json:"issues"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if len(resp.Issues) != 2 {t.Fatalf("issues length = %d, want 2", len(resp.Issues))}@@ -1475,15 +1239,11 @@ func TestBatchIssueGCCheck_WithDaemonToken(t *testing.T) {}// A token for another workspace is rejected before any issue lookup.- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": []string{issueID},}, "00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "workspaceId", testWorkspaceID)- testHandler.BatchIssueGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("cross-workspace batch: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusNotFound)}// withURLParams merges the given chi URL parameters into the request context.@@ -1522,60 +1282,48 @@ func TestListTaskMessagesByUser_InvalidTaskIDReturnsBadRequest(t *testing.T) {// Returns (issueID, taskID). All rows are cleaned up when the test ends.func setupForeignWorkspaceFixture(t *testing.T) (string, string) {t.Helper()- ctx := context.Background()- var foreignWorkspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "Foreign Workspace", "foreign-idor-tests", "Cross-tenant IDOR test workspace", "FOR").Scan(&foreignWorkspaceID); err != nil {- t.Fatalf("setup: create foreign workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)+ foreignWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Foreign Workspace",+ "slug": "foreign-idor-tests",+ "description": "Cross-tenant IDOR test workspace",+ "issue_prefix": "FOR",})- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at- )- VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, now())- RETURNING id- `, foreignWorkspaceID, "Foreign Runtime", "foreign_runtime", "Foreign runtime").Scan(&runtimeID); err != nil {- t.Fatalf("setup: create foreign runtime: %v", err)- }+ runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "daemon_id": nil,+ "name": "Foreign Runtime",+ "runtime_mode": "cloud",+ "provider": "foreign_runtime",+ "status": "online",+ "device_info": "Foreign runtime",+ "metadata": testutil.Raw("'{}'::jsonb"),+ "last_seen_at": testutil.Raw("now()"),+ })- var agentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent (- workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks- )- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1)- RETURNING id- `, foreignWorkspaceID, "Foreign Agent", runtimeID).Scan(&agentID); err != nil {- t.Fatalf("setup: create foreign agent: %v", err)- }+ agentID := dbfx.Insert(t, "agent", testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "name": "Foreign Agent",+ "description": "",+ "runtime_mode": "cloud",+ "runtime_config": testutil.Raw("'{}'::jsonb"),+ "runtime_id": runtimeID,+ "visibility": "workspace",+ "max_concurrent_tasks": 1,+ })- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type)- VALUES ($1, 'foreign-workspace-issue', 'todo', 'medium', $2, 'agent')- RETURNING id- `, foreignWorkspaceID, agentID).Scan(&issueID); err != nil {- t.Fatalf("setup: create foreign issue: %v", err)- }+ issueID := dbfx.Issue(t, "foreign-workspace-issue", testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "priority": "medium",+ "creator_id": agentID,+ "creator_type": "agent",+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)- VALUES ($1, $2, 'queued', $3)- RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("setup: create foreign task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ })return issueID, taskID}@@ -1590,14 +1338,9 @@ func TestGetActiveTaskForIssue_CrossWorkspace_Returns404(t *testing.T) {foreignIssueID, _ := setupForeignWorkspaceFixture(t)- w := httptest.NewRecorder()req := newRequest("GET", "/api/issues/"+foreignIssueID+"/active-task", nil)req = withURLParam(req, "id", foreignIssueID)-- testHandler.GetActiveTaskForIssue(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("GetActiveTaskForIssue with cross-workspace issueId: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetActiveTaskForIssue, req).Want(http.StatusNotFound)}// TestCancelTask_CrossWorkspace_Returns404 verifies that a member of workspace@@ -1610,22 +1353,15 @@ func TestCancelTask_CrossWorkspace_Returns404(t *testing.T) {foreignIssueID, foreignTaskID := setupForeignWorkspaceFixture(t)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues/"+foreignIssueID+"/tasks/"+foreignTaskID+"/cancel", nil)req = withURLParams(req, "id", foreignIssueID, "taskId", foreignTaskID)-- testHandler.CancelTask(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("CancelTask with cross-workspace issueId/taskId: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CancelTask, req).Want(http.StatusNotFound)// The foreign task must not have been cancelled.var status string- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT status FROM agent_task_queue WHERE id = $1`, foreignTaskID,- ).Scan(&status); err != nil {- t.Fatalf("read foreign task status: %v", err)- }+ ).Scan(&status)if status != "queued" {t.Fatalf("foreign task status was mutated: expected 'queued', got %q", status)}@@ -1640,62 +1376,42 @@ func TestCancelTask_TaskBelongsToDifferentIssue_Returns404(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ ).Scan(&agentID, &runtimeID)// Issue X — the task's real parent.var issueXID, taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)VALUES ($1, 'cancel-crossissue-x', 'todo', 'medium', $2, 'member', 91001, 0)RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueXID); err != nil {- t.Fatalf("setup: create issue X: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueXID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueXID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)VALUES ($1, $2, 'queued', $3)RETURNING id- `, agentID, issueXID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("setup: create task: %v", err)- }+ `, agentID, issueXID, runtimeID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })// Issue Y — a sibling in the same workspace, used only as the URL cover.- var issueYID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'cancel-crossissue-y', 'todo', 'medium', $2, 'member', 91002, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueYID); err != nil {- t.Fatalf("setup: create issue Y: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueYID) })+ issueYID := dbfx.Issue(t, "cancel-crossissue-y", testutil.Cols{+ "priority": "medium",+ "number": 91002,+ })- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues/"+issueYID+"/tasks/"+taskID+"/cancel", nil)req = withURLParams(req, "id", issueYID, "taskId", taskID)-- testHandler.CancelTask(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("CancelTask with mismatched issueId/taskId: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CancelTask, req).Want(http.StatusNotFound)var status string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT status FROM agent_task_queue WHERE id = $1`, taskID,- ).Scan(&status); err != nil {- t.Fatalf("read task status: %v", err)- }+ ).Scan(&status)if status != "queued" {t.Fatalf("task status was mutated: expected 'queued', got %q", status)}@@ -1708,43 +1424,30 @@ func TestCancelTask_SameIssue_Succeeds(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ ).Scan(&agentID, &runtimeID)var issueID, taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)VALUES ($1, 'cancel-happy-path', 'todo', 'medium', $2, 'member', 91003, 0)RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)VALUES ($1, $2, 'queued', $3)RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("setup: create task: %v", err)- }+ `, agentID, issueID, runtimeID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues/"+issueID+"/tasks/"+taskID+"/cancel", nil)req = withURLParams(req, "id", issueID, "taskId", taskID)-- testHandler.CancelTask(w, req)- if w.Code != http.StatusOK {- t.Fatalf("CancelTask with matching issueId/taskId: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CancelTask, req).Want(http.StatusOK)}// TestListTasksByIssue_CrossWorkspace_Returns404 verifies that task history@@ -1756,14 +1459,9 @@ func TestListTasksByIssue_CrossWorkspace_Returns404(t *testing.T) {foreignIssueID, _ := setupForeignWorkspaceFixture(t)- w := httptest.NewRecorder()req := newRequest("GET", "/api/issues/"+foreignIssueID+"/task-runs", nil)req = withURLParam(req, "id", foreignIssueID)-- testHandler.ListTasksByIssue(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("ListTasksByIssue with cross-workspace issueId: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.ListTasksByIssue, req).Want(http.StatusNotFound)}// TestGetIssueUsage_CrossWorkspace_Returns404 verifies that per-issue token@@ -1775,14 +1473,9 @@ func TestGetIssueUsage_CrossWorkspace_Returns404(t *testing.T) {foreignIssueID, _ := setupForeignWorkspaceFixture(t)- w := httptest.NewRecorder()req := newRequest("GET", "/api/issues/"+foreignIssueID+"/usage", nil)req = withURLParam(req, "id", foreignIssueID)-- testHandler.GetIssueUsage(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("GetIssueUsage with cross-workspace issueId: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetIssueUsage, req).Want(http.StatusNotFound)}func TestGetDaemonWorkspaceRepos_WithDaemonToken(t *testing.T) {@@ -1795,23 +1488,16 @@ func TestGetDaemonWorkspaceRepos_WithDaemonToken(t *testing.T) {{"url": " [email protected]:team/web.git ", "description": " Web "},})- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, testWorkspaceID, "test-daemon-mdt")req = withURLParam(req, "workspaceId", testWorkspaceID)-- testHandler.GetDaemonWorkspaceRepos(w, req)- if w.Code != http.StatusOK {- t.Fatalf("GetDaemonWorkspaceRepos: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusOK)var resp struct {WorkspaceID string `json:"workspace_id"`Repos []map[string]string `json:"repos"`ReposVersion string `json:"repos_version"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if resp.WorkspaceID != testWorkspaceID {t.Fatalf("expected workspace_id %s, got %s", testWorkspaceID, resp.WorkspaceID)@@ -1832,14 +1518,9 @@ func TestGetDaemonWorkspaceRepos_WithDaemonToken_WorkspaceMismatch(t *testing.T)t.Skip("database not available")}- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, "00000000-0000-0000-0000-000000000000", "test-daemon-mdt")req = withURLParam(req, "workspaceId", testWorkspaceID)-- testHandler.GetDaemonWorkspaceRepos(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("GetDaemonWorkspaceRepos with mismatched workspace: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusNotFound)}func TestGetDaemonWorkspaceRepos_VersionIgnoresOrderAndDescription(t *testing.T) {@@ -1854,35 +1535,25 @@ func TestGetDaemonWorkspaceRepos_VersionIgnoresOrderAndDescription(t *testing.T)getReposVersion := func() string {t.Helper()- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, testWorkspaceID, "test-daemon-mdt")req = withURLParam(req, "workspaceId", testWorkspaceID)- testHandler.GetDaemonWorkspaceRepos(w, req)- if w.Code != http.StatusOK {- t.Fatalf("GetDaemonWorkspaceRepos: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusOK)var resp struct {ReposVersion string `json:"repos_version"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)return resp.ReposVersion}version1 := getReposVersion()- if _, err := testPool.Exec(context.Background(), `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte(`[{"url":"[email protected]:team/web.git","description":"frontend"},{"url":"[email protected]:team/api.git","description":"backend"}]`), testWorkspaceID); err != nil {- t.Fatalf("update workspace repos: %v", err)- }+ dbfx.Exec(t, `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte(`[{"url":"[email protected]:team/web.git","description":"frontend"},{"url":"[email protected]:team/api.git","description":"backend"}]`), testWorkspaceID)version2 := getReposVersion()if version1 != version2 {t.Fatalf("expected repos_version to ignore order/description changes, got %s vs %s", version1, version2)}- if _, err := testPool.Exec(context.Background(), `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte(`[{"url":"[email protected]:team/api.git","description":"backend"},{"url":"[email protected]:team/mobile.git","description":"mobile"}]`), testWorkspaceID); err != nil {- t.Fatalf("update workspace repos: %v", err)- }+ dbfx.Exec(t, `UPDATE workspace SET repos = $1 WHERE id = $2`, []byte(`[{"url":"[email protected]:team/api.git","description":"backend"},{"url":"[email protected]:team/mobile.git","description":"mobile"}]`), testWorkspaceID)version3 := getReposVersion()if strings.EqualFold(version2, version3) {t.Fatalf("expected repos_version to change when URL set changes, got %s", version3)@@ -1907,63 +1578,52 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()const legacyDaemonID = "TestMachine.local"const newDaemonID = "0192a7a0-9ab3-7c3f-9f1c-4a6fe8c4e801"// Seed a legacy runtime row keyed on the hostname-derived id.- var legacyRuntimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)- VALUES ($1, $2, 'legacy-runtime', 'local', 'claude', 'offline', 'TestMachine.local', '{}'::jsonb, $3, now() - interval '1 hour')- RETURNING id- `, testWorkspaceID, legacyDaemonID, testUserID).Scan(&legacyRuntimeID); err != nil {- t.Fatalf("seed legacy runtime: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, legacyRuntimeID)+ legacyRuntimeID := dbfx.Runtime(t, "legacy-runtime", testutil.Cols{+ "daemon_id": legacyDaemonID,+ "runtime_mode": "local",+ "provider": "claude",+ "status": "offline",+ "device_info": "TestMachine.local",+ "last_seen_at": testutil.Raw("now() - interval '1 hour'"),})// An agent bound to the legacy runtime.- var legacyAgentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks)- VALUES ($1, 'legacy-agent', 'local', '{}'::jsonb, $2, 'workspace', 1)- RETURNING id- `, testWorkspaceID, legacyRuntimeID).Scan(&legacyAgentID); err != nil {- t.Fatalf("seed legacy agent: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, legacyAgentID)+ legacyAgentID := dbfx.Insert(t, "agent", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "name": "legacy-agent",+ "runtime_mode": "local",+ "runtime_config": testutil.Raw("'{}'::jsonb"),+ "runtime_id": legacyRuntimeID,+ "visibility": "workspace",+ "max_concurrent_tasks": 1,})// An issue + task also bound to the legacy runtime (tasks have ON DELETE// CASCADE, so without reassignment deleting the legacy row would silently// drop historical tasks).var legacyIssueID, legacyTaskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)VALUES ($1, 'legacy-task-owner', 'todo', 'medium', $2, 'member', 97501, 0)RETURNING id- `, testWorkspaceID, testUserID).Scan(&legacyIssueID); err != nil {- t.Fatalf("seed legacy issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&legacyIssueID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, legacyIssueID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)VALUES ($1, $2, 'completed', $3)RETURNING id- `, legacyAgentID, legacyIssueID, legacyRuntimeID).Scan(&legacyTaskID); err != nil {- t.Fatalf("seed legacy task: %v", err)- }+ `, legacyAgentID, legacyIssueID, legacyRuntimeID).Scan(&legacyTaskID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, legacyTaskID)})// Register under the new stable UUID, declaring the prior hostname-derived// id as legacy. The handler should merge the legacy row into the new one.- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": newDaemonID,@@ -1973,15 +1633,10 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime(t *testing.T) {{"name": "test-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]any- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)runtimes := resp["runtimes"].([]any)newRuntimeID := runtimes[0].(map[string]any)["id"].(string)t.Cleanup(func() {@@ -1994,18 +1649,14 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime(t *testing.T) {// Agent should now point at the new runtime.var agentRuntimeID string- if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, legacyAgentID).Scan(&agentRuntimeID); err != nil {- t.Fatalf("read agent runtime_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, legacyAgentID).Scan(&agentRuntimeID)if agentRuntimeID != newRuntimeID {t.Fatalf("agent not reassigned: got runtime_id=%s, want %s", agentRuntimeID, newRuntimeID)}// Task should be reassigned (not dropped).var taskRuntimeID string- if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent_task_queue WHERE id = $1`, legacyTaskID).Scan(&taskRuntimeID); err != nil {- t.Fatalf("read task runtime_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent_task_queue WHERE id = $1`, legacyTaskID).Scan(&taskRuntimeID)if taskRuntimeID != newRuntimeID {t.Fatalf("task not reassigned: got runtime_id=%s, want %s", taskRuntimeID, newRuntimeID)}@@ -2013,18 +1664,14 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime(t *testing.T) {// Legacy runtime row must be gone — no more "online + offline" duplicates// for the same machine.var legacyCount int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount); err != nil {- t.Fatalf("count legacy runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount)if legacyCount != 0 {t.Fatalf("expected legacy runtime row to be deleted, still present")}// New row should record which legacy id it subsumed, for debug/audit.var legacyTrace *string- if err := testPool.QueryRow(ctx, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, newRuntimeID).Scan(&legacyTrace); err != nil {- t.Fatalf("read legacy_daemon_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, newRuntimeID).Scan(&legacyTrace)if legacyTrace == nil || *legacyTrace != legacyDaemonID {t.Fatalf("expected legacy_daemon_id=%q, got %v", legacyDaemonID, legacyTrace)}@@ -2040,24 +1687,17 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_ReverseDotLocal(t *testing.Tt.Skip("database not available")}- ctx := context.Background()const legacyDaemonID = "ReverseDotLocalHost" // stored without .localconst emittedLegacyID = "ReverseDotLocalHost.local" // daemon now reports with .localconst newDaemonID = "0192a7b0-0011-7ee9-9c21-30a5bcf86aa2"- var legacyRuntimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)- VALUES ($1, $2, 'legacy-runtime-reverse', 'local', 'claude', 'offline', '', '{}'::jsonb, $3, now())- RETURNING id- `, testWorkspaceID, legacyDaemonID, testUserID).Scan(&legacyRuntimeID); err != nil {- t.Fatalf("seed legacy runtime: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, legacyRuntimeID)+ legacyRuntimeID := dbfx.Runtime(t, "legacy-runtime-reverse", testutil.Cols{+ "daemon_id": legacyDaemonID,+ "runtime_mode": "local",+ "provider": "claude",+ "status": "offline",})- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": newDaemonID,@@ -2067,10 +1707,7 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_ReverseDotLocal(t *testing.T{"name": "reverse-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]anyjson.NewDecoder(w.Body).Decode(&resp)@@ -2080,9 +1717,7 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_ReverseDotLocal(t *testing.T})var legacyCount int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount); err != nil {- t.Fatalf("count legacy runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount)if legacyCount != 0 {t.Fatalf("expected legacy row to be merged and deleted, still present")}@@ -2098,24 +1733,17 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_CaseDrift(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()const storedDaemonID = "Jiayuans-MacBook-Pro.local" // DB has original mixed caseconst emittedLegacyID = "jiayuans-macbook-pro.local" // Daemon now reports lowercasedconst newDaemonID = "0192a7b0-0022-7ee9-9c21-30a5bcf86aa3"- var legacyRuntimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)- VALUES ($1, $2, 'legacy-runtime-case', 'local', 'claude', 'offline', '', '{}'::jsonb, $3, now())- RETURNING id- `, testWorkspaceID, storedDaemonID, testUserID).Scan(&legacyRuntimeID); err != nil {- t.Fatalf("seed legacy runtime: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, legacyRuntimeID)+ legacyRuntimeID := dbfx.Runtime(t, "legacy-runtime-case", testutil.Cols{+ "daemon_id": storedDaemonID,+ "runtime_mode": "local",+ "provider": "claude",+ "status": "offline",})- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": newDaemonID,@@ -2125,10 +1753,7 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_CaseDrift(t *testing.T) {{"name": "case-drift-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]anyjson.NewDecoder(w.Body).Decode(&resp)@@ -2138,17 +1763,13 @@ func TestDaemonRegister_MergesLegacyDaemonIDRuntime_CaseDrift(t *testing.T) {})var legacyCount int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount); err != nil {- t.Fatalf("count legacy runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE id = $1`, legacyRuntimeID).Scan(&legacyCount)if legacyCount != 0 {t.Fatalf("expected case-drift legacy row to be merged and deleted, still present")}var legacyTrace *string- if err := testPool.QueryRow(ctx, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, newRuntimeID).Scan(&legacyTrace); err != nil {- t.Fatalf("read legacy_daemon_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, newRuntimeID).Scan(&legacyTrace)if legacyTrace == nil || *legacyTrace != emittedLegacyID {t.Fatalf("expected legacy_daemon_id trace = %q, got %v", emittedLegacyID, legacyTrace)}@@ -2168,50 +1789,40 @@ func TestDaemonRegister_MergesAllCaseDuplicateLegacyRuntimes(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()const storedUpperID = "DupHost.local"const storedLowerID = "duphost.local"const newDaemonID = "0192a7b0-0033-7ee9-9c21-30a5bcf86aa4"var legacyUpperID, legacyLowerID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)VALUES ($1, $2, 'legacy-upper', 'local', 'claude', 'offline', '', '{}'::jsonb, $3, now() - interval '2 hours')RETURNING id- `, testWorkspaceID, storedUpperID, testUserID).Scan(&legacyUpperID); err != nil {- t.Fatalf("seed upper-case legacy runtime: %v", err)- }+ `, testWorkspaceID, storedUpperID, testUserID).Scan(&legacyUpperID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, legacyUpperID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)VALUES ($1, $2, 'legacy-lower', 'local', 'claude', 'offline', '', '{}'::jsonb, $3, now() - interval '1 hour')RETURNING id- `, testWorkspaceID, storedLowerID, testUserID).Scan(&legacyLowerID); err != nil {- t.Fatalf("seed lower-case legacy runtime: %v", err)- }+ `, testWorkspaceID, storedLowerID, testUserID).Scan(&legacyLowerID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, legacyLowerID) })// Bind one agent to each legacy row to verify both sides get reassigned.var upperAgentID, lowerAgentID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks)VALUES ($1, 'dup-agent-upper', 'local', '{}'::jsonb, $2, 'workspace', 1)RETURNING id- `, testWorkspaceID, legacyUpperID).Scan(&upperAgentID); err != nil {- t.Fatalf("seed upper agent: %v", err)- }+ `, testWorkspaceID, legacyUpperID).Scan(&upperAgentID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, upperAgentID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility, max_concurrent_tasks)VALUES ($1, 'dup-agent-lower', 'local', '{}'::jsonb, $2, 'workspace', 1)RETURNING id- `, testWorkspaceID, legacyLowerID).Scan(&lowerAgentID); err != nil {- t.Fatalf("seed lower agent: %v", err)- }+ `, testWorkspaceID, legacyLowerID).Scan(&lowerAgentID)t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, lowerAgentID) })- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": newDaemonID,@@ -2221,10 +1832,7 @@ func TestDaemonRegister_MergesAllCaseDuplicateLegacyRuntimes(t *testing.T) {{"name": "dup-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]anyjson.NewDecoder(w.Body).Decode(&resp)@@ -2235,11 +1843,9 @@ func TestDaemonRegister_MergesAllCaseDuplicateLegacyRuntimes(t *testing.T) {// Both case-duplicate legacy rows must be gone — not just one.var stillPresent int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE id = ANY($1)- `, []string{legacyUpperID, legacyLowerID}).Scan(&stillPresent); err != nil {- t.Fatalf("count legacy runtimes: %v", err)- }+ `, []string{legacyUpperID, legacyLowerID}).Scan(&stillPresent)if stillPresent != 0 {t.Fatalf("expected both case-duplicate legacy rows merged and deleted, %d still present", stillPresent)}@@ -2247,9 +1853,7 @@ func TestDaemonRegister_MergesAllCaseDuplicateLegacyRuntimes(t *testing.T) {// Both agents must point at the new runtime.for _, agentID := range []string{upperAgentID, lowerAgentID} {var runtimeID string- if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {- t.Fatalf("read agent runtime_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID)if runtimeID != newRuntimeID {t.Fatalf("agent %s not reassigned: runtime_id=%s, want %s", agentID, runtimeID, newRuntimeID)}@@ -2266,9 +1870,6 @@ func TestDaemonRegister_LegacyIDNoMatchIsNoop(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": "0192a7a1-5e3c-7be9-9a7d-6e0f1cb3deab",@@ -2278,10 +1879,7 @@ func TestDaemonRegister_LegacyIDNoMatchIsNoop(t *testing.T) {{"name": "fresh-runtime", "type": "claude", "version": "1.0.0", "status": "online"},},})- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]anyjson.NewDecoder(w.Body).Decode(&resp)@@ -2291,9 +1889,7 @@ func TestDaemonRegister_LegacyIDNoMatchIsNoop(t *testing.T) {})var legacy *string- if err := testPool.QueryRow(ctx, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&legacy); err != nil {- t.Fatalf("read legacy_daemon_id: %v", err)- }+ dbfx.QueryRow(t, `SELECT legacy_daemon_id FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&legacy)if legacy != nil {t.Fatalf("expected legacy_daemon_id to stay NULL when no merge occurred, got %q", *legacy)}@@ -2310,45 +1906,33 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var autopilotID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot (- workspace_id, title, assignee_id, execution_mode,- created_by_type, created_by_id- )- VALUES ($1, 'run_only fixture', $2, 'run_only', 'member', $3)- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {- t.Fatalf("setup: create autopilot: %v", err)- }+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": "run_only fixture",+ "assignee_id": agentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })defer testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)- var runID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot_run (autopilot_id, source, status)- VALUES ($1, 'manual', 'running')- RETURNING id- `, autopilotID).Scan(&runID); err != nil {- t.Fatalf("setup: create autopilot_run: %v", err)- }+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "running",+ })// issue_id is explicitly NULL — the condition that used to trigger 404.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, autopilot_run_id- )- VALUES ($1, $2, NULL, 'dispatched', 0, $3)- RETURNING id- `, agentID, runtimeID, runID).Scan(&taskID); err != nil {- t.Fatalf("setup: create autopilot task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": nil,+ "status": "dispatched",+ "autopilot_run_id": runID,+ })defer testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)// Cross-workspace daemon token must still 404.@@ -2376,9 +1960,7 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {}var status string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {- t.Fatalf("post-check: read task status: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)if status != "running" {t.Fatalf("expected task status 'running' after StartTask, got %q", status)}@@ -2393,8 +1975,6 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-// Workspace repos: two of them, neither matches the project repo URL.setHandlerTestWorkspaceRepos(t, []map[string]string{{"url": "https://github.com/example/workspace-repo-a", "description": "ws a"},@@ -2403,62 +1983,37 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {// Project + project_resource(github_repo) with a URL that is NOT in the// workspace's repos list.- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id- `, testWorkspaceID, "Claim project repo override").Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "Claim project repo override")const projectRepoURL = "https://github.com/example/project-only-repo"const projectRepoRef = "release/v2"- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO project_resource (project_id, workspace_id, resource_type, resource_ref, position) VALUES ($1, $2, 'github_repo', $3::jsonb, 0)- `, projectID, testWorkspaceID, `{"url":"`+projectRepoURL+`","ref":"`+projectRepoRef+`"}`); err != nil {- t.Fatalf("create project_resource: %v", err)- }+ `, projectID, testWorkspaceID, `{"url":"`+projectRepoURL+`","ref":"`+projectRepoRef+`"}`)// Agent + runtime + queued task in this project.var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("get agent: %v", err)- }+ ).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (- workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position- ) VALUES ($1, $2, 'project repo override', 'todo', 'medium', $3, 'member', 88001, 0)- RETURNING id- `, testWorkspaceID, projectID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "project repo override", testutil.Cols{+ "project_id": projectID,+ "priority": "medium",+ "number": 88001,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority- ) VALUES ($1, $2, $3, 'queued', 0)- RETURNING id- `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {- t.Fatalf("create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ })- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-project-repos")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {@@ -2467,9 +2022,7 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {ProjectResources []ProjectResourceData `json:"project_resources"`} `json:"task"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatal("expected task in response")}@@ -2502,54 +2055,31 @@ func TestClaimTask_ProjectDescriptionInjected(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-const projectDescription = "Always write copy in British English. Ship behind a feature flag."- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title, description) VALUES ($1, $2, $3) RETURNING id- `, testWorkspaceID, "Claim project description", projectDescription).Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "Claim project description", testutil.Cols{+ "description": projectDescription,+ })var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("get agent: %v", err)- }+ ).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (- workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position- ) VALUES ($1, $2, 'project description', 'todo', 'medium', $3, 'member', 88002, 0)- RETURNING id- `, testWorkspaceID, projectID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "project description", testutil.Cols{+ "project_id": projectID,+ "priority": "medium",+ "number": 88002,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority- ) VALUES ($1, $2, $3, 'queued', 0)- RETURNING id- `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {- t.Fatalf("create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ })- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-project-desc")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {@@ -2557,9 +2087,7 @@ func TestClaimTask_ProjectDescriptionInjected(t *testing.T) {ProjectDescription string `json:"project_description"`} `json:"task"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatal("expected task in response")}@@ -2583,13 +2111,9 @@ func TestClaimTask_QuickCreateInjectsProjectDescription(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)const projectDescription = "Use the design system tokens; never hardcode colors."- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title, description) VALUES ($1, $2, $3) RETURNING id- `, testWorkspaceID, "Quick-create project description", projectDescription).Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "Quick-create project description", testutil.Cols{+ "description": projectDescription,+ })quickContext, _ := json.Marshal(map[string]any{"type": "quick_create",@@ -2598,12 +2122,10 @@ func TestClaimTask_QuickCreateInjectsProjectDescription(t *testing.T) {"workspace_id": testWorkspaceID,"project_id": projectID,})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context)VALUES ($1, $2, 'queued', 2, $3)- `, agentID, runtimeID, quickContext); err != nil {- t.Fatalf("setup: create quick-create task: %v", err)- }+ `, agentID, runtimeID, quickContext)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.ProjectID != projectID {@@ -2621,66 +2143,39 @@ func TestClaimTask_ProjectWithoutRepos_FallsBackToWorkspaceRepos(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()-setHandlerTestWorkspaceRepos(t, []map[string]string{{"url": "https://github.com/example/workspace-fallback", "description": "ws"},})- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id- `, testWorkspaceID, "Claim project without repos").Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "Claim project without repos")var agentID, runtimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("get agent: %v", err)- }+ ).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (- workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position- ) VALUES ($1, $2, 'no project repos', 'todo', 'medium', $3, 'member', 88002, 0)- RETURNING id- `, testWorkspaceID, projectID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "no project repos", testutil.Cols{+ "project_id": projectID,+ "priority": "medium",+ "number": 88002,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority- ) VALUES ($1, $2, $3, 'queued', 0)- RETURNING id- `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {- t.Fatalf("create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ })- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-fallback")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {Repos []RepoData `json:"repos"`} `json:"task"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatal("expected task in response")}@@ -2702,45 +2197,32 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var autopilotID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot (- workspace_id, title, assignee_id, execution_mode,- created_by_type, created_by_id- )- VALUES ($1, 'claim workspace fixture', $2, 'run_only', 'member', $3)- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {- t.Fatalf("setup: create autopilot: %v", err)- }+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": "claim workspace fixture",+ "assignee_id": agentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })defer testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)- var runID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot_run (autopilot_id, source, status)- VALUES ($1, 'manual', 'running')- RETURNING id- `, autopilotID).Scan(&runID); err != nil {- t.Fatalf("setup: create autopilot_run: %v", err)- }+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "running",+ })// Create a queued task with only AutopilotRunID (no IssueID, no ChatSessionID).- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, autopilot_run_id- )- VALUES ($1, $2, NULL, 'queued', 0, $3)- RETURNING id- `, agentID, runtimeID, runID).Scan(&taskID); err != nil {- t.Fatalf("setup: create autopilot task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": nil,+ "autopilot_run_id": runID,+ })defer testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)w := httptest.NewRecorder()@@ -2790,50 +2272,36 @@ func TestClaimTaskByRuntime_TaskWorkspaceMismatch_CancelsAndRejects(t *testing.Tt.Skip("database not available")}- ctx := context.Background()-// Local agent/runtime (belongs to testWorkspace).var localAgentID, localRuntimeID string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,- ).Scan(&localAgentID, &localRuntimeID); err != nil {- t.Fatalf("setup: get local agent: %v", err)- }+ ).Scan(&localAgentID, &localRuntimeID)// Foreign workspace with its own issue — what the misrouted task will// resolve to.- var foreignWorkspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "Mismatch Foreign", "mismatch-foreign-claim", "", "MFC").Scan(&foreignWorkspaceID); err != nil {- t.Fatalf("setup: create foreign workspace: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID) })+ foreignWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Mismatch Foreign",+ "slug": "mismatch-foreign-claim",+ "description": "",+ "issue_prefix": "MFC",+ })- var foreignIssueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'mismatch-foreign-issue', 'todo', 'medium', $2, 'member', 77001, 0)- RETURNING id- `, foreignWorkspaceID, testUserID).Scan(&foreignIssueID); err != nil {- t.Fatalf("setup: create foreign issue: %v", err)- }+ foreignIssueID := dbfx.Issue(t, "mismatch-foreign-issue", testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "priority": "medium",+ "number": 77001,+ })// Construct the inconsistent task: runtime_id belongs to testWorkspace,// but issue_id is in foreignWorkspace. This is the data shape a routing// bug would produce.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)- VALUES ($1, $2, $3, 'queued', 2)- RETURNING id- `, localAgentID, localRuntimeID, foreignIssueID).Scan(&taskID); err != nil {- t.Fatalf("setup: create mismatched task: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, localAgentID, testutil.Cols{+ "runtime_id": localRuntimeID,+ "issue_id": foreignIssueID,+ "priority": 2,+ })w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil,@@ -2850,11 +2318,9 @@ func TestClaimTaskByRuntime_TaskWorkspaceMismatch_CancelsAndRejects(t *testing.T// Task must NOT remain dispatched — it has to be cancelled so the agent// is released immediately rather than stuck until the sweeper fires.var status string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT status FROM agent_task_queue WHERE id = $1`, taskID,- ).Scan(&status); err != nil {- t.Fatalf("read task status: %v", err)- }+ ).Scan(&status)if status != "cancelled" {t.Fatalf("ClaimTaskByRuntime (mismatch): expected task status=cancelled, got %q", status)}@@ -2875,46 +2341,27 @@ func TestCompleteTask_CommentTriggered_SynthesizesCommentWhenAgentSilent(t *testctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)setWorkspaceIssuePrefixForTest(t, "MUL")- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'mul-3310 agent output fixture', 'in_progress', 'none', $2, 'member', 3310, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "mul-3310 agent output fixture", testutil.Cols{+ "status": "in_progress",+ "number": 3310,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'please take a look', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: create trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "please take a look")// Comment-triggered, already running (as CompleteAgentTask requires).- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, trigger_comment_id,- status, priority, started_at- )- VALUES ($1, $2, $3, $4, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: create comment-triggered task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "trigger_comment_id": triggerCommentID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })agentFinalOutput := fmt.Sprintf("sure, see MUL-3310, issue/MUL-3310, feature/MUL-3310, and [MUL-3310](mention://issue/%s)",@@ -2980,54 +2427,31 @@ func TestCompleteTask_CommentTriggered_SkipsSynthesisWhenAgentAlreadyCommented(tt.Skip("database not available")}- ctx := context.Background()-var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'mul-1198 dedup fixture', 'in_progress', 'none', $2, 'member', 81199, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "mul-1198 dedup fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81199,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'please take a look', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: create trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "please take a look")- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, trigger_comment_id,- status, priority, started_at- )- VALUES ($1, $2, $3, $4, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: create comment-triggered task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "trigger_comment_id": triggerCommentID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })// Agent posts its own reply during the run — exactly the compliant path.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id)VALUES ($1, $2, 'agent', $3, 'done, see PR', 'comment', $4)- `, issueID, testWorkspaceID, agentID, triggerCommentID); err != nil {- t.Fatalf("setup: create agent reply: %v", err)- }+ `, issueID, testWorkspaceID, agentID, triggerCommentID)w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",@@ -3043,12 +2467,10 @@ func TestCompleteTask_CommentTriggered_SkipsSynthesisWhenAgentAlreadyCommented(t}var count int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM commentWHERE issue_id = $1 AND author_type = 'agent' AND author_id = $2- `, issueID, agentID).Scan(&count); err != nil {- t.Fatalf("count agent comments: %v", err)- }+ `, issueID, agentID).Scan(&count)if count != 1 {t.Fatalf("expected 1 agent comment (the agent's own reply), got %d — synthesis duplicated", count)}@@ -3059,46 +2481,25 @@ func TestCompleteTask_CommentTriggered_SuppressesTrivialDoneOutput(t *testing.T)t.Skip("database not available")}- ctx := context.Background()-var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'trivial-done-suppression fixture', 'in_progress', 'none', $2, 'member', 81200, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "trivial-done-suppression fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81200,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'please follow up', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: create trigger comment: %v", err)- }+ triggerCommentID := dbfx.Comment(t, issueID, "please follow up")- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, trigger_comment_id,- status, priority, started_at- )- VALUES ($1, $2, $3, $4, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, issueID, triggerCommentID).Scan(&taskID); err != nil {- t.Fatalf("setup: create comment-triggered task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "trigger_comment_id": triggerCommentID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",@@ -3114,12 +2515,10 @@ func TestCompleteTask_CommentTriggered_SuppressesTrivialDoneOutput(t *testing.T)}var count int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM commentWHERE issue_id = $1 AND author_type = 'agent' AND author_id = $2- `, issueID, agentID).Scan(&count); err != nil {- t.Fatalf("count agent comments: %v", err)- }+ `, issueID, agentID).Scan(&count)if count != 0 {t.Fatalf("expected no synthesized agent comment for trivial Done output, got %d", count)}@@ -3130,37 +2529,22 @@ func TestCompleteTask_AssignmentTriggered_DoesNotSuppressTrivialDoneOutput(t *tet.Skip("database not available")}- ctx := context.Background()-var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'assignment-trivial-done fixture', 'in_progress', 'none', $2, 'member', 81201, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })+ issueID := dbfx.Issue(t, "assignment-trivial-done fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81201,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id,- status, priority, started_at- )- VALUES ($1, $2, $3, 'running', 0, now())- RETURNING id- `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {- t.Fatalf("setup: create assignment-triggered task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",@@ -3176,13 +2560,11 @@ func TestCompleteTask_AssignmentTriggered_DoesNotSuppressTrivialDoneOutput(t *te}var content string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT content FROM commentWHERE issue_id = $1 AND author_type = 'agent' AND author_id = $2ORDER BY created_at DESC LIMIT 1- `, issueID, agentID).Scan(&content); err != nil {- t.Fatalf("query synthesized comment: %v", err)- }+ `, issueID, agentID).Scan(&content)if content != "Done." {t.Fatalf("synthesized comment content = %q, want Done.", content)}@@ -3231,7 +2613,6 @@ func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtimt.Helper()daemonID = "runtime-guard-" + strings.ToLower(strings.ReplaceAll(t.Name(), "/", "-"))- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,"daemon_id": daemonID,@@ -3240,35 +2621,25 @@ func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtim{"name": "runtime-guard-current", "type": "opencode", "version": "test", "status": "online"},},}, testWorkspaceID, daemonID)-- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusOK {- t.Fatalf("setup: DaemonRegister: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)var resp map[string]any- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("setup: decode DaemonRegister response: %v", err)- }+ w.JSON(&resp)runtimes, ok := resp["runtimes"].([]any)if !ok || len(runtimes) == 0 {t.Fatalf("setup: expected registered runtime, got %v", resp)}runtimeID = runtimes[0].(map[string]any)["id"].(string)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })- if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, testUserID, runtimeID); err != nil {- t.Fatalf("setup: set runtime owner: %v", err)- }+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, testUserID, runtimeID)- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config,runtime_id, visibility, max_concurrent_tasks)VALUES ($1, $2, 'local', '{}'::jsonb, $3, 'workspace', 3)RETURNING id- `, testWorkspaceID, "Runtime Guard Agent "+t.Name(), runtimeID).Scan(&agentID); err != nil {- t.Fatalf("setup: create runtime guard agent: %v", err)- }+ `, testWorkspaceID, "Runtime Guard Agent "+t.Name(), runtimeID).Scan(&agentID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })return agentID, runtimeID, daemonID@@ -3277,19 +2648,13 @@ func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtimfunc createRuntimeGuardRuntime(t *testing.T, ctx context.Context, provider string) string {t.Helper()- var runtimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status,- device_info, metadata, owner_id, last_seen_at- )- VALUES ($1, 'runtime-guard-' || gen_random_uuid()::text, 'Runtime Guard Fixture',- 'local', $2, 'offline', '{}'::jsonb, '{}'::jsonb, $3, now())- RETURNING id- `, testWorkspaceID, provider, testUserID).Scan(&runtimeID); err != nil {- t.Fatalf("setup: create runtime: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })+ runtimeID := dbfx.Runtime(t, "Runtime Guard Fixture", testutil.Cols{+ "daemon_id": testutil.Raw("'runtime-guard-' || gen_random_uuid()::text"),+ "runtime_mode": "local",+ "provider": provider,+ "status": "offline",+ "device_info": testutil.Raw("'{}'::jsonb"),+ })return runtimeID}@@ -3411,35 +2776,26 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)oldRuntimeID := createRuntimeGuardRuntime(t, ctx, "kimi")- var skipIssueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'runtime-session-skip fixture', 'in_progress', 'none', $2, 'member', 81203, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&skipIssueID); err != nil {- t.Fatalf("setup: create skip issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, skipIssueID) })+ skipIssueID := dbfx.Issue(t, "runtime-session-skip fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81203,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'old-runtime-session', '/tmp/old-runtime-workdir')- `, agentID, oldRuntimeID, skipIssueID); err != nil {- t.Fatalf("setup: create old-runtime prior task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, oldRuntimeID, skipIssueID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, skipIssueID); err != nil {- t.Fatalf("setup: create current-runtime task: %v", err)- }+ `, agentID, runtimeID, skipIssueID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "" {@@ -3451,43 +2807,32 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {if task.ThreadName != "runtime-session-skip fixture" {t.Fatalf("issue task thread_name = %q, want issue title", task.ThreadName)}- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queueSET status = 'completed', completed_at = now()WHERE issue_id = $1 AND status IN ('dispatched', 'running')- `, skipIssueID); err != nil {- t.Fatalf("setup: complete claimed skip task: %v", err)- }+ `, skipIssueID)- var resumeIssueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'runtime-session-resume fixture', 'in_progress', 'none', $2, 'member', 81204, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&resumeIssueID); err != nil {- t.Fatalf("setup: create resume issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, resumeIssueID) })+ resumeIssueID := dbfx.Issue(t, "runtime-session-resume fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81204,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'same-runtime-session', '/tmp/same-runtime-workdir')- `, agentID, runtimeID, resumeIssueID); err != nil {- t.Fatalf("setup: create same-runtime prior task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, resumeIssueID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, resumeIssueID); err != nil {- t.Fatalf("setup: create same-runtime task: %v", err)- }+ `, agentID, runtimeID, resumeIssueID)task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "same-runtime-session" {@@ -3497,43 +2842,27 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {t.Fatalf("runtime match: expected PriorWorkDir='/tmp/same-runtime-workdir', got %q", task.PriorWorkDir)}- var commentIssueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'comment-triggered-session-skip fixture', 'in_progress', 'none', $2, 'member', 81205, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&commentIssueID); err != nil {- t.Fatalf("setup: create comment-triggered issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, commentIssueID) })+ commentIssueID := dbfx.Issue(t, "comment-triggered-session-skip fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81205,+ })- var triggerCommentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'please follow up', 'comment')- RETURNING id- `, commentIssueID, testWorkspaceID, testUserID).Scan(&triggerCommentID); err != nil {- t.Fatalf("setup: create trigger comment: %v", err)- }- if _, err := testPool.Exec(ctx, `+ triggerCommentID := dbfx.Comment(t, commentIssueID, "please follow up")+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'comment-prior-session', '/tmp/comment-prior-workdir')- `, agentID, runtimeID, commentIssueID); err != nil {- t.Fatalf("setup: create comment-trigger prior task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, commentIssueID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id,status, priority)VALUES ($1, $2, $3, $4, 'queued', 0)- `, agentID, runtimeID, commentIssueID, triggerCommentID); err != nil {- t.Fatalf("setup: create comment-triggered task: %v", err)- }+ `, agentID, runtimeID, commentIssueID, triggerCommentID)task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)// Comment-triggered tasks now resume the prior session by default (same@@ -3544,42 +2873,31 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {if task.PriorWorkDir != "/tmp/comment-prior-workdir" {t.Fatalf("comment trigger: expected PriorWorkDir='/tmp/comment-prior-workdir', got %q", task.PriorWorkDir)}- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queueSET status = 'completed', completed_at = now()WHERE issue_id = $1 AND status IN ('dispatched', 'running')- `, commentIssueID); err != nil {- t.Fatalf("setup: complete claimed comment-trigger task: %v", err)- }+ `, commentIssueID)- var freshIssueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'force-fresh-session fixture', 'in_progress', 'none', $2, 'member', 81206, 0)- RETURNING id- `, testWorkspaceID, testUserID).Scan(&freshIssueID); err != nil {- t.Fatalf("setup: create force-fresh issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, freshIssueID) })- if _, err := testPool.Exec(ctx, `+ freshIssueID := dbfx.Issue(t, "force-fresh-session fixture", testutil.Cols{+ "status": "in_progress",+ "number": 81206,+ })+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'force-fresh-prior-session', '/tmp/force-fresh-prior-workdir')- `, agentID, runtimeID, freshIssueID); err != nil {- t.Fatalf("setup: create force-fresh prior task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, freshIssueID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id,status, priority, force_fresh_session)VALUES ($1, $2, $3, 'queued', 0, TRUE)- `, agentID, runtimeID, freshIssueID); err != nil {- t.Fatalf("setup: create force-fresh task: %v", err)- }+ `, agentID, runtimeID, freshIssueID)task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "" {@@ -3617,38 +2935,28 @@ func TestClaimTask_ManualRetryReusesWorkdir(t *testing.T) {insertRerun := func(t *testing.T, sourceRuntimeID, failureReason, errorText, session, workdir string) *claimRuntimeGuardTask {t.Helper()issueNum++- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)- VALUES ($1, 'manual-retry-reuse fixture', 'in_progress', 'none', $2, 'member', $3, 0)- RETURNING id- `, testWorkspaceID, testUserID, issueNum).Scan(&issueID); err != nil {- t.Fatalf("setup: create issue: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- var sourceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority,- failure_reason, error, session_id, work_dir- )- VALUES ($1, $2, $3, 'failed', 0, $4, $5, $6, $7)- RETURNING id- `, agentID, sourceRuntimeID, issueID, failureReason, errorText, session, workdir).Scan(&sourceID); err != nil {- t.Fatalf("setup: insert source task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, sourceID) })+ issueID := dbfx.Issue(t, "manual-retry-reuse fixture", testutil.Cols{+ "status": "in_progress",+ "number": issueNum,+ })+ sourceID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": sourceRuntimeID,+ "issue_id": issueID,+ "status": "failed",+ "failure_reason": failureReason,+ "error": errorText,+ "session_id": session,+ "work_dir": workdir,+ })// force_fresh_session is always true on a rerun row (rollback-safe); the// new claim handler resumes from the source task regardless.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,rerun_of_task_id, force_fresh_session)VALUES ($1, $2, $3, 'queued', 0, $4, TRUE)- `, agentID, runtimeID, issueID, sourceID); err != nil {- t.Fatalf("setup: insert rerun task: %v", err)- }+ `, agentID, runtimeID, issueID, sourceID)return claimTaskForRuntimeGuard(t, runtimeID, daemonID)}@@ -3707,38 +3015,28 @@ func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)oldRuntimeID := createRuntimeGuardRuntime(t, ctx, "kimi")- var skipSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'runtime guard skip chat', 'old-chat-session', '/tmp/old-chat-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, oldRuntimeID).Scan(&skipSessionID); err != nil {- t.Fatalf("setup: create skip chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, skipSessionID) })+ skipSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "runtime guard skip chat",+ "session_id": "old-chat-session",+ "work_dir": "/tmp/old-chat-workdir",+ "runtime_id": oldRuntimeID,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'old-chat-session', '/tmp/old-chat-workdir')- `, agentID, oldRuntimeID, skipSessionID); err != nil {- t.Fatalf("setup: create old-runtime chat task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, oldRuntimeID, skipSessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, skipSessionID); err != nil {- t.Fatalf("setup: create current-runtime chat task: %v", err)- }+ `, agentID, runtimeID, skipSessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "" {@@ -3747,36 +3045,26 @@ func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {if task.PriorWorkDir != "/tmp/old-chat-workdir" {t.Fatalf("chat runtime mismatch: expected PriorWorkDir='/tmp/old-chat-workdir', got %q", task.PriorWorkDir)}- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queueSET status = 'completed', completed_at = now()WHERE chat_session_id = $1 AND status IN ('dispatched', 'running')- `, skipSessionID); err != nil {- t.Fatalf("setup: complete claimed skip chat task: %v", err)- }+ `, skipSessionID)- var resumeSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'runtime guard resume chat', 'same-chat-session', '/tmp/same-chat-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&resumeSessionID); err != nil {- t.Fatalf("setup: create resume chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, resumeSessionID) })+ resumeSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "runtime guard resume chat",+ "session_id": "same-chat-session",+ "work_dir": "/tmp/same-chat-workdir",+ "runtime_id": runtimeID,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, resumeSessionID); err != nil {- t.Fatalf("setup: create same-runtime chat task: %v", err)- }+ `, agentID, runtimeID, resumeSessionID)task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "same-chat-session" {@@ -3800,31 +3088,21 @@ func TestClaimTask_ChatDeliversAllUnansweredUserMessages(t *testing.T) {ctx := context.Background()agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var sessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)- VALUES ($1, $2, $3, 'debounce delivery chat')- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&sessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "debounce delivery chat",+ })// Two user messages debounced into one run (explicit created_at so the// ASC ordering is deterministic).- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content, created_at) VALUES($1, 'user', '看上海天气', now()),($1, 'user', '还有青岛', now() + interval '1 second')- `, sessionID); err != nil {- t.Fatalf("setup: insert user messages: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, sessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 2)- `, agentID, runtimeID, sessionID); err != nil {- t.Fatalf("setup: create chat task: %v", err)- }+ `, agentID, runtimeID, sessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.ChatMessage != "看上海天气\n\n还有青岛" {@@ -3836,30 +3114,22 @@ func TestClaimTask_ChatDeliversAllUnansweredUserMessages(t *testing.T) {// Complete the run and record the agent's assistant reply, then send a// fresh user message — only the new one should be delivered next.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now()WHERE chat_session_id = $1 AND status IN ('dispatched', 'running')- `, sessionID); err != nil {- t.Fatalf("setup: complete first chat task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, sessionID)+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content, created_at)VALUES ($1, 'assistant', '上海与青岛天气如下…', now() + interval '2 second')- `, sessionID); err != nil {- t.Fatalf("setup: insert assistant reply: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, sessionID)+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content, created_at)VALUES ($1, 'user', '深圳呢', now() + interval '3 second')- `, sessionID); err != nil {- t.Fatalf("setup: insert follow-up user message: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, sessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)VALUES ($1, $2, $3, 'queued', 2)- `, agentID, runtimeID, sessionID); err != nil {- t.Fatalf("setup: create follow-up chat task: %v", err)- }+ `, agentID, runtimeID, sessionID)task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.ChatMessage != "深圳呢" {@@ -3882,45 +3152,28 @@ func TestClaimTask_ChatPopulatesInitiator(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)// A separate user stands in for the Lark group session creator (installer).- var installerID string- if err := testPool.QueryRow(ctx, `- INSERT INTO "user" (name, email) VALUES ('Installer User', '[email protected]')- RETURNING id- `).Scan(&installerID); err != nil {- t.Fatalf("setup: create installer user: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, installerID) })+ installerID := dbfx.Insert(t, "user", testutil.Cols{+ "name": "Installer User",+ "email": "[email protected]",+ })- var sessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)- VALUES ($1, $2, $3, 'initiator chat')- RETURNING id- `, testWorkspaceID, agentID, installerID).Scan(&sessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "creator_id": installerID,+ "title": "initiator chat",+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content) VALUES ($1, 'user', 'hi there')- `, sessionID); err != nil {- t.Fatalf("setup: insert user message: %v", err)- }+ `, sessionID)// initiator_user_id = the real sender (testUserID), distinct from creator.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, initiator_user_id)VALUES ($1, $2, $3, 'queued', 2, $4)- `, agentID, runtimeID, sessionID, testUserID); err != nil {- t.Fatalf("setup: create chat task: %v", err)- }+ `, agentID, runtimeID, sessionID, testUserID)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {InitiatorType string `json:"initiator_type"`@@ -3929,9 +3182,7 @@ func TestClaimTask_ChatPopulatesInitiator(t *testing.T) {InitiatorEmail string `json:"initiator_email"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatalf("expected a claimed task, got %s", w.Body.String())}@@ -3963,12 +3214,10 @@ func TestClaimTask_QuickCreatePopulatesThreadName(t *testing.T) {"attachment_ids": []string{attachmentID},})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context)VALUES ($1, $2, 'queued', 2, $3)- `, agentID, runtimeID, quickContext); err != nil {- t.Fatalf("setup: create quick-create task: %v", err)- }+ `, agentID, runtimeID, quickContext)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.ThreadName != quickPrompt {@@ -3991,38 +3240,28 @@ func TestClaimTask_ChatForceFreshSessionSkipsPriorSession(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'force fresh chat', 'chat-pointer-session', '/tmp/chat-pointer-workdir', $4)- RETURNING id- `, testWorkspaceID, agentID, testUserID, runtimeID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "force fresh chat",+ "session_id": "chat-pointer-session",+ "work_dir": "/tmp/chat-pointer-workdir",+ "runtime_id": runtimeID,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'task-row-session', '/tmp/task-row-workdir')- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create prior chat task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, chatSessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, force_fresh_session)VALUES ($1, $2, $3, 'queued', 0, TRUE)- `, agentID, runtimeID, chatSessionID); err != nil {- t.Fatalf("setup: create force-fresh chat task: %v", err)- }+ `, agentID, runtimeID, chatSessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "" {@@ -4046,38 +3285,28 @@ func TestClaimTask_ChatLegacyNullRuntimeFallsBackToTaskRow(t *testing.T) {agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)- var legacySessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (- workspace_id, agent_id, creator_id, title,- session_id, work_dir, runtime_id- )- VALUES ($1, $2, $3, 'runtime guard legacy chat', NULL, NULL, NULL)- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&legacySessionID); err != nil {- t.Fatalf("setup: create legacy chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, legacySessionID) })+ legacySessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "runtime guard legacy chat",+ "session_id": nil,+ "work_dir": nil,+ "runtime_id": nil,+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority, started_at, completed_at,session_id, work_dir)VALUES ($1, $2, $3, 'completed', 0, now(), now(), 'legacy-fallback-session', '/tmp/legacy-fallback-workdir')- `, agentID, runtimeID, legacySessionID); err != nil {- t.Fatalf("setup: create matching-runtime prior task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ `, agentID, runtimeID, legacySessionID)+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id,status, priority)VALUES ($1, $2, $3, 'queued', 0)- `, agentID, runtimeID, legacySessionID); err != nil {- t.Fatalf("setup: create current chat task: %v", err)- }+ `, agentID, runtimeID, legacySessionID)task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)if task.PriorSessionID != "legacy-fallback-session" {@@ -4099,46 +3328,29 @@ func TestGetChatSessionGCCheck(t *testing.T) {ctx := context.Background()var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- var sessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)- VALUES ($1, $2, $3, 'gc-check fixture', 'active')- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&sessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "gc-check fixture",+ })defer testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID)// Cross-workspace daemon token must 404 with no oracle.- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil,"00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "sessionId", sessionID)- testHandler.GetChatSessionGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusNotFound)// Same-workspace daemon token sees the live row.- w = httptest.NewRecorder()req = newDaemonTokenRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "sessionId", sessionID)- testHandler.GetChatSessionGCCheck(w, req)- if w.Code != http.StatusOK {- t.Fatalf("same-workspace token: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusOK)var resp struct {Status string `json:"status"`UpdatedAt string `json:"updated_at"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Status != "active" {t.Fatalf("expected status %q, got %q", "active", resp.Status)}@@ -4148,17 +3360,11 @@ func TestGetChatSessionGCCheck(t *testing.T) {// Hard-deleted session: 404 — exactly what the daemon needs to reclaim// the workdir on the next GC pass after a user runs DeleteChatSession.- if _, err := testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID); err != nil {- t.Fatalf("delete chat session: %v", err)- }- w = httptest.NewRecorder()+ dbfx.Exec(t, `DELETE FROM chat_session WHERE id = $1`, sessionID)req = newDaemonTokenRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "sessionId", sessionID)- testHandler.GetChatSessionGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("hard-deleted session: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusNotFound)}// TestGetAutopilotRunGCCheck verifies the autopilot-run gc-check endpoint:@@ -4171,58 +3377,41 @@ func TestGetAutopilotRunGCCheck(t *testing.T) {ctx := context.Background()var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }-- var autopilotID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot (- workspace_id, title, assignee_id, execution_mode,- created_by_type, created_by_id- )- VALUES ($1, 'gc-check autopilot', $2, 'run_only', 'member', $3)- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&autopilotID); err != nil {- t.Fatalf("setup: create autopilot: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)++ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": "gc-check autopilot",+ "assignee_id": agentID,+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })defer testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)- var runID string- if err := testPool.QueryRow(ctx, `- INSERT INTO autopilot_run (autopilot_id, source, status, completed_at)- VALUES ($1, 'manual', 'completed', NOW() - INTERVAL '6 days')- RETURNING id- `, autopilotID).Scan(&runID); err != nil {- t.Fatalf("setup: create autopilot_run: %v", err)- }+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "completed",+ "completed_at": testutil.Raw("NOW() - INTERVAL '6 days'"),+ })// Cross-workspace probe.- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/autopilot-runs/"+runID+"/gc-check", nil,"00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "runId", runID)- testHandler.GetAutopilotRunGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetAutopilotRunGCCheck, req).Want(http.StatusNotFound)// Same-workspace probe.- w = httptest.NewRecorder()req = newDaemonTokenRequest("GET", "/api/daemon/autopilot-runs/"+runID+"/gc-check", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "runId", runID)- testHandler.GetAutopilotRunGCCheck(w, req)- if w.Code != http.StatusOK {- t.Fatalf("same-workspace token: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetAutopilotRunGCCheck, req).Want(http.StatusOK)var resp struct {Status string `json:"status"`CompletedAt string `json:"completed_at"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Status != "completed" {t.Fatalf("expected status %q, got %q", "completed", resp.Status)}@@ -4241,11 +3430,9 @@ func TestGetTaskGCCheck(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)// Quick-create-shaped task: no issue_id, no chat_session_id, no run id.// context.type is set so ResolveTaskWorkspaceID can recover workspace.@@ -4256,44 +3443,30 @@ func TestGetTaskGCCheck(t *testing.T) {"workspace_id": testWorkspaceID,})- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, status, priority, context, completed_at- )- VALUES ($1, $2, 'completed', 0, $3, NOW())- RETURNING id- `, agentID, runtimeID, quickContext).Scan(&taskID); err != nil {- t.Fatalf("setup: create quick-create task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "status": "completed",+ "context": quickContext,+ "completed_at": testutil.Raw("NOW()"),+ })defer testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)// Cross-workspace probe.- w := httptest.NewRecorder()req := newDaemonTokenRequest("GET", "/api/daemon/tasks/"+taskID+"/gc-check", nil,"00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "taskId", taskID)- testHandler.GetTaskGCCheck(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.GetTaskGCCheck, req).Want(http.StatusNotFound)// Same-workspace probe — terminal task returns its status.- w = httptest.NewRecorder()req = newDaemonTokenRequest("GET", "/api/daemon/tasks/"+taskID+"/gc-check", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "taskId", taskID)- testHandler.GetTaskGCCheck(w, req)- if w.Code != http.StatusOK {- t.Fatalf("same-workspace token: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetTaskGCCheck, req).Want(http.StatusOK)var resp struct {Status string `json:"status"`CompletedAt string `json:"completed_at"`}- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode: %v", err)- }+ w.JSON(&resp)if resp.Status != "completed" {t.Fatalf("expected status %q, got %q", "completed", resp.Status)}@@ -4332,14 +3505,9 @@ func installFreshMembershipCache(t *testing.T) {func createEphemeralUser(t *testing.T, label string) string {t.Helper()email := fmt.Sprintf("membership-cache-%s-%[email protected]", label, uuid.NewString())- var userID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id- `, "Membership Cache Test "+label, email).Scan(&userID); err != nil {- t.Fatalf("create ephemeral user: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ userID := dbfx.Insert(t, "user", testutil.Cols{+ "name": "Membership Cache Test " + label,+ "email": email,})return userID}@@ -4350,14 +3518,10 @@ func createEphemeralUser(t *testing.T, label string) string {func createEphemeralMember(t *testing.T, workspaceID, label, role string) (string, string) {t.Helper()userID := createEphemeralUser(t, label)- var memberID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3) RETURNING id- `, workspaceID, userID, role).Scan(&memberID); err != nil {- t.Fatalf("create ephemeral member: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM member WHERE id = $1`, memberID)+ memberID := dbfx.Insert(t, "member", testutil.Cols{+ "workspace_id": workspaceID,+ "user_id": userID,+ "role": role,})return userID, memberID}@@ -4438,13 +3602,9 @@ func TestMembershipCache_InvalidatedOnDeleteMember(t *testing.T) {t.Fatal("setup: expected cache hit after Set")}- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/members/"+targetMemberID, nil)req = withURLParams(req, "id", testWorkspaceID, "memberId", targetMemberID)- testHandler.DeleteMember(w, req)- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)if testHandler.MembershipCache.Get(ctx, targetUserID, testWorkspaceID) {t.Fatal("DeleteMember handler did not invalidate membership cache for removed user")@@ -4466,14 +3626,10 @@ func TestMembershipCache_InvalidatedOnUpdateMember(t *testing.T) {targetUserID, targetMemberID := createEphemeralMember(t, testWorkspaceID, "update", "admin")testHandler.MembershipCache.Set(ctx, targetUserID, testWorkspaceID)- w := httptest.NewRecorder()req := newRequest("PUT", "/api/workspaces/"+testWorkspaceID+"/members/"+targetMemberID,map[string]any{"role": "member"})req = withURLParams(req, "id", testWorkspaceID, "memberId", targetMemberID)- testHandler.UpdateMember(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateMember: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusOK)if testHandler.MembershipCache.Get(ctx, targetUserID, testWorkspaceID) {t.Fatal("UpdateMember handler did not invalidate membership cache for updated user")@@ -4495,13 +3651,9 @@ func TestMembershipCache_InvalidatedOnLeaveWorkspace(t *testing.T) {targetUserID, _ := createEphemeralMember(t, testWorkspaceID, "leave", "admin")testHandler.MembershipCache.Set(ctx, targetUserID, testWorkspaceID)- w := httptest.NewRecorder()req := newRequestAsUser(targetUserID, "DELETE", "/api/workspaces/"+testWorkspaceID+"/leave", nil)req = withURLParam(req, "id", testWorkspaceID)- testHandler.LeaveWorkspace(w, req)- if w.Code != http.StatusNoContent {- t.Fatalf("LeaveWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.LeaveWorkspace, req).Want(http.StatusNoContent)if testHandler.MembershipCache.Get(ctx, targetUserID, testWorkspaceID) {t.Fatal("LeaveWorkspace handler did not invalidate membership cache for leaver")@@ -4521,37 +3673,27 @@ func TestMembershipCache_InvalidatedOnDeleteWorkspace(t *testing.T) {const slug = "membership-cache-delete-ws"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4) RETURNING id- `, "Membership Cache Delete WS", slug, "DeleteWorkspace cache invalidation test", "MCD").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Membership Cache Delete WS",+ "slug": slug,+ "description": "DeleteWorkspace cache invalidation test",+ "issue_prefix": "MCD",})// testUser must be an owner of the isolated workspace to call// DeleteWorkspace.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')- `, wsID, testUserID); err != nil {- t.Fatalf("add owner: %v", err)- }+ `, wsID, testUserID)extraUserID, _ := createEphemeralMember(t, wsID, "ws-delete-extra", "admin")testHandler.MembershipCache.Set(ctx, testUserID, wsID)testHandler.MembershipCache.Set(ctx, extraUserID, wsID)- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)req = withURLParam(req, "id", wsID)- testHandler.DeleteWorkspace(w, req)- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusNoContent)if testHandler.MembershipCache.Get(ctx, testUserID, wsID) {t.Fatal("DeleteWorkspace handler did not invalidate owner cache entry")@@ -4566,25 +3708,15 @@ func TestMembershipCache_InvalidatedOnDeleteWorkspace(t *testing.T) {// Returns the task id and the trigger comment id.func createCommentTriggeredClaimTask(t *testing.T, ctx context.Context, agentID, runtimeID, issueID string, parentID *string) (string, string) {t.Helper()- var commentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id)- VALUES ($1, $2, 'member', $3, 'trigger comment', 'comment', $4)- RETURNING id- `, issueID, testWorkspaceID, testUserID, parentID).Scan(&commentID); err != nil {- t.Fatalf("insert trigger comment: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, commentID) })+ commentID := dbfx.Comment(t, issueID, "trigger comment", testutil.Cols{+ "parent_id": parentID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id)- VALUES ($1, $2, $3, 'queued', 0, $4)- RETURNING id- `, agentID, runtimeID, issueID, commentID).Scan(&taskID); err != nil {- t.Fatalf("insert comment-triggered task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "trigger_comment_id": commentID,+ })return taskID, commentID}@@ -4600,17 +3732,11 @@ type claimCommentTaskResp struct {func claimCommentTask(t *testing.T, runtimeID, daemonID string) claimCommentTaskResp {t.Helper()- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp claimCommentTaskResp- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil {t.Fatalf("expected a claimed task, got nil: %s", w.Body.String())}@@ -4632,45 +3758,23 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesNewCommentCount(t *testing.T) {agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment newcount agent")// A prior run establishes the "since" anchor (its started_at, in the past).- var priorTaskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at)- VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 hour', now() - interval '50 minutes')- RETURNING id- `, agentID, runtimeID, issueID).Scan(&priorTaskID); err != nil {- t.Fatalf("insert prior task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, priorTaskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "started_at": testutil.Raw("now() - interval '1 hour'"),+ "completed_at": testutil.Raw("now() - interval '50 minutes'"),+ })- var threadRootID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'same-thread context', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&threadRootID); err != nil {- t.Fatalf("insert trigger thread root: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, threadRootID) })+ threadRootID := dbfx.Comment(t, issueID, "same-thread context")- var unrelatedRootID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)- VALUES ($1, $2, 'member', $3, 'unrelated thread context', 'comment')- RETURNING id- `, issueID, testWorkspaceID, testUserID).Scan(&unrelatedRootID); err != nil {- t.Fatalf("insert unrelated thread root: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, unrelatedRootID) })+ dbfx.Comment(t, issueID, "unrelated thread context")- var agentOwnID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id)- VALUES ($1, $2, 'agent', $3, 'agent self reply', 'comment', $4)- RETURNING id- `, issueID, testWorkspaceID, agentID, threadRootID).Scan(&agentOwnID); err != nil {- t.Fatalf("insert agent self reply: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM comment WHERE id = $1`, agentOwnID) })+ dbfx.Comment(t, issueID, "agent self reply", testutil.Cols{+ "author_type": "agent",+ "author_id": agentID,+ "parent_id": threadRootID,+ })// The trigger comment (member-authored, created now) lands after the anchor// but is injected into the prompt, so it should not be counted.@@ -4704,13 +3808,9 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesInitiator(t *testing.T) {agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment initiator agent")taskID, _ := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "comment-initiator-claim")req = withURLParam(req, "runtimeId", runtimeID)- testHandler.ClaimTaskByRuntime(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)var resp struct {Task *struct {ID string `json:"id"`@@ -4720,9 +3820,7 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesInitiator(t *testing.T) {InitiatorEmail string `json:"initiator_email"`} `json:"task"`}- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode claim response: %v", err)- }+ w.JSON(&resp)if resp.Task == nil || resp.Task.ID != taskID {t.Fatalf("expected claimed task %s, got %s", taskID, w.Body.String())}@@ -4748,15 +3846,13 @@ func TestClaimTaskByRuntime_CommentTaskOmitsDeltaWhenOnlyTriggerIsNew(t *testingruntimeID := createClaimReclaimRuntime(t, ctx, "Comment trigger-only runtime")agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Comment trigger-only agent")- var priorTaskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at, completed_at)- VALUES ($1, $2, $3, 'completed', 0, now() - interval '1 hour', now() - interval '50 minutes')- RETURNING id- `, agentID, runtimeID, issueID).Scan(&priorTaskID); err != nil {- t.Fatalf("insert prior task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, priorTaskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "started_at": testutil.Raw("now() - interval '1 hour'"),+ "completed_at": testutil.Raw("now() - interval '50 minutes'"),+ })_, triggerID := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)@@ -4785,15 +3881,13 @@ func TestClaimTaskByRuntime_CommentResumeDefaultOn(t *testing.T) {// A prior completed task on the same (agent, issue, runtime) with a session.const priorSession = "sess-prior-123"- var priorTaskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, session_id, completed_at)- VALUES ($1, $2, $3, 'completed', 0, $4, now())- RETURNING id- `, agentID, runtimeID, issueID, priorSession).Scan(&priorTaskID); err != nil {- t.Fatalf("insert prior completed task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, priorTaskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "session_id": priorSession,+ "completed_at": testutil.Raw("now()"),+ })createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)@@ -4815,107 +3909,75 @@ func TestAckTaskCancelled(t *testing.T) {ctx := context.Background()var agentID, runtimeID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {- t.Fatalf("setup: get agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID, &runtimeID)- var chatSessionID string- if err := testPool.QueryRow(ctx, `- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)- VALUES ($1, $2, $3, 'cancel ack test')- RETURNING id- `, testWorkspaceID, agentID, testUserID).Scan(&chatSessionID); err != nil {- t.Fatalf("setup: create chat session: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{+ "title": "cancel ack test",+ })// Cancelled chat task with a pending deferred-finalize marker, plus a// transcript row that landed after the cancel (the daemon's late flush).- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, chat_session_id, status, priority,- started_at, completed_at, chat_finalize_deferred_at- )- VALUES ($1, $2, NULL, $3, 'cancelled', 0, now(), now(), now())- RETURNING id- `, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {- t.Fatalf("setup: create task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": nil,+ "chat_session_id": chatSessionID,+ "status": "cancelled",+ "started_at": testutil.Raw("now()"),+ "completed_at": testutil.Raw("now()"),+ "chat_finalize_deferred_at": testutil.Raw("now()"),+ })t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_message WHERE task_id = $1`, taskID)testPool.Exec(ctx, `DELETE FROM chat_message WHERE task_id = $1`, taskID)testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_message (task_id, seq, type, content)VALUES ($1, 1, 'text', 'late flush')- `, taskID); err != nil {- t.Fatalf("setup: insert task message: %v", err)- }+ `, taskID)// Cross-workspace daemon token must still 404 and leave the marker armed.- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,"00000000-0000-0000-0000-000000000000", "attacker-daemon")req = withURLParam(req, "taskId", taskID)- testHandler.AckTaskCancelled(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("AckTaskCancelled with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusNotFound)var deferredAt *time.Time- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1- `, taskID).Scan(&deferredAt); err != nil {- t.Fatalf("read marker: %v", err)- }+ `, taskID).Scan(&deferredAt)if deferredAt == nil {t.Fatal("cross-workspace ack must not claim the marker")}// Same-workspace token settles the deferred finalize.- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "taskId", taskID)- testHandler.AckTaskCancelled(w, req)- if w.Code != http.StatusOK {- t.Fatalf("AckTaskCancelled same-workspace: expected 200, got %d: %s", w.Code, w.Body.String())- }- if err := testPool.QueryRow(ctx, `+ testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)+ dbfx.QueryRow(t, `SELECT chat_finalize_deferred_at FROM agent_task_queue WHERE id = $1- `, taskID).Scan(&deferredAt); err != nil {- t.Fatalf("read marker: %v", err)- }+ `, taskID).Scan(&deferredAt)if deferredAt != nil {t.Errorf("marker should be claimed, got %v", deferredAt)}var stopped int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'assistant' AND content = 'Stopped.'- `, taskID).Scan(&stopped); err != nil {- t.Fatalf("count stopped rows: %v", err)- }+ `, taskID).Scan(&stopped)if stopped != 1 {t.Errorf("Stopped. rows = %d, want 1", stopped)}// Idempotent: a second ack is a no-op (no duplicate Stopped.).- w = httptest.NewRecorder()req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,testWorkspaceID, "legit-daemon")req = withURLParam(req, "taskId", taskID)- testHandler.AckTaskCancelled(w, req)- if w.Code != http.StatusOK {- t.Fatalf("second AckTaskCancelled: expected 200, got %d: %s", w.Code, w.Body.String())- }- if err := testPool.QueryRow(ctx, `+ testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'assistant' AND content = 'Stopped.'- `, taskID).Scan(&stopped); err != nil {- t.Fatalf("count stopped rows: %v", err)- }+ `, taskID).Scan(&stopped)if stopped != 1 {t.Errorf("Stopped. rows after second ack = %d, want 1", stopped)}diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.goindex 409cf50d25..2df321b127 100644--- a/server/internal/handler/dashboard_test.go+++ b/server/internal/handler/dashboard_test.go@@ -8,6 +8,8 @@ import ("strings""testing""time"++ "github.com/multica-ai/multica/server/internal/testutil")// dashboardFixtureTZ is the zone the day-boundary fixtures in this file are@@ -158,27 +160,15 @@ func TestDashboardEndpoints(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1- `, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ `, testWorkspaceID).Scan(&agentID)// Two issues: one bound to a project, one not.- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title)- VALUES ($1, 'dashboard test project')- RETURNING id- `, testWorkspaceID).Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "dashboard test project")// issue.number is `UNIQUE (workspace_id, number)` (migration 020) and// defaults to 0. Two inserts into the same workspace would collide on the@@ -191,16 +181,14 @@ func TestDashboardEndpoints(t *testing.T) {if withProject {pid = projectID}- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, project_id, number)VALUES ($1, 'dashboard test', $2, 'member', $3,(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID, pid).Scan(&id); err != nil {- t.Fatalf("insert issue: %v", err)- }+ `, testWorkspaceID, testUserID, pid).Scan(&id)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, id) })return id}@@ -213,20 +201,18 @@ func TestDashboardEndpoints(t *testing.T) {started, completed := runFinishedToday(pinDayWindowClock(t, time.Now()), dashboardFixtureLoc(t))mkTaskWithUsage := func(issueID string, status string, tokens int64) {- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)- VALUES ($1, $2, $3, $4, $5, $6, now())- RETURNING id- `, agentID, issueID, runtimeID, status, started, completed).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": status,+ "started_at": started,+ "completed_at": completed,+ "created_at": testutil.Raw("now()"),+ })+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'claude-3-5-sonnet', $2, 0, now())- `, taskID, tokens); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID, tokens)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })}@@ -237,11 +223,9 @@ func TestDashboardEndpoints(t *testing.T) {// Phase 3). Drive the underlying window function directly so the// freshly inserted fixture rows are aggregated before assertions —// in production the cron tick handles this with a 5-min lag.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup window: %v", err)- }+ `)type dailyRow struct {Date string `json:"date"`@@ -392,12 +376,8 @@ func TestDashboardUsageDailyBucketsByViewerTimezone(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE runtime_id = $1 AND provider = 'tz-bucket-test'`, runtimeID)@@ -406,7 +386,7 @@ func TestDashboardUsageDailyBucketsByViewerTimezone(t *testing.T) {// previous evening in America/Los_Angeles (UTC-7/-8), so the UTC// viewer and the LA viewer must see this row under different dates.var bucketHour time.Time- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO task_usage_hourly (bucket_hour, workspace_id, runtime_id, agent_id, project_id,provider, model,@@ -420,9 +400,7 @@ func TestDashboardUsageDailyBucketsByViewerTimezone(t *testing.T) {ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATESET input_tokens = EXCLUDED.input_tokensRETURNING bucket_hour- `, testWorkspaceID, runtimeID, agentID).Scan(&bucketHour); err != nil {- t.Fatalf("seed hourly row: %v", err)- }+ `, testWorkspaceID, runtimeID, agentID).Scan(&bucketHour)utcDate := bucketHour.UTC().Format("2006-01-02")laLoc, err := time.LoadLocation("America/Los_Angeles")@@ -475,30 +453,24 @@ func TestDashboardRunTimeDailyBucketsByViewerTimezone(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)// Issue tagged so we can clean up just this test's rows.var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'runtime-daily tz test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// completed_at at 04:00 UTC two days ago — still the prior evening in LA.// started_at 10 minutes earlier so the run has a non-zero duration.var completedAt time.Timevar taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)VALUES ($1, $2, $3, 'completed',@@ -507,9 +479,7 @@ func TestDashboardRunTimeDailyBucketsByViewerTimezone(t *testing.T) {now())RETURNING id, completed_at- `, agentID, issueID, runtimeID).Scan(&taskID, &completedAt); err != nil {- t.Fatalf("insert completed task: %v", err)- }+ `, agentID, issueID, runtimeID).Scan(&taskID, &completedAt)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })utcDate := completedAt.UTC().Format("2006-01-02")@@ -574,22 +544,16 @@ func TestDashboardRunTimeCountsCancelledRuns(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'run-time cancelled test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// Baseline before inserting, so a shared fixture DB with pre-existing@@ -597,26 +561,24 @@ func TestDashboardRunTimeCountsCancelledRuns(t *testing.T) {baseSeconds, baseTasks, baseCancelled := readAgentRunTime(t, agentID)// Stopped 15 minutes into the run: started_at and completed_at both set.- var cancelledTaskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)- VALUES ($1, $2, $3, 'cancelled', now() - interval '15 minutes', now(), now())- RETURNING id- `, agentID, issueID, runtimeID).Scan(&cancelledTaskID); err != nil {- t.Fatalf("insert cancelled task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, cancelledTaskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "cancelled",+ "started_at": testutil.Raw("now() - interval '15 minutes'"),+ "completed_at": testutil.Raw("now()"),+ "created_at": testutil.Raw("now()"),+ })// Cancelled from the queue: never started, so it must not contribute.- var queuedCancelID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)- VALUES ($1, $2, $3, 'cancelled', NULL, now(), now())- RETURNING id- `, agentID, issueID, runtimeID).Scan(&queuedCancelID); err != nil {- t.Fatalf("insert queue-cancelled task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, queuedCancelID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "cancelled",+ "started_at": nil,+ "completed_at": testutil.Raw("now()"),+ "created_at": testutil.Raw("now()"),+ })gotSeconds, gotTasks, gotCancelled := readAgentRunTime(t, agentID)@@ -673,57 +635,43 @@ func TestRollupTaskUsageHourlyIdempotentAndWatermark(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID, taskID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'rollup idempotency', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)VALUES ($1, $2, $3, 'completed', now() - interval '20 minutes') RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }+ `, agentID, issueID, runtimeID).Scan(&taskID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'rollup-idem-model', 3333, 0, now() - interval '20 minutes')- `, taskID); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID)readTotal := func() int64 {var total int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE runtime_id = $1 AND model = 'rollup-idem-model'- `, runtimeID).Scan(&total); err != nil {- t.Fatalf("read total: %v", err)- }+ `, runtimeID).Scan(&total)return total}// Idempotency: two passes over the same range must not double-count.for i := 0; i < 2; i++ {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup pass %d: %v", i, err)- }+ `)}if got := readTotal(); got != 3333 {t.Errorf("idempotency: expected exactly 3333 tokens after two passes, got %d", got)@@ -731,25 +679,19 @@ func TestRollupTaskUsageHourlyIdempotentAndWatermark(t *testing.T) {// Watermark advance: park the watermark an hour back, run the cron// entry, confirm it moved forward to ~now()-5min with no error.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE task_usage_hourly_rollup_stateSET watermark_at = now() - interval '1 hour', last_error = 'stale'WHERE id = 1- `); err != nil {- t.Fatalf("park watermark: %v", err)- }- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {- t.Fatalf("rollup_task_usage_hourly: %v", err)- }+ `)+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly()`)var watermarkAge time.Durationvar lastError *stringvar ageSeconds float64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT EXTRACT(EPOCH FROM (now() - watermark_at)), last_errorFROM task_usage_hourly_rollup_state WHERE id = 1- `).Scan(&ageSeconds, &lastError); err != nil {- t.Fatalf("read rollup state: %v", err)- }+ `).Scan(&ageSeconds, &lastError)watermarkAge = time.Duration(ageSeconds) * time.Second// Watermark should sit at now()-5min (the cron upper bound), well// short of the 1-hour-back value we parked it at.@@ -775,59 +717,49 @@ func TestRollupTaskUsageHourlyReassignBetweenRuntimes(t *testing.T) {ctx := context.Background()oldRuntimeID := handlerTestRuntimeID(t)- var newRuntimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at- )- VALUES ($1, NULL, 'reassign-target-hourly', 'cloud', 'reassign-target-hourly', 'online', '{}'::jsonb, '{}'::jsonb, now())- RETURNING id- `, testWorkspaceID).Scan(&newRuntimeID); err != nil {- t.Fatalf("create dest runtime: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, newRuntimeID) })+ newRuntimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "daemon_id": nil,+ "name": "reassign-target-hourly",+ "runtime_mode": "cloud",+ "provider": "reassign-target-hourly",+ "status": "online",+ "device_info": testutil.Raw("'{}'::jsonb"),+ "metadata": testutil.Raw("'{}'::jsonb"),+ "last_seen_at": testutil.Raw("now()"),+ })var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'reassign hourly test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })usageAt := time.Date(2021, 3, 14, 1, 0, 0, 0, time.UTC)- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', $4) RETURNING id- `, agentID, issueID, oldRuntimeID, usageAt).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })- if _, err := testPool.Exec(ctx, `+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": oldRuntimeID,+ "status": "completed",+ "created_at": usageAt,+ })+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at, updated_at)VALUES ($1, 'claude', 'm-reassign-hourly', 700, 70, $2, $2)- `, taskID, usageAt); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID, usageAt)t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'm-reassign-hourly'`)testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'm-reassign-hourly'`)})runWindow := func(label string) {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('-infinity'::timestamptz, 'infinity'::timestamptz)- `); err != nil {- t.Fatalf("%s: %v", label, err)- }+ `)}runtimeTotal := func(rt string) int64 {var total int64@@ -845,9 +777,7 @@ func TestRollupTaskUsageHourlyReassignBetweenRuntimes(t *testing.T) {// Reassignment fires trg_atq_dirty_hourly, which enqueues the OLD and// NEW runtime buckets (same bucket_hour, two runtime_ids).- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, newRuntimeID, taskID); err != nil {- t.Fatalf("reassign task: %v", err)- }+ dbfx.Exec(t, `UPDATE agent_task_queue SET runtime_id = $1 WHERE id = $2`, newRuntimeID, taskID)var dirtyCount inttestPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE model = 'm-reassign-hourly'`).Scan(&dirtyCount)if dirtyCount != 2 {@@ -880,76 +810,60 @@ func TestRollupTaskUsageHourlyWorkspaceMismatch(t *testing.T) {}ctx := context.Background()- var foreignWorkspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug)- VALUES ('ws-mismatch-hourly', 'ws-mismatch-hourly-' || gen_random_uuid()::text)- RETURNING id- `).Scan(&foreignWorkspaceID); err != nil {- t.Fatalf("create foreign workspace: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID) })+ foreignWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "ws-mismatch-hourly",+ "slug": testutil.Raw("'ws-mismatch-hourly-' || gen_random_uuid()::text"),+ })- var foreignRuntimeID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at- )- VALUES ($1, NULL, 'mismatch-rt-hourly', 'cloud', 'mismatch-rt-hourly', 'online', '{}'::jsonb, '{}'::jsonb, now())- RETURNING id- `, foreignWorkspaceID).Scan(&foreignRuntimeID); err != nil {- t.Fatalf("create foreign runtime: %v", err)- }- var foreignAgentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent (- workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args, mcp_config- )- VALUES ($1, 'mismatch-agent-hourly', '', 'cloud', '{}'::jsonb, $2, 'private', 1, $3, '', '{}'::jsonb, '[]'::jsonb, '[]'::jsonb)- RETURNING id- `, foreignWorkspaceID, foreignRuntimeID, testUserID).Scan(&foreignAgentID); err != nil {- t.Fatalf("create foreign agent: %v", err)- }+ foreignRuntimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "daemon_id": nil,+ "name": "mismatch-rt-hourly",+ "runtime_mode": "cloud",+ "provider": "mismatch-rt-hourly",+ "status": "online",+ "device_info": testutil.Raw("'{}'::jsonb"),+ "metadata": testutil.Raw("'{}'::jsonb"),+ "last_seen_at": testutil.Raw("now()"),+ })+ foreignAgentID := dbfx.Agent(t, "mismatch-agent-hourly", foreignRuntimeID, testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ "mcp_config": testutil.Raw("'[]'::jsonb"),+ })// Issue lives in the primary test workspace; the agent lives in the// foreign one — so agent.workspace_id != issue.workspace_id.var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'mismatch hourly test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })usageAt := time.Date(2021, 9, 9, 1, 0, 0, 0, time.UTC)- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', $4) RETURNING id- `, foreignAgentID, issueID, foreignRuntimeID, usageAt).Scan(&taskID); err != nil {- t.Fatalf("insert atq: %v", err)- }- if _, err := testPool.Exec(ctx, `+ taskID := dbfx.Task(t, foreignAgentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": foreignRuntimeID,+ "status": "completed",+ "created_at": usageAt,+ })+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at, updated_at)VALUES ($1, 'claude', 'm-mismatch-hourly', 333, 33, $2, $2)- `, taskID, usageAt); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID, usageAt)t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'm-mismatch-hourly'`)testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'm-mismatch-hourly'`)})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('-infinity'::timestamptz, 'infinity'::timestamptz)- `); err != nil {- t.Fatalf("rollup: %v", err)- }+ `)wsTotal := func(ws string) int64 {var total int64@@ -979,95 +893,67 @@ func TestDashboardRollupReattributesOnProjectChange(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)mkProject := func(name string) string {- var id string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id- `, testWorkspaceID, name).Scan(&id); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, id) })+ id := dbfx.Project(t, name)return id}projectA := mkProject("dashboard reattr A")projectB := mkProject("dashboard reattr B")var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, project_id, number)VALUES ($1, 'reattr issue', $2, 'member', $3,(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID, projectA).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID, projectA).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', now()) RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "created_at": testutil.Raw("now()"),+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'claude-3-5-sonnet', 7777, 0, now())- `, taskID); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID)// First rollup pass: tokens attributed to project A.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup A: %v", err)- }+ `)var aTokens int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3- `, testWorkspaceID, projectA, agentID).Scan(&aTokens); err != nil {- t.Fatalf("read A rollup: %v", err)- }+ `, testWorkspaceID, projectA, agentID).Scan(&aTokens)if aTokens < 7777 {t.Fatalf("project A: expected >=7777 tokens after first rollup, got %d", aTokens)}// Move the issue to project B. Trigger enqueues both A and B buckets.- if _, err := testPool.Exec(ctx, `UPDATE issue SET project_id = $1 WHERE id = $2`, projectB, issueID); err != nil {- t.Fatalf("reassign project: %v", err)- }+ dbfx.Exec(t, `UPDATE issue SET project_id = $1 WHERE id = $2`, projectB, issueID)// Second rollup pass: A bucket drops to zero (deleted_empty), B// bucket gets the tokens.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup B: %v", err)- }+ `)var bTokens, aTokensAfter int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3- `, testWorkspaceID, projectB, agentID).Scan(&bTokens); err != nil {- t.Fatalf("read B rollup: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, testWorkspaceID, projectB, agentID).Scan(&bTokens)+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3- `, testWorkspaceID, projectA, agentID).Scan(&aTokensAfter); err != nil {- t.Fatalf("read A rollup after move: %v", err)- }+ `, testWorkspaceID, projectA, agentID).Scan(&aTokensAfter)if bTokens < 7777 {t.Errorf("project B: expected >=7777 tokens after reassign + rollup, got %d", bTokens)}@@ -1086,64 +972,44 @@ func TestDashboardRollupClearsOnIssueDelete(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title) VALUES ($1, 'dashboard cascade test') RETURNING id- `, testWorkspaceID).Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "dashboard cascade test")var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, project_id, number)VALUES ($1, 'cascade issue', $2, 'member', $3,(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID, projectID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID, projectID).Scan(&issueID)// No t.Cleanup deleting the issue — that's what the test exercises.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', now()) RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "created_at": testutil.Raw("now()"),+ })// Don't bother cleaning up taskID either; cascade will take it.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'claude-3-5-sonnet', 4242, 0, now())- `, taskID); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID)// First rollup: project bucket exists with 4242 tokens.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup before delete: %v", err)- }+ `)var before int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2- `, testWorkspaceID, projectID).Scan(&before); err != nil {- t.Fatalf("read before: %v", err)- }+ `, testWorkspaceID, projectID).Scan(&before)if before < 4242 {t.Fatalf("project bucket: expected >=4242 tokens before delete, got %d", before)}@@ -1151,22 +1017,16 @@ func TestDashboardRollupClearsOnIssueDelete(t *testing.T) {// Delete the issue. Cascade removes atq + task_usage. The issue// BEFORE DELETE trigger should have enqueued the project bucket// before the cascade started.- if _, err := testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID); err != nil {- t.Fatalf("delete issue: %v", err)- }+ dbfx.Exec(t, `DELETE FROM issue WHERE id = $1`, issueID)- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup after delete: %v", err)- }+ `)var after int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2- `, testWorkspaceID, projectID).Scan(&after); err != nil {- t.Fatalf("read after: %v", err)- }+ `, testWorkspaceID, projectID).Scan(&after)if after != 0 {t.Errorf("project bucket: expected 0 tokens after issue delete, got %d", after)}@@ -1184,43 +1044,32 @@ func TestDashboardRollupReattributesOnLinkTaskToIssue(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)// Quick-create task: issue_id is NULL at creation time.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, context, created_at)- VALUES ($1, NULL, $2, 'completed', '{}'::jsonb, now()) RETURNING id- `, agentID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert quick-create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": nil,+ "runtime_id": runtimeID,+ "status": "completed",+ "context": testutil.Raw("'{}'::jsonb"),+ "created_at": testutil.Raw("now()"),+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'claude-3-5-sonnet', 1234, 0, now())- `, taskID); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID)// First rollup: tokens attributed to the no-project bucket (NULL).- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup pre-link: %v", err)- }+ `)var nullBefore int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id IS NULL AND agent_id = $2- `, testWorkspaceID, agentID).Scan(&nullBefore); err != nil {- t.Fatalf("read NULL bucket pre-link: %v", err)- }+ `, testWorkspaceID, agentID).Scan(&nullBefore)if nullBefore < 1234 {t.Fatalf("NULL bucket: expected >=1234 tokens pre-link, got %d", nullBefore)}@@ -1229,51 +1078,35 @@ func TestDashboardRollupReattributesOnLinkTaskToIssue(t *testing.T) {// uses. The atq trigger should enqueue OLD (NULL project) AND NEW// (the project's id) so the next rollup tick zeroes the NULL bucket// and populates the project bucket.- var projectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title) VALUES ($1, 'dashboard link test') RETURNING id- `, testWorkspaceID).Scan(&projectID); err != nil {- t.Fatalf("create project: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID) })+ projectID := dbfx.Project(t, "dashboard link test")var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, project_id, number)VALUES ($1, 'link test issue', $2, 'member', $3,(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID, projectID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID, projectID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// Mirror LinkTaskToIssue's UPDATE shape.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE agent_task_queue SET issue_id = $1 WHERE id = $2 AND issue_id IS NULL- `, issueID, taskID); err != nil {- t.Fatalf("link task to issue: %v", err)- }+ `, issueID, taskID)- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup post-link: %v", err)- }+ `)var projectAfter, nullAfter int64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id = $2 AND agent_id = $3- `, testWorkspaceID, projectID, agentID).Scan(&projectAfter); err != nil {- t.Fatalf("read project bucket post-link: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, testWorkspaceID, projectID, agentID).Scan(&projectAfter)+ dbfx.QueryRow(t, `SELECT COALESCE(SUM(input_tokens), 0) FROM task_usage_hourlyWHERE workspace_id = $1 AND project_id IS NULL AND agent_id = $2- `, testWorkspaceID, agentID).Scan(&nullAfter); err != nil {- t.Fatalf("read NULL bucket post-link: %v", err)- }+ `, testWorkspaceID, agentID).Scan(&nullAfter)if projectAfter < 1234 {t.Errorf("project bucket: expected >=1234 tokens after link, got %d", projectAfter)}@@ -1304,7 +1137,7 @@ func TestPruneTaskUsageHourlyDirty(t *testing.T) {testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE provider = $1`, tag)})seed := func(model, age string) {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage_hourly_dirty (bucket_hour, workspace_id, runtime_id, agent_id, project_id,provider, model, enqueued_at@@ -1313,9 +1146,7 @@ func TestPruneTaskUsageHourlyDirty(t *testing.T) {date_trunc('hour', now()), gen_random_uuid(), gen_random_uuid(),gen_random_uuid(), NULL, $1, $2, now() - $3::interval)- `, tag, model, age); err != nil {- t.Fatalf("seed dirty row %s: %v", model, err)- }+ `, tag, model, age)}countModel := func(model string) int {var n int@@ -1331,9 +1162,7 @@ func TestPruneTaskUsageHourlyDirty(t *testing.T) {// Default 7-day retention: the 8-day row goes, the 1-day row stays.var pruned int64- if err := testPool.QueryRow(ctx, `SELECT prune_task_usage_hourly_dirty()`).Scan(&pruned); err != nil {- t.Fatalf("prune (default retention): %v", err)- }+ dbfx.QueryRow(t, `SELECT prune_task_usage_hourly_dirty()`).Scan(&pruned)if pruned < 1 {t.Errorf("expected prune to report at least the one stale row deleted, got %d", pruned)}@@ -1345,9 +1174,7 @@ func TestPruneTaskUsageHourlyDirty(t *testing.T) {}// An explicit retention shorter than the surviving row's age drops it.- if _, err := testPool.Exec(ctx, `SELECT prune_task_usage_hourly_dirty(interval '12 hours')`); err != nil {- t.Fatalf("prune (12h retention): %v", err)- }+ dbfx.Exec(t, `SELECT prune_task_usage_hourly_dirty(interval '12 hours')`)if got := countModel("fresh-row"); got != 0 {t.Errorf("12h-retention prune: expected fresh row deleted, still %d present", got)}@@ -1355,9 +1182,7 @@ func TestPruneTaskUsageHourlyDirty(t *testing.T) {// The cron entry folds the prune in so operators do// not need a second scheduled job. A single tick must drop a stale row.seed("cron-fold-row", "9 days")- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {- t.Fatalf("rollup_task_usage_hourly: %v", err)- }+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly()`)if got := countModel("cron-fold-row"); got != 0 {t.Errorf("cron entry did not fold in the prune: stale row still present (%d)", got)}@@ -1390,28 +1215,22 @@ func TestRollupTaskUsageHourlyCapsWindowAtOneDay(t *testing.T) {})park := func(behind string) {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `UPDATE task_usage_hourly_rollup_stateSET watermark_at = now() - $1::interval, last_error = NULLWHERE id = 1- `, behind); err != nil {- t.Fatalf("park watermark: %v", err)- }+ `, behind)}ageDays := func() float64 {var sec float64- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT EXTRACT(EPOCH FROM (now() - watermark_at))FROM task_usage_hourly_rollup_state WHERE id = 1- `).Scan(&sec); err != nil {- t.Fatalf("read watermark: %v", err)- }+ `).Scan(&sec)return sec / 86400}tick := func(label string) {- if _, err := testPool.Exec(ctx, `SELECT rollup_task_usage_hourly()`); err != nil {- t.Fatalf("%s: %v", label, err)- }+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly()`)}// Park 3 days back. One tick advances by exactly one day (v_from + 1d,@@ -1454,32 +1273,24 @@ func TestDashboardUsageDailyCrossMidnightFullPipeline(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'cross-midnight pipeline test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', now()) RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "created_at": testutil.Raw("now()"),+ })// Raw task_usage at 00:30 UTC two days ago — genuinely near UTC// midnight. 00:30 UTC is still the PRIOR evening (~16:30/17:30) in@@ -1487,26 +1298,22 @@ func TestDashboardUsageDailyCrossMidnightFullPipeline(t *testing.T) {// must see this row under different calendar days. Using CURRENT_DATE// keeps the row inside the days=10 window without a fixed-date drift.var usageAt time.Time- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)VALUES ($1, 'claude', 'cross-midnight-model', 8888, 0,((CURRENT_DATE - 2)::timestamp + interval '30 minutes') AT TIME ZONE 'UTC')RETURNING created_at- `, taskID).Scan(&usageAt); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ `, taskID).Scan(&usageAt)t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'cross-midnight-model'`)})// Run the rollup so the raw row is aggregated into task_usage_hourly.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("rollup window: %v", err)- }+ `)utcDate := usageAt.UTC().Format("2006-01-02")laLoc, err := time.LoadLocation("America/Los_Angeles")@@ -1565,41 +1372,33 @@ func TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'tu-delete trigger test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, created_at)- VALUES ($1, $2, $3, 'completed', now() - interval '30 minutes') RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "created_at": testutil.Raw("now() - interval '30 minutes'"),+ })- var usageID string- if err := testPool.QueryRow(ctx, `- INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)- VALUES ($1, 'claude', 'tu-delete-model', 5050, 0, now() - interval '30 minutes')- RETURNING id- `, taskID).Scan(&usageID); err != nil {- t.Fatalf("insert task_usage: %v", err)- }+ usageID := dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": taskID,+ "provider": "claude",+ "model": "tu-delete-model",+ "input_tokens": 5050,+ "output_tokens": 0,+ "created_at": testutil.Raw("now() - interval '30 minutes'"),+ })t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE model = 'tu-delete-model'`)testPool.Exec(ctx, `DELETE FROM task_usage_hourly_dirty WHERE model = 'tu-delete-model'`)@@ -1614,11 +1413,9 @@ func TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete(t *testing.T) {return total}runWindow := func(label string) {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')- `); err != nil {- t.Fatalf("%s: %v", label, err)- }+ `)}runWindow("initial rollup")@@ -1628,9 +1425,7 @@ func TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete(t *testing.T) {// Delete the task_usage row directly — fires trg_tu_dirty_hourly,// which enqueues the bucket on task_usage_hourly_dirty.- if _, err := testPool.Exec(ctx, `DELETE FROM task_usage WHERE id = $1`, usageID); err != nil {- t.Fatalf("delete task_usage: %v", err)- }+ dbfx.Exec(t, `DELETE FROM task_usage WHERE id = $1`, usageID)var dirtyCount inttestPool.QueryRow(ctx, `SELECT COUNT(*) FROM task_usage_hourly_dirty WHERE model = 'tu-delete-model'`).Scan(&dirtyCount)if dirtyCount != 1 {@@ -1657,22 +1452,16 @@ func TestDashboardFailuresCountNeverStartedTasks(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'failures rollup test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// Same window-safe fixture as TestDashboardEndpoints: the by-agent case@@ -1684,15 +1473,15 @@ func TestDashboardFailuresCountNeverStartedTasks(t *testing.T) {// startedAt is nullable so the queue-expiry case can be modelled exactly:// completed_at set, started_at absent.mkTask := func(status string, failureReason any, startedAt any) {- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, failure_reason, created_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, now())- RETURNING id- `, agentID, issueID, runtimeID, status, startedAt, completed, failureReason).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": status,+ "started_at": startedAt,+ "completed_at": completed,+ "failure_reason": failureReason,+ "created_at": testutil.Raw("now()"),+ })}mkTask("completed", nil, started)@@ -1779,41 +1568,30 @@ func TestDashboardFailuresByAgentUsesExactWindow(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'failures window test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// One failure at noon YESTERDAY (UTC). days=1 means "today", so neither// endpoint may count it. Noon avoids the midnight edge in either// direction.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, failure_reason, created_at)- VALUES (- $1, $2, $3, 'failed',- ((CURRENT_DATE - 1)::timestamp + interval '11 hours') AT TIME ZONE 'UTC',- ((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC',- 'timeout', now()- )- RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "failed",+ "started_at": testutil.Raw("((CURRENT_DATE - 1)::timestamp + interval '11 hours') AT TIME ZONE 'UTC'"),+ "completed_at": testutil.Raw("((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC'"),+ "failure_reason": "timeout",+ "created_at": testutil.Raw("now()"),+ })type failureRow struct {FailureReason string `json:"failure_reason"`@@ -1876,22 +1654,16 @@ func TestDashboardPerAgentRollupsUseExactWindow(t *testing.T) {ctx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'per-agent window test', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })// A token bucket at noon YESTERDAY, under a provider/model pair no other@@ -1904,7 +1676,7 @@ func TestDashboardPerAgentRollupsUseExactWindow(t *testing.T) {t.Cleanup(func() {testPool.Exec(ctx, `DELETE FROM task_usage_hourly WHERE runtime_id = $1 AND provider = $2`, runtimeID, windowProvider)})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO task_usage_hourly (bucket_hour, workspace_id, runtime_id, agent_id, project_id,provider, model,@@ -1917,27 +1689,19 @@ func TestDashboardPerAgentRollupsUseExactWindow(t *testing.T) {)ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATESET input_tokens = EXCLUDED.input_tokens- `, testWorkspaceID, runtimeID, agentID, windowProvider, windowModel); err != nil {- t.Fatalf("seed hourly row: %v", err)- }+ `, testWorkspaceID, runtimeID, agentID, windowProvider, windowModel)// A terminal task that ran for 900s and completed at noon yesterday, for// the agent-runtime half. Noon keeps both fixtures clear of the midnight// edge in either direction.- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)- VALUES (- $1, $2, $3, 'completed',- ((CURRENT_DATE - 1)::timestamp + interval '11 hours 45 minutes') AT TIME ZONE 'UTC',- ((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC',- now()- )- RETURNING id- `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "started_at": testutil.Raw("((CURRENT_DATE - 1)::timestamp + interval '11 hours 45 minutes') AT TIME ZONE 'UTC'"),+ "completed_at": testutil.Raw("((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC'"),+ "created_at": testutil.Raw("now()"),+ })seededTokens := func(body []byte) int64 {var rows []struct {@@ -2052,33 +1816,26 @@ func dashboardRunTimeSeconds(t *testing.T, at time.Time, loc *time.Location, quectx := context.Background()var runtimeID, agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("fetch agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID)+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)var issueID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)VALUES ($1, 'clock fixture', $2, 'member',(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))RETURNING id- `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ `, testWorkspaceID, testUserID).Scan(&issueID)t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })started, completed := runFinishedToday(at, loc)- var taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, created_at)- VALUES ($1, $2, $3, 'completed', $4, $5, $4)- RETURNING id- `, agentID, issueID, runtimeID, started, completed).Scan(&taskID); err != nil {- t.Fatalf("create task: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "started_at": started,+ "completed_at": completed,+ "created_at": started,+ })w := httptest.NewRecorder()testHandler.GetDashboardAgentRunTime(w, newRequest("GET", "/api/dashboard/agent-runtime?"+query, nil))diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex 1ca9c09c10..52a685e21e 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -25,6 +25,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -388,15 +389,11 @@ func TestWebhook_MergedPR_AdvancesLinkedIssueToDone(t *testing.T) {t.Setenv("GITHUB_WEBHOOK_SECRET", secret)// Seed an issue we expect the webhook to close out.- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "PR auto-merge test","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -448,14 +445,10 @@ func TestWebhook_MergedPR_AdvancesLinkedIssueToDone(t *testing.T) {mac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- w = httptest.NewRecorder()req2 := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))req2.Header.Set("X-GitHub-Event", "pull_request")req2.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(w, req2)- if w.Code != http.StatusAccepted {- t.Fatalf("webhook: expected 202, got %d (%s)", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.HandleGitHubWebhook, req2).Want(http.StatusAccepted)// Verify PR row + link + issue status.pr, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{@@ -499,15 +492,11 @@ func TestWebhook_MergedPR_PreservesCancelled(t *testing.T) {secret := "cancelled-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Already cancelled","status": "cancelled",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -544,11 +533,10 @@ func TestWebhook_MergedPR_PreservesCancelled(t *testing.T) {mac.Write(body)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- w = httptest.NewRecorder()req2 := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(body))req2.Header.Set("X-GitHub-Event", "pull_request")req2.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(w, req2)+ w = testutil.Call(t, testHandler.HandleGitHubWebhook, req2)updated, err := testHandler.Queries.GetIssue(ctx, parseUUID(created.ID))if err != nil {@@ -613,15 +601,11 @@ func TestWebhook_MergedPR_WaitsForOpenSibling(t *testing.T) {secret := "multi-pr-test-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Multi-PR auto-merge test","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -678,14 +662,10 @@ func TestWebhook_MergedPR_WaitsForOpenSibling(t *testing.T) {mac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()hookReq := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))hookReq.Header.Set("X-GitHub-Event", "pull_request")hookReq.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, hookReq)- if rec.Code != http.StatusAccepted {- t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())- }+ testutil.Call(t, testHandler.HandleGitHubWebhook, hookReq).Want(http.StatusAccepted)}// Open PR A and PR B against two repos so the (workspace, owner, repo,@@ -766,11 +746,10 @@ func firePullRequestWebhook(t *testing.T, secret, identifier string, installatiomac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()hookReq := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))hookReq.Header.Set("X-GitHub-Event", "pull_request")hookReq.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, hookReq)+ rec := testutil.Call(t, testHandler.HandleGitHubWebhook, hookReq)if rec.Code != http.StatusAccepted {t.Fatalf("webhook %s pr=%d state=%s: expected 202, got %d (%s)",repo, prNumber, prState, rec.Code, rec.Body.String())@@ -789,15 +768,11 @@ func TestWebhook_ClosedSiblingAfterMerge(t *testing.T) {secret := "closed-sibling-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Closed sibling after merge","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -857,15 +832,11 @@ func TestWebhook_AllClosedWithoutMerge(t *testing.T) {secret := "all-closed-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "All closed no merge","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -934,11 +905,10 @@ func fireBareWebhook(t *testing.T, secret string, installationID int64, prNumbermac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()req := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))req.Header.Set("X-GitHub-Event", "pull_request")req.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, req)+ rec := testutil.Call(t, testHandler.HandleGitHubWebhook, req)if rec.Code != http.StatusAccepted {t.Fatalf("webhook pr=%d: expected 202, got %d (%s)", prNumber, rec.Code, rec.Body.String())}@@ -959,12 +929,11 @@ func TestWebhook_MergedPR_OnlyClosesIdentifiersWithClosingKeyword(t *testing.T)// Three issues to mention in the same PR body.createIssue := func(title string) IssueResponse {t.Helper()- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "in_progress",})- testHandler.CreateIssue(w, req)+ w := testutil.Call(t, testHandler.CreateIssue, req)if w.Code != http.StatusCreated {t.Fatalf("CreateIssue %q: %d %s", title, w.Code, w.Body.String())}@@ -1028,11 +997,9 @@ func TestWebhook_MergedPR_OnlyClosesIdentifiersWithClosingKeyword(t *testing.T)// The link row still exists — flagged reference_only, not deleted — so// close_intent stays trackable across later edits.var refOnly bool- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT reference_only FROM issue_pull_request WHERE issue_id = $1`, issue.ID,- ).Scan(&refOnly); err != nil {- t.Fatalf("query reference_only(%s): %v", issue.Identifier, err)- }+ ).Scan(&refOnly)if !refOnly {t.Errorf("expected %s link to be reference_only, got false", issue.Identifier)}@@ -1067,15 +1034,11 @@ func TestWebhook_MergedPR_TitlePrefixDoesNotClose(t *testing.T) {secret := "title-prefix-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "title-prefix repro","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1128,15 +1091,11 @@ func TestWebhook_MergedPR_BranchNameDoesNotClose(t *testing.T) {secret := "branch-name-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "branch-name repro","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1231,11 +1190,10 @@ func firePRWebhook(t *testing.T, secret string, installationID int64, prNumber imac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()req := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))req.Header.Set("X-GitHub-Event", "pull_request")req.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, req)+ rec := testutil.Call(t, testHandler.HandleGitHubWebhook, req)if rec.Code != http.StatusAccepted {t.Fatalf("webhook pr=%d (%s): expected 202, got %d (%s)", prNumber, lifecycle, rec.Code, rec.Body.String())}@@ -1249,15 +1207,11 @@ func TestWebhook_CloseKeywordRemovedBeforeMergeDoesNotClose(t *testing.T) {secret := "close-intent-removal-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "close intent can be removed","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1298,15 +1252,11 @@ func TestWebhook_CloseKeywordRemovedBeforeMergeDoesNotClose(t *testing.T) {t.Fatalf("merged_with_close_intent_count = %d, want 0", counts.MergedWithCloseIntentCount)}- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "post merge close keyword is link only","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue second: %d %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var second IssueResponsejson.NewDecoder(w.Body).Decode(&second)t.Cleanup(func() {@@ -1358,15 +1308,11 @@ func TestWebhook_LinkOnlySiblingMergeAfterCloseKeywordPR(t *testing.T) {secret := "link-only-sibling-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "needs two prs","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1438,15 +1384,11 @@ func TestWebhook_BareBodyMentionHiddenFromPRList(t *testing.T) {secret := "bare-mention-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "mentioned in passing","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1510,15 +1452,11 @@ func TestWebhook_HiddenBodyMentionDoesNotBlockAutoAdvance(t *testing.T) {secret := "hidden-mention-gate-secret"t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "closing PR plus invisible mention","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1645,11 +1583,10 @@ func firePullRequestWebhookWithHead(t *testing.T, secret, identifier string, insmac.Write(raw)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()hookReq := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))hookReq.Header.Set("X-GitHub-Event", "pull_request")hookReq.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, hookReq)+ rec := testutil.Call(t, testHandler.HandleGitHubWebhook, hookReq)if rec.Code != http.StatusAccepted {t.Fatalf("webhook %s pr=%d action=%s: expected 202, got %d (%s)",repo, prNumber, action, rec.Code, rec.Body.String())@@ -1659,15 +1596,11 @@ func firePullRequestWebhookWithHead(t *testing.T, secret, identifier string, insfunc setupPRTestIssue(t *testing.T, ctx context.Context, secret string) (IssueResponse, int64) {t.Helper()t.Setenv("GITHUB_WEBHOOK_SECRET", secret)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "PR CI test","status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1891,14 +1824,12 @@ func TestGitHubRoutes_RoleGating(t *testing.T) {_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)_, _ = testPool.Exec(ctx, `DELETE FROM "user" WHERE email LIKE $1`, "github-routes-"+slug+"-%")- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description, issue_prefix)-VALUES ($1, $2, $3, $4)-RETURNING id-`, "GitHub Routes Role Gating", slug, "github routes role gating", "GRG").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "GitHub Routes Role Gating",+ "slug": slug,+ "description": "github routes role gating",+ "issue_prefix": "GRG",+ })// Three workspace members + one outsider. We attach the requesting user// via the X-User-ID header so the middleware reads them off the auth@@ -1907,11 +1838,9 @@ RETURNING idt.Helper()var id stringemail := fmt.Sprintf("github-routes-%s-%[email protected]", slug, label)- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id-`, "GHR "+label, email).Scan(&id); err != nil {- t.Fatalf("create user %s: %v", label, err)- }+`, "GHR "+label, email).Scan(&id)return id}adminUserID := mkUser(t, "admin")@@ -1924,11 +1853,9 @@ INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id{adminUserID, "admin"},{memberUserID, "member"},} {- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3)-`, wsID, m.userID, m.role); err != nil {- t.Fatalf("insert member (%s): %v", m.role, err)- }+`, wsID, m.userID, m.role)}const installationID int64 = 90909090@@ -2031,9 +1958,7 @@ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3)t.Errorf("admin DELETE installation: want 204, got %d", code)}var remaining int- if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM github_installation WHERE id = $1`, uuidToString(createdInst.ID)).Scan(&remaining); err != nil {- t.Fatalf("verify deletion: %v", err)- }+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM github_installation WHERE id = $1`, uuidToString(createdInst.ID)).Scan(&remaining)if remaining != 0 {t.Errorf("expected installation row gone after admin DELETE, got %d remaining", remaining)}@@ -2095,28 +2020,20 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {t.Setenv("GITHUB_WEBHOOK_SECRET", secret)// Create parent (open) + child (in_progress) pair.- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "PR-merge parent " + time.Now().Format(time.RFC3339Nano),"status": "in_progress",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue parent: %d %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var parent IssueResponsejson.NewDecoder(w.Body).Decode(&parent)- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "PR-merge child " + time.Now().Format(time.RFC3339Nano),"status": "in_progress","parent_issue_id": parent.ID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue child: %d %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var child IssueResponsejson.NewDecoder(w.Body).Decode(&child)@@ -2167,14 +2084,10 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {mac.Write(body)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- w = httptest.NewRecorder()req2 := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(body))req2.Header.Set("X-GitHub-Event", "pull_request")req2.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(w, req2)- if w.Code != http.StatusAccepted {- t.Fatalf("webhook: expected 202, got %d (%s)", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.HandleGitHubWebhook, req2).Want(http.StatusAccepted)// Child must now be done (sanity check — the existing path).updatedChild, err := testHandler.Queries.GetIssue(ctx, parseUUID(child.ID))@@ -2187,23 +2100,19 @@ func TestWebhook_MergedPR_ChildWithParent_NotifiesParent(t *testing.T) {// Parent must have received exactly one platform-generated system comment.var sysCount int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM comment WHERE issue_id = $1 AND author_type = 'system'`,parent.ID,- ).Scan(&sysCount); err != nil {- t.Fatalf("count system comments on parent: %v", err)- }+ ).Scan(&sysCount)if sysCount != 1 {t.Fatalf("expected 1 system comment on parent after PR-merge auto-done, got %d", sysCount)}var content string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT content FROM comment WHERE issue_id = $1 AND author_type = 'system' LIMIT 1`,parent.ID,- ).Scan(&content); err != nil {- t.Fatalf("read system comment: %v", err)- }+ ).Scan(&content)if !strings.Contains(content, child.Identifier) {t.Errorf("system comment should reference child identifier %q, got: %s", child.Identifier, content)}@@ -2630,14 +2539,10 @@ func TestWebhook_InstallationCreatedRefreshesUnknownLogin(t *testing.T) {mac.Write(body)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()req := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(body))req.Header.Set("X-GitHub-Event", "installation")req.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, req)- if rec.Code != http.StatusAccepted {- t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())- }+ testutil.Call(t, testHandler.HandleGitHubWebhook, req).Want(http.StatusAccepted)// (a) The row's account_login must be the real login, not "unknown".rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(ctx, installationID)@@ -2746,12 +2651,10 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {}var pendingLogin string- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT account_login FROM github_pending_installation WHERE installation_id = $1`,installationID,- ).Scan(&pendingLogin); err != nil {- t.Fatalf("pending installation row not stored: %v", err)- }+ ).Scan(&pendingLogin)if pendingLogin != "pending-octocat" {t.Fatalf("pending account_login = %q, want pending-octocat", pendingLogin)}@@ -2792,12 +2695,10 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {}var pendingCount int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM github_pending_installation WHERE installation_id = $1`,installationID,- ).Scan(&pendingCount); err != nil {- t.Fatalf("count pending installation: %v", err)- }+ ).Scan(&pendingCount)if pendingCount != 0 {t.Fatalf("pending installation row should be consumed, got count %d", pendingCount)}@@ -2999,11 +2900,9 @@ func TestWebhook_PullRequest_AmbiguousCloseAcrossWorkspaces(t *testing.T) {}var closeIntent bool- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, tc.issueID,- ).Scan(&closeIntent); err != nil {- t.Fatalf("%s: read close_intent: %v", tc.name, err)- }+ ).Scan(&closeIntent)if closeIntent {t.Errorf("%s: close_intent must be withheld while the identifier is ambiguous", tc.name)}@@ -3170,11 +3069,9 @@ func TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent(t *testing.// Valid JSONB, but the auto-link flag is not a bool — the settings blob// parses in Postgres and fails in the handler, which is exactly the// "we could not find out" case.- if _, err := testPool.Exec(ctx,+ dbfx.Exec(t,`UPDATE workspace SET settings = '{"github_auto_link_prs_enabled": 5}'::jsonb WHERE id = $1`, wsA,- ); err != nil {- t.Fatalf("corrupt workspace settings: %v", err)- }+ )t.Cleanup(func() {bg := context.Background()@@ -3188,11 +3085,9 @@ func TestWebhook_PullRequest_UnreadableWorkspaceWithholdsCloseIntent(t *testing.firePullRequestWebhook(t, secret, issueB.Identifier, installationID, repo, prNumber, "merged")var closeIntent bool- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT close_intent FROM issue_pull_request WHERE issue_id = $1`, parseUUID(issueB.ID),- ).Scan(&closeIntent); err != nil {- t.Fatalf("read close_intent: %v", err)- }+ ).Scan(&closeIntent)if closeIntent {t.Error("close_intent must be withheld when a bound workspace could not be inspected")}@@ -3366,14 +3261,10 @@ func TestWebhook_UninstallDeletesAllBindings(t *testing.T) {mac := hmac.New(sha256.New, []byte(secret))mac.Write(body)sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))- rec := httptest.NewRecorder()req := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(body))req.Header.Set("X-GitHub-Event", "installation")req.Header.Set("X-Hub-Signature-256", sig)- testHandler.HandleGitHubWebhook(rec, req)- if rec.Code != http.StatusAccepted {- t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())- }+ testutil.Call(t, testHandler.HandleGitHubWebhook, req).Want(http.StatusAccepted)rows, err := testHandler.Queries.ListGitHubInstallationsByInstallationID(ctx, installationID)if err != nil {diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex b7d37c88f3..b5c833f213 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -19,6 +19,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -29,6 +30,11 @@ var testUserID stringvar testWorkspaceID stringvar testRuntimeID string+// dbfx builds the rows these tests act on and removes them again when the test+// that asked for them ends. New tests build fixtures through it rather than+// writing an INSERT and a matching DELETE by hand; see internal/testutil.+var dbfx *testutil.Fixture+const (handlerTestEmail = "[email protected]"handlerTestName = "Handler Test User"@@ -82,6 +88,7 @@ func TestMain(m *testing.M) {pool.Close()os.Exit(1)}+ dbfx = testutil.New(pool, testWorkspaceID, testUserID)code := m.Run()if err := cleanupHandlerTestFixture(context.Background(), pool); err != nil {@@ -200,14 +207,9 @@ func withURLParam(req *http.Request, key, value string) *http.Request {func setWorkspaceIssuePrefixForTest(t *testing.T, prefix string) {t.Helper()- ctx := context.Background()var previous string- if err := testPool.QueryRow(ctx, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous); err != nil {- t.Fatalf("load workspace prefix: %v", err)- }- if _, err := testPool.Exec(ctx, `UPDATE workspace SET issue_prefix = $1 WHERE id = $2`, prefix, testWorkspaceID); err != nil {- t.Fatalf("set workspace prefix: %v", err)- }+ dbfx.QueryRow(t, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous)+ dbfx.Exec(t, `UPDATE workspace SET issue_prefix = $1 WHERE id = $2`, prefix, testWorkspaceID)t.Cleanup(func() {testPool.Exec(context.Background(), `UPDATE workspace SET issue_prefix = $1 WHERE id = $2`, previous, testWorkspaceID)})@@ -217,12 +219,10 @@ func handlerTestRuntimeID(t *testing.T) string {t.Helper()var runtimeID string- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT id FROM agent_runtime WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,testWorkspaceID,- ).Scan(&runtimeID); err != nil {- t.Fatalf("failed to load handler test runtime: %v", err)- }+ ).Scan(&runtimeID)return runtimeID}@@ -230,30 +230,24 @@ func handlerTestRuntimeID(t *testing.T) string {func createHandlerTestAgent(t *testing.T, name string, mcpConfig []byte) string {t.Helper()- var agentID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO agent (- workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id,- instructions, custom_env, custom_args, mcp_config- )- VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 'public_to', 1, $4, '', '{}'::jsonb, '[]'::jsonb, $5)- RETURNING id- `, testWorkspaceID, name, handlerTestRuntimeID(t), testUserID, mcpConfig).Scan(&agentID); err != nil {- t.Fatalf("failed to create handler test agent: %v", err)- }+ agentID := dbfx.Agent(t, name, handlerTestRuntimeID(t), testutil.Cols{+ "visibility": "workspace",+ "permission_mode": "public_to",+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ "mcp_config": mcpConfig,+ })// Generic test agents are workspace-invocable (MUL-3963): seed the// matching workspace invocation target so canInvokeAgent admits workspace// members and A2A triggers, mirroring the pre-permission-model behavior// where a workspace-visible agent could be triggered by anyone in the// workspace. Dedicated private-agent tests use privateAgentTestFixture.- if _, err := testPool.Exec(context.Background(), `+ dbfx.Exec(t, `INSERT INTO agent_invocation_target (agent_id, target_type, target_id)VALUES ($1, 'workspace', $2)ON CONFLICT (agent_id, target_type, target_id) DO NOTHING- `, agentID, testWorkspaceID); err != nil {- t.Fatalf("failed to seed workspace invocation target: %v", err)- }+ `, agentID, testWorkspaceID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)@@ -293,16 +287,11 @@ func createHandlerTestTaskForAgentOnIssue(t *testing.T, agentID, issueID string)issueArg = issueID}- var taskID string- if err := testPool.QueryRow(context.Background(), `- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, started_at)- VALUES ($1, $2, 'running', 0, $3, now())- RETURNING id- `, agentID, handlerTestRuntimeID(t), issueArg).Scan(&taskID); err != nil {- t.Fatalf("failed to create handler test task: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "status": "running",+ "issue_id": issueArg,+ "started_at": testutil.Raw("now()"),})return taskID}@@ -311,9 +300,7 @@ func fetchAgentMcpConfig(t *testing.T, agentID string) []byte {t.Helper()var mcpConfig []byte- if err := testPool.QueryRow(context.Background(), `SELECT mcp_config FROM agent WHERE id = $1`, agentID).Scan(&mcpConfig); err != nil {- t.Fatalf("failed to load agent mcp_config: %v", err)- }+ dbfx.QueryRow(t, `SELECT mcp_config FROM agent WHERE id = $1`, agentID).Scan(&mcpConfig)return mcpConfig}@@ -451,16 +438,12 @@ func TestIssueCRUD(t *testing.T) {// not the raw identifier — frontend caches key by UUID and would otherwise// leave stale entries on other clients after an identifier-path delete.func TestDeleteIssueByIdentifier(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Issue to delete by identifier","status": "todo","priority": "medium",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)if created.Identifier == "" {@@ -479,22 +462,16 @@ func TestDeleteIssueByIdentifier(t *testing.T) {})// Delete using the human-readable identifier (e.g. "HAN-1") rather than the UUID.- w = httptest.NewRecorder()req = newRequest("DELETE", "/api/issues/"+created.Identifier, nil)req = withURLParam(req, "id", created.Identifier)- testHandler.DeleteIssue(w, req)- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteIssue by identifier: expected 204, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.DeleteIssue, req).Want(http.StatusNoContent)// Verify the row is actually gone — the silent-data-loss bug would have// returned 204 here too, but the row would still exist.var count int- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT COUNT(*) FROM issue WHERE id = $1`, created.ID,- ).Scan(&count); err != nil {- t.Fatalf("count query: %v", err)- }+ ).Scan(&count)if count != 0 {t.Fatalf("DeleteIssue by identifier returned 204 but row still exists (count=%d) — silent-data-loss regression", count)}@@ -518,16 +495,12 @@ func TestDeleteIssueByIdentifier(t *testing.T) {// identifier URL could be treated as canonical, and a mistyped or stale prefix// silently opened someone else's link target.func TestGetIssueByIdentifierEnforcesPrefix(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Issue addressed by identifier","status": "todo","priority": "medium",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -540,10 +513,9 @@ func TestGetIssueByIdentifierEnforcesPrefix(t *testing.T) {// The workspace's own prefix resolves, in either case — a hand-typed// lowercase key from a chat message must open the same issue.for _, id := range []string{created.Identifier, strings.ToLower(created.Identifier)} {- w = httptest.NewRecorder()req = newRequest("GET", "/api/issues/"+id, nil)req = withURLParam(req, "id", id)- testHandler.GetIssue(w, req)+ w = testutil.Call(t, testHandler.GetIssue, req)if w.Code != http.StatusOK {t.Fatalf("GetIssue(%q): expected 200, got %d: %s", id, w.Code, w.Body.String())}@@ -556,10 +528,9 @@ func TestGetIssueByIdentifierEnforcesPrefix(t *testing.T) {// A foreign prefix carrying the right number must not resolve.foreign := prefix + "X-" + number- w = httptest.NewRecorder()req = newRequest("GET", "/api/issues/"+foreign, nil)req = withURLParam(req, "id", foreign)- testHandler.GetIssue(w, req)+ w = testutil.Call(t, testHandler.GetIssue, req)if w.Code != http.StatusNotFound {t.Fatalf("GetIssue(%q): expected 404 for a foreign prefix, got %d: %s", foreign, w.Code, w.Body.String())}@@ -569,10 +540,9 @@ func TestGetIssueByIdentifierEnforcesPrefix(t *testing.T) {// neither a valid UUID nor a valid identifier returns 404 (not 204) — the// handler must never silently succeed on malformed input.func TestDeleteIssueRejectsInvalidUUID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/issues/not-a-uuid-or-identifier", nil)req = withURLParam(req, "id", "not-a-uuid-or-identifier")- testHandler.DeleteIssue(w, req)+ w := testutil.Call(t, testHandler.DeleteIssue, req)if w.Code == http.StatusNoContent {t.Fatalf("DeleteIssue with invalid id: must not return 204; got %d", w.Code)}@@ -585,14 +555,10 @@ func TestDeleteIssueRejectsInvalidUUID(t *testing.T) {// explicit status default to "todo" so the daemon picks them up immediately.// Before this fix the default was "backlog", which daemons ignore.func TestCreateIssueDefaultStatusIsTodo(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Issue with no explicit status",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -609,15 +575,11 @@ func TestCreateIssueDefaultStatusIsTodo(t *testing.T) {// TestCreateIssueExplicitBacklogPreserved verifies that explicitly requesting// "backlog" status is still respected — only the implicit default changed.func TestCreateIssueExplicitBacklogPreserved(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Explicit backlog issue","status": "backlog",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -639,49 +601,33 @@ func TestCreateIssueExplicitBacklogPreserved(t *testing.T) {// inserts a foreign workspace + issue directly via SQL, then drives the// request through the regular handler entry point.func TestCreateIssueRejectsCrossWorkspaceParent(t *testing.T) {- ctx := context.Background()- var otherWorkspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "Cross-workspace parent test", "xwp-parent-test", "Foreign workspace", "XWP").Scan(&otherWorkspaceID); err != nil {- t.Fatalf("insert foreign workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)+ otherWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Cross-workspace parent test",+ "slug": "xwp-parent-test",+ "description": "Foreign workspace",+ "issue_prefix": "XWP",})- var foreignParentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)- VALUES ($1, $2, 'todo', 'none', 'member', $3, 1)- RETURNING id- `, otherWorkspaceID, "Foreign parent", testUserID).Scan(&foreignParentID); err != nil {- t.Fatalf("insert foreign parent: %v", err)- }+ foreignParentID := dbfx.Issue(t, "Foreign parent", testutil.Cols{+ "workspace_id": otherWorkspaceID,+ "number": 1,+ })- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Should be rejected","parent_issue_id": foreignParentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue with foreign parent: expected 400, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)if !strings.Contains(w.Body.String(), "parent issue not found in this workspace") {t.Fatalf("CreateIssue with foreign parent: expected boundary error message, got %s", w.Body.String())}var count int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = $2`,testWorkspaceID, "Should be rejected",- ).Scan(&count); err != nil {- t.Fatalf("count query: %v", err)- }+ ).Scan(&count)if count != 0 {t.Fatalf("rejected create still wrote a row (count=%d) — service-layer boundary check failed", count)}@@ -692,49 +638,32 @@ func TestCreateIssueRejectsCrossWorkspaceParent(t *testing.T) {// (Lark /issue, MCP, API keys) must inherit this guard from the service// without re-implementing it.func TestCreateIssueRejectsCrossWorkspaceProject(t *testing.T) {- ctx := context.Background()- var otherWorkspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "Cross-workspace project test", "xwp-project-test", "Foreign workspace", "XWP").Scan(&otherWorkspaceID); err != nil {- t.Fatalf("insert foreign workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID)+ otherWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Cross-workspace project test",+ "slug": "xwp-project-test",+ "description": "Foreign workspace",+ "issue_prefix": "XWP",})- var foreignProjectID string- if err := testPool.QueryRow(ctx, `- INSERT INTO project (workspace_id, title, status, priority)- VALUES ($1, $2, 'planned', 'none')- RETURNING id- `, otherWorkspaceID, "Foreign project").Scan(&foreignProjectID); err != nil {- t.Fatalf("insert foreign project: %v", err)- }+ foreignProjectID := dbfx.Project(t, "Foreign project", testutil.Cols{+ "workspace_id": otherWorkspaceID,+ })- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Should be rejected","project_id": foreignProjectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue with foreign project: expected 400, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)if !strings.Contains(w.Body.String(), "project not found in this workspace") {t.Fatalf("CreateIssue with foreign project: expected boundary error message, got %s", w.Body.String())}var count int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = $2`,testWorkspaceID, "Should be rejected",- ).Scan(&count); err != nil {- t.Fatalf("count query: %v", err)- }+ ).Scan(&count)if count != 0 {t.Fatalf("rejected create still wrote a row (count=%d) — service-layer boundary check failed", count)}@@ -758,27 +687,19 @@ func TestCreateSubIssueInheritsParentProject(t *testing.T) {}}()- w := httptest.NewRecorder()req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{"title": "Sub-issue inheritance project",})- testHandler.CreateProject(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateProject: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateProject, req).Want(http.StatusCreated)var project ProjectResponsejson.NewDecoder(w.Body).Decode(&project)projectID = project.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Parent with project","project_id": projectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue parent: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var parent IssueResponsejson.NewDecoder(w.Body).Decode(&parent)parentID = parent.ID@@ -786,15 +707,11 @@ func TestCreateSubIssueInheritsParentProject(t *testing.T) {t.Fatalf("CreateIssue parent: expected project_id %q, got %v", projectID, parent.ProjectID)}- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Child without explicit project","parent_issue_id": parentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue child: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var child IssueResponsejson.NewDecoder(w.Body).Decode(&child)childID = child.ID@@ -828,39 +745,27 @@ func TestCreateSubIssueUsesExplicitProjectOverParentProject(t *testing.T) {}}()- w := httptest.NewRecorder()req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{"title": "Parent project",})- testHandler.CreateProject(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateProject parent: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateProject, req).Want(http.StatusCreated)var parentProject ProjectResponsejson.NewDecoder(w.Body).Decode(&parentProject)parentProjectID = parentProject.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{"title": "Child explicit project",})- testHandler.CreateProject(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateProject child: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateProject, req).Want(http.StatusCreated)var childProject ProjectResponsejson.NewDecoder(w.Body).Decode(&childProject)childProjectID = childProject.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Parent with project","project_id": parentProjectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue parent: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var parent IssueResponsejson.NewDecoder(w.Body).Decode(&parent)parentID = parent.ID@@ -868,16 +773,12 @@ func TestCreateSubIssueUsesExplicitProjectOverParentProject(t *testing.T) {t.Fatalf("CreateIssue parent: expected project_id %q, got %v", parentProjectID, parent.ProjectID)}- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Child with explicit project","parent_issue_id": parentID,"project_id": childProjectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue child: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var child IssueResponsejson.NewDecoder(w.Body).Decode(&child)childID = child.ID@@ -905,64 +806,44 @@ func TestCreateIssueRejectsActiveDuplicate(t *testing.T) {}}()- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO project (workspace_id, title)VALUES ($1, $2)RETURNING id- `, testWorkspaceID, "Duplicate guard project "+suffix).Scan(&projectID); err != nil {- t.Fatalf("create project fixture: %v", err)- }+ `, testWorkspaceID, "Duplicate guard project "+suffix).Scan(&projectID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Duplicate guard parent " + suffix,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue parent: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var parent IssueResponse- if err := json.NewDecoder(w.Body).Decode(&parent); err != nil {- t.Fatalf("decode parent: %v", err)- }+ w.JSON(&parent)parentID = parent.IDtitle := "SH-PM-SYNTH-01 Synthesize recommendation-to-shortlist planning outputs " + suffix- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "in_progress","parent_issue_id": parentID,"project_id": projectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue original: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var original IssueResponse- if err := json.NewDecoder(w.Body).Decode(&original); err != nil {- t.Fatalf("decode original: %v", err)- }+ w.JSON(&original)issueID = original.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": " sh-pm-synth-01 synthesize recommendation-to-shortlist planning outputs " + suffix + " ","parent_issue_id": parentID,"project_id": projectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusConflict {- t.Fatalf("CreateIssue duplicate: expected 409, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusConflict)var conflict struct {Code string `json:"code"`Error string `json:"error"`Issue IssueResponse `json:"issue"`}- if err := json.NewDecoder(w.Body).Decode(&conflict); err != nil {- t.Fatalf("decode conflict: %v", err)- }+ w.JSON(&conflict)if conflict.Code != "active_duplicate_issue" {t.Fatalf("code = %q, want active_duplicate_issue", conflict.Code)}@@ -973,39 +854,27 @@ func TestCreateIssueRejectsActiveDuplicate(t *testing.T) {t.Fatalf("unexpected duplicate message: %q", conflict.Error)}- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"parent_issue_id": parentID,"project_id": projectID,"allow_duplicate": true,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue allow duplicate: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var duplicate IssueResponse- if err := json.NewDecoder(w.Body).Decode(&duplicate); err != nil {- t.Fatalf("decode duplicate: %v", err)- }+ w.JSON(&duplicate)duplicateID = duplicate.IDif duplicateID == issueID {t.Fatalf("allow duplicate returned original issue id %s", duplicateID)}- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"parent_issue_id": parentID,"project_id": projectID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusConflict {- t.Fatalf("CreateIssue duplicate after allow-duplicate: expected 409, got %d: %s", w.Code, w.Body.String())- }- if err := json.NewDecoder(w.Body).Decode(&conflict); err != nil {- t.Fatalf("decode second conflict: %v", err)- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusConflict)+ w.JSON(&conflict)if conflict.Issue.ID != issueID {t.Fatalf("conflict issue = %s, want oldest active issue %s", conflict.Issue.ID, issueID)}@@ -1023,33 +892,21 @@ func TestCreateIssueAllowsDuplicateAfterCancelled(t *testing.T) {}}()- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "cancelled",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue cancelled: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var first IssueResponse- if err := json.NewDecoder(w.Body).Decode(&first); err != nil {- t.Fatalf("decode cancelled: %v", err)- }+ w.JSON(&first)firstID = first.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue after cancelled: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var second IssueResponse- if err := json.NewDecoder(w.Body).Decode(&second); err != nil {- t.Fatalf("decode second: %v", err)- }+ w.JSON(&second)secondID = second.IDif secondID == firstID {t.Fatalf("new issue reused cancelled issue id %s", secondID)@@ -1068,33 +925,21 @@ func TestCreateIssueAllowsDuplicateAfterDone(t *testing.T) {}}()- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "done",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue done: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var first IssueResponse- if err := json.NewDecoder(w.Body).Decode(&first); err != nil {- t.Fatalf("decode done: %v", err)- }+ w.JSON(&first)firstID = first.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue after done: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var second IssueResponse- if err := json.NewDecoder(w.Body).Decode(&second); err != nil {- t.Fatalf("decode second: %v", err)- }+ w.JSON(&second)secondID = second.IDif secondID == firstID {t.Fatalf("new issue reused done issue id %s", secondID)@@ -1113,52 +958,32 @@ func TestTriggerAutopilotAllowsActiveDuplicateIssue(t *testing.T) {}()var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "todo",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue existing: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var existing IssueResponse- if err := json.NewDecoder(w.Body).Decode(&existing); err != nil {- t.Fatalf("decode existing issue: %v", err)- }+ w.JSON(&existing)- w = httptest.NewRecorder()req = newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Duplicate title autopilot","assignee_id": agentID,"execution_mode": "create_issue","issue_title_template": title,})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var autopilot AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {- t.Fatalf("decode autopilot: %v", err)- }+ w.JSON(&autopilot)autopilotID = autopilot.ID- w = httptest.NewRecorder()req = newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger?workspace_id="+testWorkspaceID, nil)req = withURLParam(req, "id", autopilotID)- testHandler.TriggerAutopilot(w, req)- if w.Code != http.StatusOK {- t.Fatalf("TriggerAutopilot duplicate title: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.TriggerAutopilot, req).Want(http.StatusOK)var run AutopilotRunResponse- if err := json.NewDecoder(w.Body).Decode(&run); err != nil {- t.Fatalf("decode autopilot run: %v", err)- }+ w.JSON(&run)if run.Status != "issue_created" {t.Fatalf("run status = %q, want issue_created", run.Status)}@@ -1173,9 +998,7 @@ func TestTriggerAutopilotAllowsActiveDuplicateIssue(t *testing.T) {}var count int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count); err != nil {- t.Fatalf("count issues: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count)if count != 2 {t.Fatalf("autopilot should create a new same-title issue, got %d matching issues", count)}@@ -1193,39 +1016,25 @@ func TestScheduledAutopilotAllowsActiveDuplicateIssue(t *testing.T) {}()var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": title,"status": "todo",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue existing: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var existing IssueResponse- if err := json.NewDecoder(w.Body).Decode(&existing); err != nil {- t.Fatalf("decode existing issue: %v", err)- }+ w.JSON(&existing)- w = httptest.NewRecorder()req = newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Scheduled duplicate title autopilot","assignee_id": agentID,"execution_mode": "create_issue","issue_title_template": title,})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var autopilot AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {- t.Fatalf("decode autopilot: %v", err)- }+ w.JSON(&autopilot)autopilotID = autopilot.IDqueries := db.New(testPool)@@ -1252,9 +1061,7 @@ func TestScheduledAutopilotAllowsActiveDuplicateIssue(t *testing.T) {}var count int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count); err != nil {- t.Fatalf("count issues: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count)if count != 2 {t.Fatalf("autopilot should create a new same-title issue, got %d matching issues", count)}@@ -1279,25 +1086,17 @@ func TestAutopilotCreatedIssueCreatorIsAssigneeAgent(t *testing.T) {}()var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Creator attribution autopilot","assignee_id": agentID,"execution_mode": "create_issue","issue_title_template": title,})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var autopilot AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {- t.Fatalf("decode autopilot: %v", err)- }+ w.JSON(&autopilot)autopilotID = autopilot.IDif autopilot.CreatedByType != "member" || autopilot.CreatedByID != testUserID {t.Fatalf("autopilot created_by = %s/%s, want member/%s", autopilot.CreatedByType, autopilot.CreatedByID, testUserID)@@ -1325,15 +1124,13 @@ func TestAutopilotCreatedIssueCreatorIsAssigneeAgent(t *testing.T) {}var creatorType, creatorID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT id, creator_type, creator_idFROM issueWHERE workspace_id = $1 AND title = $2ORDER BY created_at DESCLIMIT 1- `, testWorkspaceID, title).Scan(&issueID, &creatorType, &creatorID); err != nil {- t.Fatalf("load autopilot-created issue: %v", err)- }+ `, testWorkspaceID, title).Scan(&issueID, &creatorType, &creatorID)if creatorType != "agent" {t.Fatalf("issue creator_type = %q, want agent", creatorType)}@@ -1370,20 +1167,15 @@ func TestAutopilotCreateIssueAssociatesConfiguredProject(t *testing.T) {}}()- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO project (workspace_id, title)VALUES ($1, $2)RETURNING id::text- `, testWorkspaceID, "Autopilot project target").Scan(&projectID); err != nil {- t.Fatalf("create project fixture: %v", err)- }+ `, testWorkspaceID, "Autopilot project target").Scan(&projectID)var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Project-linked autopilot","assignee_id": agentID,@@ -1391,14 +1183,9 @@ func TestAutopilotCreateIssueAssociatesConfiguredProject(t *testing.T) {"issue_title_template": title,"project_id": projectID,})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var autopilot AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&autopilot); err != nil {- t.Fatalf("decode autopilot: %v", err)- }+ w.JSON(&autopilot)autopilotID = autopilot.IDif autopilot.ProjectID == nil || *autopilot.ProjectID != projectID {t.Fatalf("autopilot project_id = %v, want %q", autopilot.ProjectID, projectID)@@ -1419,13 +1206,11 @@ func TestAutopilotCreateIssueAssociatesConfiguredProject(t *testing.T) {issueID = uuidToString(run.IssueID)var issueProjectID *string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT project_id::textFROM issueWHERE id = $1- `, issueID).Scan(&issueProjectID); err != nil {- t.Fatalf("load created issue project: %v", err)- }+ `, issueID).Scan(&issueProjectID)if issueProjectID == nil || *issueProjectID != projectID {t.Fatalf("created issue project_id = %v, want %q", issueProjectID, projectID)}@@ -1450,27 +1235,20 @@ func TestAutopilotDispatchUsesCurrentProjectBinding(t *testing.T) {}}()- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO project (workspace_id, title)VALUES ($1, $2)RETURNING id::text- `, testWorkspaceID, "Autopilot stale project A").Scan(&projectAID); err != nil {- t.Fatalf("create project A fixture: %v", err)- }- if err := testPool.QueryRow(ctx, `+ `, testWorkspaceID, "Autopilot stale project A").Scan(&projectAID)+ dbfx.QueryRow(t, `INSERT INTO project (workspace_id, title)VALUES ($1, $2)RETURNING id::text- `, testWorkspaceID, "Autopilot stale project B").Scan(&projectBID); err != nil {- t.Fatalf("create project B fixture: %v", err)- }+ `, testWorkspaceID, "Autopilot stale project B").Scan(&projectBID)var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Stale-project autopilot","assignee_id": agentID,@@ -1478,14 +1256,9 @@ func TestAutopilotDispatchUsesCurrentProjectBinding(t *testing.T) {"issue_title_template": title,"project_id": projectAID,})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var created AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&created); err != nil {- t.Fatalf("decode autopilot: %v", err)- }+ w.JSON(&created)autopilotID = created.IDqueries := db.New(testPool)@@ -1494,15 +1267,11 @@ func TestAutopilotDispatchUsesCurrentProjectBinding(t *testing.T) {t.Fatalf("GetAutopilot: %v", err)}- w = httptest.NewRecorder()req = newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, map[string]any{"project_id": projectBID,})req = withURLParam(req, "id", autopilotID)- testHandler.UpdateAutopilot(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateAutopilot, req).Want(http.StatusOK)run, err := testHandler.AutopilotService.DispatchAutopilot(ctx, ap, pgtype.UUID{}, "manual", nil)if err != nil {@@ -1514,13 +1283,11 @@ func TestAutopilotDispatchUsesCurrentProjectBinding(t *testing.T) {issueID = uuidToString(run.IssueID)var issueProjectID *string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT project_id::textFROM issueWHERE id = $1- `, issueID).Scan(&issueProjectID); err != nil {- t.Fatalf("load created issue project: %v", err)- }+ `, issueID).Scan(&issueProjectID)if issueProjectID == nil || *issueProjectID != projectBID {t.Fatalf("created issue project_id = %v, want refreshed %q", issueProjectID, projectBID)}@@ -1538,68 +1305,46 @@ func TestUpdateAutopilotCanSetAndClearProject(t *testing.T) {}}()- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO project (workspace_id, title)VALUES ($1, $2)RETURNING id::text- `, testWorkspaceID, "Autopilot update project target").Scan(&projectID); err != nil {- t.Fatalf("create project fixture: %v", err)- }+ `, testWorkspaceID, "Autopilot update project target").Scan(&projectID)var agentID string- if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load test agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)- w := httptest.NewRecorder()req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{"title": "Project update autopilot","assignee_id": agentID,"execution_mode": "create_issue",})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusCreated)var created AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&created); err != nil {- t.Fatalf("decode created autopilot: %v", err)- }+ w.JSON(&created)autopilotID = created.IDif created.ProjectID != nil {t.Fatalf("new autopilot project_id = %v, want nil", created.ProjectID)}- w = httptest.NewRecorder()req = newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, map[string]any{"project_id": projectID,})req = withURLParam(req, "id", autopilotID)- testHandler.UpdateAutopilot(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAutopilot set project: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateAutopilot, req).Want(http.StatusOK)var updated AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {- t.Fatalf("decode updated autopilot: %v", err)- }+ w.JSON(&updated)if updated.ProjectID == nil || *updated.ProjectID != projectID {t.Fatalf("updated project_id = %v, want %q", updated.ProjectID, projectID)}- w = httptest.NewRecorder()req = newRequest("PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, map[string]any{"project_id": nil,})req = withURLParam(req, "id", autopilotID)- testHandler.UpdateAutopilot(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAutopilot clear project: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateAutopilot, req).Want(http.StatusOK)var cleared AutopilotResponse- if err := json.NewDecoder(w.Body).Decode(&cleared); err != nil {- t.Fatalf("decode cleared autopilot: %v", err)- }+ w.JSON(&cleared)if cleared.ProjectID != nil {t.Fatalf("cleared project_id = %v, want nil", cleared.ProjectID)}@@ -1609,90 +1354,66 @@ func TestUpdateAutopilotCanSetAndClearProject(t *testing.T) {// well-formed UUID was accepted as assignee_id without checking workspace// membership.func TestCreateIssueRejectsNonexistentMemberAssignee(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Ghost member assignee","assignee_type": "member","assignee_id": "00000000-0000-0000-0000-000000000000",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 for nonexistent member, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}// TestCreateIssueRejectsNonexistentAgentAssignee verifies the same check on// the agent branch — previously rejected with 403 "agent not found"; we want a// consistent 400 from the new validator.func TestCreateIssueRejectsNonexistentAgentAssignee(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Ghost agent assignee","assignee_type": "agent","assignee_id": "00000000-0000-0000-0000-000000000000",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 for nonexistent agent, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}// TestCreateIssueRejectsAssigneeTypeWithoutID rejects requests where only one// of the two fields was supplied — historically this would create an issue// with an inconsistent state.func TestCreateIssueRejectsAssigneeTypeWithoutID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Lone assignee_type","assignee_type": "member",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 when only assignee_type is set, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}// TestCreateIssueRejectsAssigneeIDWithoutType is the symmetric case.func TestCreateIssueRejectsAssigneeIDWithoutType(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Lone assignee_id","assignee_id": testUserID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 when only assignee_id is set, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}// TestCreateIssueRejectsUnknownAssigneeType guards against typos like// "members" or "user" that previously sneaked through.func TestCreateIssueRejectsUnknownAssigneeType(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Bogus assignee_type","assignee_type": "user","assignee_id": testUserID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 for unknown assignee_type, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}// TestCreateIssueAcceptsValidMemberAssignee is the positive control — the// validator must not block legitimate workspace members.func TestCreateIssueAcceptsValidMemberAssignee(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Valid member assignee","assignee_type": "member","assignee_id": testUserID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201 for valid member assignee, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -1705,37 +1426,25 @@ func TestCreateIssueAcceptsValidMemberAssignee(t *testing.T) {// silently produces an invalid pgtype.UUID and the validator would otherwise// treat (no type + unparseable id) as "no assignee" and accept the request.func TestCreateIssueRejectsMalformedAssigneeID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Malformed assignee_id only","assignee_id": "not-a-uuid",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 for malformed assignee_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)}func TestCreateIssueRejectsMalformedAttachmentIDBeforeWrite(t *testing.T) {var before int- if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&before); err != nil {- t.Fatalf("count issues before: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&before)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Malformed attachment issue","attachment_ids": []string{"not-a-uuid"},})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateIssue: expected 400 for malformed attachment_ids, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)var after int- if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&after); err != nil {- t.Fatalf("count issues after: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&after)if after != before {t.Fatalf("CreateIssue: malformed attachment_ids should not create issue, count before=%d after=%d", before, after)}@@ -1745,14 +1454,10 @@ func TestCreateIssueRejectsMalformedAttachmentIDBeforeWrite(t *testing.T) {// path, where the same parseUUID-shaped gap existed on a previously-unassigned// issue.func TestUpdateIssueRejectsMalformedAssigneeID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Update malformed assignee target",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)defer func() {@@ -1761,28 +1466,20 @@ func TestUpdateIssueRejectsMalformedAssigneeID(t *testing.T) {testHandler.DeleteIssue(httptest.NewRecorder(), cleanupReq)}()- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"assignee_id": "not-a-uuid",})req = withURLParam(req, "id", created.ID)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateIssue: expected 400 for malformed assignee_id, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusBadRequest)}// TestUpdateIssueRejectsNonexistentMemberAssignee verifies the same gap is// closed on the update path — UpdateIssue previously only validated agents.func TestUpdateIssueRejectsNonexistentMemberAssignee(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Update assignee target",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)defer func() {@@ -1791,32 +1488,24 @@ func TestUpdateIssueRejectsNonexistentMemberAssignee(t *testing.T) {testHandler.DeleteIssue(httptest.NewRecorder(), cleanupReq)}()- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"assignee_type": "member","assignee_id": "00000000-0000-0000-0000-000000000000",})req = withURLParam(req, "id", created.ID)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateIssue: expected 400 for nonexistent member, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusBadRequest)}// TestUpdateIssueAllowsExplicitUnassign verifies that sending null for both// fields still works after the new validator landed — clearing the assignee// must not be misclassified as a mismatched pair.func TestUpdateIssueAllowsExplicitUnassign(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Issue to unassign","assignee_type": "member","assignee_id": testUserID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)defer func() {@@ -1825,16 +1514,12 @@ func TestUpdateIssueAllowsExplicitUnassign(t *testing.T) {testHandler.DeleteIssue(httptest.NewRecorder(), cleanupReq)}()- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"assignee_type": nil,"assignee_id": nil,})req = withURLParam(req, "id", created.ID)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200 for unassign, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)var updated IssueResponsejson.NewDecoder(w.Body).Decode(&updated)if updated.AssigneeType != nil || updated.AssigneeID != nil {@@ -1844,34 +1529,25 @@ func TestUpdateIssueAllowsExplicitUnassign(t *testing.T) {func TestCommentCRUD(t *testing.T) {// Create an issue first- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Comment test issue",})- testHandler.CreateIssue(w, req)+ w := testutil.Call(t, testHandler.CreateIssue, req)var issue IssueResponsejson.NewDecoder(w.Body).Decode(&issue)issueID := issue.ID// Create comment- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": "Test comment from Go test",})req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateComment, req).Want(http.StatusCreated)// List comments- w = httptest.NewRecorder()req = newRequest("GET", "/api/issues/"+issueID+"/comments", nil)req = withURLParam(req, "id", issueID)- testHandler.ListComments(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListComments: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.ListComments, req).Want(http.StatusOK)var comments []CommentResponsejson.NewDecoder(w.Body).Decode(&comments)@@ -1883,10 +1559,9 @@ func TestCommentCRUD(t *testing.T) {}// Cleanup- w = httptest.NewRecorder()req = newRequest("DELETE", "/api/issues/"+issueID, nil)req = withURLParam(req, "id", issueID)- testHandler.DeleteIssue(w, req)+ w = testutil.Call(t, testHandler.DeleteIssue, req)}func TestCommentWritePathsPreserveIssueIdentifiers(t *testing.T) {@@ -1894,19 +1569,14 @@ func TestCommentWritePathsPreserveIssueIdentifiers(t *testing.T) {t.Skip("requires DB")}- ctx := context.Background()setWorkspaceIssuePrefixForTest(t, "MUL")- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, creator_type, creator_id, title, number)- VALUES ($1, 'member', $2, $3, 3310)- RETURNING id- `, testWorkspaceID, testUserID, "preserve bare issue identifiers").Scan(&issueID); err != nil {- t.Fatalf("create issue fixture: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ issueID := dbfx.Insert(t, "issue", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "creator_type": "member",+ "creator_id": testUserID,+ "title": "preserve bare issue identifiers",+ "number": 3310,})explicitMention := fmt.Sprintf("[MUL-3310](mention://issue/%s)", issueID)@@ -1919,20 +1589,17 @@ func TestCommentWritePathsPreserveIssueIdentifiers(t *testing.T) {var firstCommentID stringfor _, content := range createCases {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": content,})req = withURLParam(req, "id", issueID)- testHandler.CreateComment(w, req)+ w := testutil.Call(t, testHandler.CreateComment, req)if w.Code != http.StatusCreated {t.Fatalf("CreateComment(%q): expected 201, got %d: %s", content, w.Code, w.Body.String())}var created CommentResponse- if err := json.NewDecoder(w.Body).Decode(&created); err != nil {- t.Fatalf("decode created comment: %v", err)- }+ w.JSON(&created)if created.Content != content {t.Fatalf("CreateComment(%q) stored %q", content, created.Content)}@@ -1942,225 +1609,150 @@ func TestCommentWritePathsPreserveIssueIdentifiers(t *testing.T) {}updatedContent := "updated MUL-3310 issue/MUL-3310 feature/MUL-3310 " + explicitMention- w := httptest.NewRecorder()req := newRequest("PUT", "/api/comments/"+firstCommentID, map[string]any{"content": updatedContent,})req = withURLParam(req, "commentId", firstCommentID)- testHandler.UpdateComment(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateComment: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.UpdateComment, req).Want(http.StatusOK)var updated CommentResponse- if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {- t.Fatalf("decode updated comment: %v", err)- }+ w.JSON(&updated)if updated.Content != updatedContent {t.Fatalf("UpdateComment stored %q, want %q", updated.Content, updatedContent)}}func TestCreateCommentRejectsMalformedParentID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Comment malformed parent issue",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var issue IssueResponsejson.NewDecoder(w.Body).Decode(&issue)- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues/"+issue.ID+"/comments", map[string]any{"content": "bad parent","parent_id": "not-a-uuid",})req = withURLParam(req, "id", issue.ID)- testHandler.CreateComment(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateComment: expected 400 for malformed parent_id, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateComment, req).Want(http.StatusBadRequest)- w = httptest.NewRecorder()req = newRequest("DELETE", "/api/issues/"+issue.ID, nil)req = withURLParam(req, "id", issue.ID)- testHandler.DeleteIssue(w, req)+ w = testutil.Call(t, testHandler.DeleteIssue, req)}func TestGetChatSessionRejectsMalformedSessionID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("GET", "/api/chat/sessions/not-a-uuid", nil)req = withURLParam(req, "sessionId", "not-a-uuid")- testHandler.GetChatSession(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("GetChatSession: expected 400 for malformed sessionId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetChatSession, req).Want(http.StatusBadRequest)}func TestCreateAutopilotRejectsMalformedAssigneeID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/autopilots", map[string]any{"title": "Malformed assignee autopilot","assignee_id": "not-a-uuid","execution_mode": "run_only",})- testHandler.CreateAutopilot(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateAutopilot: expected 400 for malformed assignee_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateAutopilot, req).Want(http.StatusBadRequest)}func TestUpdateAutopilotRejectsMalformedID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PUT", "/api/autopilots/not-a-uuid", map[string]any{"title": "Malformed autopilot id",})req = withURLParam(req, "id", "not-a-uuid")- testHandler.UpdateAutopilot(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateAutopilot: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateAutopilot, req).Want(http.StatusBadRequest)}func TestUpdateAgentRejectsMalformedAgentID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/not-a-uuid", map[string]any{"name": "Malformed agent id",})req = withURLParam(req, "id", "not-a-uuid")- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateAgent: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusBadRequest)}func TestCreateAgentRejectsMalformedRuntimeID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents", map[string]any{"name": "Malformed runtime agent","runtime_id": "not-a-uuid",})- testHandler.CreateAgent(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateAgent: expected 400 for malformed runtime_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateAgent, req).Want(http.StatusBadRequest)}func TestUpdateAgentRejectsMalformedRuntimeID(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Malformed Runtime Update", nil)- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{"runtime_id": "not-a-uuid",})req = withURLParam(req, "id", agentID)- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateAgent: expected 400 for malformed runtime_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusBadRequest)}func TestCreatePinRejectsMalformedItemID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/pins", map[string]any{"item_type": "issue","item_id": "not-a-uuid",})- testHandler.CreatePin(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreatePin: expected 400 for malformed item_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreatePin, req).Want(http.StatusBadRequest)}func TestUpdateWorkspaceRejectsMalformedID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PUT", "/api/workspaces/not-a-uuid", map[string]any{"name": "Malformed workspace id",})req = withURLParam(req, "id", "not-a-uuid")- testHandler.UpdateWorkspace(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateWorkspace: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusBadRequest)}func TestUpdateMemberRejectsMalformedMemberID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PATCH", "/api/workspaces/"+testWorkspaceID+"/members/not-a-uuid", map[string]any{"role": "member",})req = withURLParams(req, "id", testWorkspaceID, "memberId", "not-a-uuid")- testHandler.UpdateMember(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateMember: expected 400 for malformed memberId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateMember, req).Want(http.StatusBadRequest)}func TestRevokeInvitationRejectsMalformedInvitationID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/invitations/not-a-uuid", nil)req = withURLParams(req, "id", testWorkspaceID, "invitationId", "not-a-uuid")- testHandler.RevokeInvitation(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("RevokeInvitation: expected 400 for malformed invitationId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.RevokeInvitation, req).Want(http.StatusBadRequest)}func TestGetMyInvitationRejectsMalformedID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("GET", "/api/invitations/not-a-uuid", nil)req = withURLParam(req, "id", "not-a-uuid")- testHandler.GetMyInvitation(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("GetMyInvitation: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetMyInvitation, req).Want(http.StatusBadRequest)}func TestAddReactionRejectsMalformedCommentID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/comments/not-a-uuid/reactions", map[string]any{"emoji": "thumbs_up",})req = withURLParam(req, "commentId", "not-a-uuid")- testHandler.AddReaction(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("AddReaction: expected 400 for malformed commentId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.AddReaction, req).Want(http.StatusBadRequest)}func TestUpdateCommentRejectsMalformedCommentID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PUT", "/api/comments/not-a-uuid", map[string]any{"content": "updated",})req = withURLParam(req, "commentId", "not-a-uuid")- testHandler.UpdateComment(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("UpdateComment: expected 400 for malformed commentId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateComment, req).Want(http.StatusBadRequest)}func TestMarkInboxReadRejectsMalformedItemID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/inbox/not-a-uuid/read", nil)req = withURLParam(req, "id", "not-a-uuid")- testHandler.MarkInboxRead(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("MarkInboxRead: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.MarkInboxRead, req).Want(http.StatusBadRequest)}func TestRevokePersonalAccessTokenRejectsMalformedID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/tokens/not-a-uuid", nil)req = withURLParam(req, "id", "not-a-uuid")- testHandler.RevokePersonalAccessToken(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("RevokePersonalAccessToken: expected 400 for malformed id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.RevokePersonalAccessToken, req).Want(http.StatusBadRequest)}func TestRequestBodyUUIDFieldsRejectMalformed(t *testing.T) {@@ -2194,24 +1786,16 @@ func TestRequestBodyUUIDFieldsRejectMalformed(t *testing.T) {}func TestDaemonDeregisterRejectsMalformedRuntimeID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/daemon/deregister", map[string]any{"runtime_ids": []string{"not-a-uuid"},})- testHandler.DaemonDeregister(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("DaemonDeregister: expected 400 for malformed runtime_ids, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DaemonDeregister, req).Want(http.StatusBadRequest)}func TestGetIssueGCCheckRejectsMalformedIssueID(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("GET", "/api/daemon/issues/not-a-uuid/gc-check", nil)req = withURLParam(req, "issueId", "not-a-uuid")- testHandler.GetIssueGCCheck(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("GetIssueGCCheck: expected 400 for malformed issueId, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusBadRequest)}func TestBatchIssueGCCheckRejectsInvalidRequests(t *testing.T) {@@ -2234,14 +1818,10 @@ func TestBatchIssueGCCheckRejectsInvalidRequests(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+tt.workspaceID+"/issues/gc-check", tt.body,tt.workspaceID, "test-daemon")req = withURLParam(req, "workspaceId", tt.workspaceID)- h.BatchIssueGCCheck(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, h.BatchIssueGCCheck, req).Want(http.StatusBadRequest)})}}@@ -2249,15 +1829,11 @@ func TestBatchIssueGCCheckRejectsInvalidRequests(t *testing.T) {func TestSetAgentSkillsRejectsMalformedSkillID(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Malformed Skill Assignment", nil)- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/"+agentID+"/skills", map[string]any{"skill_ids": []string{"not-a-uuid"},})req = withURLParam(req, "id", agentID)- testHandler.SetAgentSkills(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("SetAgentSkills: expected 400 for malformed skill_ids, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.SetAgentSkills, req).Want(http.StatusBadRequest)}func TestAddAgentSkillsPreservesExistingAssignments(t *testing.T) {@@ -2265,27 +1841,19 @@ func TestAddAgentSkillsPreservesExistingAssignments(t *testing.T) {existingSkillID := insertHandlerTestSkill(t, "add-preserve-existing", "existing body")newSkillID := insertHandlerTestSkill(t, "add-preserve-new", "new body")- if _, err := testPool.Exec(context.Background(),+ dbfx.Exec(t,`INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`,agentID, existingSkillID,- ); err != nil {- t.Fatalf("seed existing skill assignment: %v", err)- }+ )- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{"skill_ids": []string{newSkillID},})req = withURLParam(req, "id", agentID)- testHandler.AddAgentSkills(w, req)- if w.Code != http.StatusOK {- t.Fatalf("AddAgentSkills: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.AddAgentSkills, req).Want(http.StatusOK)var resp []SkillSummaryResponse- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)assertSkillIDsPresent(t, resp, existingSkillID, newSkillID)assertAgentSkillRowCount(t, agentID, 2)}@@ -2296,12 +1864,11 @@ func TestAddAgentSkillsAddsMultipleAndIsIdempotent(t *testing.T) {skillB := insertHandlerTestSkill(t, "add-multiple-b", "b body")for attempt := 0; attempt < 2; attempt++ {- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{"skill_ids": []string{skillA, skillB},})req = withURLParam(req, "id", agentID)- testHandler.AddAgentSkills(w, req)+ w := testutil.Call(t, testHandler.AddAgentSkills, req)if w.Code != http.StatusOK {t.Fatalf("AddAgentSkills attempt %d: expected 200, got %d: %s", attempt+1, w.Code, w.Body.String())}@@ -2313,61 +1880,44 @@ func TestAddAgentSkillsAddsMultipleAndIsIdempotent(t *testing.T) {func TestAddAgentSkillsRejectsMalformedSkillID(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Add Malformed Skill Assignment", nil)- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{"skill_ids": []string{"not-a-uuid"},})req = withURLParam(req, "id", agentID)- testHandler.AddAgentSkills(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("AddAgentSkills: expected 400 for malformed skill_ids, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.AddAgentSkills, req).Want(http.StatusBadRequest)}func TestAddAgentSkillsRejectsCrossWorkspaceSkillID(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Add Cross Workspace Skill", nil)foreignSkillID := insertHandlerTestSkillInForeignWorkspace(t, "add-cross-workspace", "foreign body")- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{"skill_ids": []string{foreignSkillID},})req = withURLParam(req, "id", agentID)- testHandler.AddAgentSkills(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("AddAgentSkills: expected 404 for cross-workspace skill_id, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.AddAgentSkills, req).Want(http.StatusNotFound)assertAgentSkillRowCount(t, agentID, 0)}func insertHandlerTestSkillInForeignWorkspace(t *testing.T, namePrefix, content string) string {t.Helper()- ctx := context.Background()slug := "foreign-skill-" + strings.ToLower(strings.ReplaceAll(t.Name(), "_", "-"))- var workspaceID string- if err := testPool.QueryRow(ctx, `- INSERT INTO workspace (name, slug, description, issue_prefix)- VALUES ($1, $2, $3, $4)- RETURNING id- `, "Foreign Skill Workspace "+t.Name(), slug, "", "FSW").Scan(&workspaceID); err != nil {- t.Fatalf("insert foreign workspace: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)+ workspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Foreign Skill Workspace " + t.Name(),+ "slug": slug,+ "description": "",+ "issue_prefix": "FSW",})name := namePrefix + "-" + t.Name()- var skillID string- if err := testPool.QueryRow(ctx, `- INSERT INTO skill (workspace_id, name, description, content, config, created_by)- VALUES ($1, $2, $3, $4, '{}'::jsonb, $5)- RETURNING id- `, workspaceID, name, "fixture", content, testUserID).Scan(&skillID); err != nil {- t.Fatalf("insert foreign skill: %v", err)- }- t.Cleanup(func() {- testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, skillID)+ skillID := dbfx.Insert(t, "skill", testutil.Cols{+ "workspace_id": workspaceID,+ "name": name,+ "description": "fixture",+ "content": content,+ "config": testutil.Raw("'{}'::jsonb"),+ "created_by": testUserID,})return skillID}@@ -2388,12 +1938,10 @@ func assertSkillIDsPresent(t *testing.T, skills []SkillSummaryResponse, wantIDsfunc assertAgentSkillRowCount(t *testing.T, agentID string, want int) {t.Helper()var got int- if err := testPool.QueryRow(context.Background(),+ dbfx.QueryRow(t,`SELECT COUNT(*) FROM agent_skill WHERE agent_id = $1`,agentID,- ).Scan(&got); err != nil {- t.Fatalf("count agent_skill: %v", err)- }+ ).Scan(&got)if got != want {t.Fatalf("agent_skill row count: got %d, want %d", got, want)}@@ -2401,12 +1949,7 @@ func assertAgentSkillRowCount(t *testing.T, agentID string, want int) {func TestAgentCRUD(t *testing.T) {// List agents- w := httptest.NewRecorder()- req := newRequest("GET", "/api/agents?workspace_id="+testWorkspaceID, nil)- testHandler.ListAgents(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListAgents: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ListAgents, newRequest("GET", "/api/agents?workspace_id="+testWorkspaceID, nil)).Want(http.StatusOK)var agents []AgentResponsejson.NewDecoder(w.Body).Decode(&agents)@@ -2416,15 +1959,11 @@ func TestAgentCRUD(t *testing.T) {// Update agent statusagentID := agents[0].ID- w = httptest.NewRecorder()- req = newRequest("PUT", "/api/agents/"+agentID, map[string]any{+ req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{"status": "idle",})req = withURLParam(req, "id", agentID)- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusOK)var updated AgentResponsejson.NewDecoder(w.Body).Decode(&updated)@@ -2439,20 +1978,14 @@ func TestAgentCRUD(t *testing.T) {func TestUpdateAgentMcpConfigAbsentPreservesValue(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Mcp Preserve", []byte(`{"preset":"keep"}`))- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{"name": "Handler Mcp Preserve Updated",})req = withURLParam(req, "id", agentID)- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusOK)var updated AgentResponse- if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {- t.Fatalf("UpdateAgent: decode response: %v", err)- }+ w.JSON(&updated)assertJSONEqual(t, updated.McpConfig, `{"preset":"keep"}`)assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), `{"preset":"keep"}`)}@@ -2460,20 +1993,14 @@ func TestUpdateAgentMcpConfigAbsentPreservesValue(t *testing.T) {func TestUpdateAgentMcpConfigNullClearsValue(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Mcp Clear", []byte(`{"preset":"clear"}`))- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{"mcp_config": nil,})req = withURLParam(req, "id", agentID)- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusOK)var updated AgentResponse- if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {- t.Fatalf("UpdateAgent: decode response: %v", err)- }+ w.JSON(&updated)assertJSONEqual(t, updated.McpConfig, `null`)if fetchAgentMcpConfig(t, agentID) != nil {t.Fatalf("UpdateAgent: expected DB mcp_config to be SQL NULL")@@ -2483,26 +2010,19 @@ func TestUpdateAgentMcpConfigNullClearsValue(t *testing.T) {func TestUpdateAgentMcpConfigObjectUpdatesValue(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Mcp Update", []byte(`{"preset":"old"}`))- w := httptest.NewRecorder()req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{"mcp_config": map[string]any{"preset": "new"},})req = withURLParam(req, "id", agentID)- testHandler.UpdateAgent(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusOK)var updated AgentResponse- if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {- t.Fatalf("UpdateAgent: decode response: %v", err)- }+ w.JSON(&updated)assertJSONEqual(t, updated.McpConfig, `{"preset":"new"}`)assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), `{"preset":"new"}`)}func TestCreateAgentMcpConfigNullStoresSQLNull(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/agents", map[string]any{"name": "Handler Mcp Create Null","runtime_id": handlerTestRuntimeID(t),@@ -2510,15 +2030,10 @@ func TestCreateAgentMcpConfigNullStoresSQLNull(t *testing.T) {"custom_env": map[string]string{},"custom_args": []string{},})- testHandler.CreateAgent(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateAgent: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateAgent, req).Want(http.StatusCreated)var created AgentResponse- if err := json.NewDecoder(w.Body).Decode(&created); err != nil {- t.Fatalf("CreateAgent: decode response: %v", err)- }+ w.JSON(&created)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, created.ID)})@@ -2531,12 +2046,7 @@ func TestCreateAgentMcpConfigNullStoresSQLNull(t *testing.T) {func TestWorkspaceCRUD(t *testing.T) {// List workspaces- w := httptest.NewRecorder()- req := newRequest("GET", "/api/workspaces", nil)- testHandler.ListWorkspaces(w, req)- if w.Code != http.StatusOK {- t.Fatalf("ListWorkspaces: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.ListWorkspaces, newRequest("GET", "/api/workspaces", nil)).Want(http.StatusOK)var workspaces []WorkspaceResponsejson.NewDecoder(w.Body).Decode(&workspaces)@@ -2546,13 +2056,9 @@ func TestWorkspaceCRUD(t *testing.T) {// Get workspacewsID := workspaces[0].ID- w = httptest.NewRecorder()- req = newRequest("GET", "/api/workspaces/"+wsID, nil)+ req := newRequest("GET", "/api/workspaces/"+wsID, nil)req = withURLParam(req, "id", wsID)- testHandler.GetWorkspace(w, req)- if w.Code != http.StatusOK {- t.Fatalf("GetWorkspace: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.GetWorkspace, req).Want(http.StatusOK)}func TestCreateWorkspaceUsesRequestedSlug(t *testing.T) {@@ -2563,20 +2069,14 @@ func TestCreateWorkspaceUsesRequestedSlug(t *testing.T) {testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)})- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]string{"name": "Handler Create Workspace Requested","slug": slug,})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusCreated)var created WorkspaceResponse- if err := json.NewDecoder(w.Body).Decode(&created); err != nil {- t.Fatalf("CreateWorkspace: decode response: %v", err)- }+ w.JSON(&created)if created.Slug != slug {t.Fatalf("CreateWorkspace: expected slug %q, got %q", slug, created.Slug)}@@ -2590,35 +2090,25 @@ func TestCreateWorkspaceSlugConflictReturnsConflict(t *testing.T) {testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, retriedSlug)})- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]string{"name": "Duplicate Handler Workspace","slug": handlerTestWorkspaceSlug,})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusConflict {- t.Fatalf("CreateWorkspace: expected 409, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusConflict)var count int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, retriedSlug).Scan(&count); err != nil {- t.Fatalf("CreateWorkspace: check retried slug: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM workspace WHERE slug = $1`, retriedSlug).Scan(&count)if count != 0 {t.Fatalf("CreateWorkspace: expected no fallback slug %q, got %d rows", retriedSlug, count)}}func TestCreateWorkspaceInvalidSlugReturnsBadRequest(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]string{"name": "Invalid Slug Workspace","slug": "invalid slug",})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("CreateWorkspace: expected 400, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusBadRequest)}func TestSendCode(t *testing.T) {@@ -3108,17 +2598,13 @@ func TestBacklogNoTriggerOnCreate(t *testing.T) {t.Fatalf("failed to find test agent: %v", err)}- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Backlog no-trigger test","status": "backlog","assignee_type": "agent","assignee_id": agentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)@@ -3157,31 +2643,23 @@ func TestBacklogToTodoTriggersAgent(t *testing.T) {}// Create a backlog issue assigned to the agent — should NOT trigger.- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Backlog trigger test","status": "backlog","assignee_type": "agent","assignee_id": agentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)// Move the issue from backlog to todo — should trigger.- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"status": "todo",})req = withURLParam(req, "id", created.ID)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)// Verify exactly one task was enqueued (from the status transition, not creation).var taskCount int@@ -3222,17 +2700,13 @@ func TestBacklogToTodoByAgentTriggersDifferentAssignee(t *testing.T) {// Create a backlog issue assigned to the child agent — should NOT trigger// on creation (backlog parking-lot rule).- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Serial sub-task Step 2","status": "backlog","assignee_type": "agent","assignee_id": childAgent,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {@@ -3242,23 +2716,17 @@ func TestBacklogToTodoByAgentTriggersDifferentAssignee(t *testing.T) {// Parent agent promotes backlog → todo on behalf of the X-Task it is// currently running. Must enqueue exactly one task for the child agent.- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"status": "todo"})req = withURLParam(req, "id", created.ID)req.Header.Set("X-Agent-ID", parentAgent)req.Header.Set("X-Task-ID", parentTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)var childTasks int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,created.ID, childAgent,- ).Scan(&childTasks); err != nil {- t.Fatalf("failed to count child tasks: %v", err)- }+ ).Scan(&childTasks)if childTasks != 1 {t.Fatalf("expected exactly 1 task enqueued for child agent after agent-driven backlog→todo, got %d", childTasks)}@@ -3283,17 +2751,13 @@ func TestBacklogToTodoByAgentSameIssueDoesNotSelfTrigger(t *testing.T) {selfAgent := createHandlerTestAgent(t, "Backlog Self Agent", nil)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Self-promoted backlog","status": "backlog","assignee_type": "agent","assignee_id": selfAgent,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {@@ -3304,23 +2768,17 @@ func TestBacklogToTodoByAgentSameIssueDoesNotSelfTrigger(t *testing.T) {// Task bound to the SAME issue being promoted — true self-loop.selfTask := createHandlerTestTaskForAgentOnIssue(t, selfAgent, created.ID)- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"status": "todo"})req = withURLParam(req, "id", created.ID)req.Header.Set("X-Agent-ID", selfAgent)req.Header.Set("X-Task-ID", selfTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)var tasks int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,created.ID, selfAgent,- ).Scan(&tasks); err != nil {- t.Fatalf("failed to count tasks: %v", err)- }+ ).Scan(&tasks)if tasks != 0 {t.Fatalf("expected no self-trigger when agent promotes the same issue its task is running on, got %d queued tasks", tasks)}@@ -3341,17 +2799,13 @@ func TestBacklogToTodoByAgentSameAgentDifferentIssue(t *testing.T) {agentID := createHandlerTestAgent(t, "Backlog Same-Agent Chain", nil)// Step 1 issue — the one the agent is currently working on.- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Step 1 (running)","status": "in_progress","assignee_type": "agent","assignee_id": agentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue step1: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var step1 IssueResponsejson.NewDecoder(w.Body).Decode(&step1)t.Cleanup(func() {@@ -3360,17 +2814,13 @@ func TestBacklogToTodoByAgentSameAgentDifferentIssue(t *testing.T) {})// Step 2 issue — backlog, also assigned to the same agent.- w = httptest.NewRecorder()req = newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Step 2 (backlog)","status": "backlog","assignee_type": "agent","assignee_id": agentID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue step2: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var step2 IssueResponsejson.NewDecoder(w.Body).Decode(&step2)t.Cleanup(func() {@@ -3381,23 +2831,17 @@ func TestBacklogToTodoByAgentSameAgentDifferentIssue(t *testing.T) {// Task is running on step1 — promoting step2 is NOT a self-loop.step1Task := createHandlerTestTaskForAgentOnIssue(t, agentID, step1.ID)- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+step2.ID, map[string]any{"status": "todo"})req = withURLParam(req, "id", step2.ID)req.Header.Set("X-Agent-ID", agentID)req.Header.Set("X-Task-ID", step1Task)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue step2: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)var step2Tasks int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,step2.ID, agentID,- ).Scan(&step2Tasks); err != nil {- t.Fatalf("failed to count step2 tasks: %v", err)- }+ ).Scan(&step2Tasks)if step2Tasks != 1 {t.Fatalf("expected exactly 1 task enqueued on step2 for same-agent serial chain, got %d", step2Tasks)}@@ -3416,7 +2860,6 @@ func TestAssignIssueToSelfWithActiveTargetRunDoesNotDuplicate(t *testing.T) {issue := createIssueForTest(t, map[string]any{"title": "self-assign active target", "status": "todo"})runningTask := createHandlerTestTaskForAgentOnIssue(t, agentID, issue.ID)- previewRecorder := httptest.NewRecorder()previewReq := newRequest("POST", "/api/issues/preview-trigger?workspace_id="+testWorkspaceID, map[string]any{"issue_ids": []string{issue.ID},"assignee_type": "agent",@@ -3424,29 +2867,20 @@ func TestAssignIssueToSelfWithActiveTargetRunDoesNotDuplicate(t *testing.T) {})previewReq.Header.Set("X-Agent-ID", agentID)previewReq.Header.Set("X-Task-ID", runningTask)- testHandler.PreviewIssueTrigger(previewRecorder, previewReq)- if previewRecorder.Code != http.StatusOK {- t.Fatalf("PreviewIssueTrigger: expected 200, got %d: %s", previewRecorder.Code, previewRecorder.Body.String())- }+ previewRecorder := testutil.Call(t, testHandler.PreviewIssueTrigger, previewReq).Want(http.StatusOK)var preview IssueTriggerPreviewResponse- if err := json.NewDecoder(previewRecorder.Body).Decode(&preview); err != nil {- t.Fatalf("decode preview: %v", err)- }+ previewRecorder.JSON(&preview)if preview.TotalCount != 0 {t.Fatalf("preview promised a duplicate self-assignment run: %+v", preview)}- w := httptest.NewRecorder()req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{"assignee_type": "agent","assignee_id": agentID,}), "id", issue.ID)req.Header.Set("X-Agent-ID", agentID)req.Header.Set("X-Task-ID", runningTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)if got := queuedTaskCountFor(t, issue.ID, agentID); got != 0 {t.Fatalf("self-assignment duplicated an active target run: got %d queued task(s)", got)}@@ -3487,17 +2921,13 @@ func TestAssignDifferentIssueToSelfStillEnqueues(t *testing.T) {target := createIssueForTest(t, map[string]any{"title": "cross-issue target", "status": "todo"})sourceTask := createHandlerTestTaskForAgentOnIssue(t, agentID, source.ID)- w := httptest.NewRecorder()req := withURLParam(newRequest("PUT", "/api/issues/"+target.ID, map[string]any{"assignee_type": "agent","assignee_id": agentID,}), "id", target.ID)req.Header.Set("X-Agent-ID", agentID)req.Header.Set("X-Task-ID", sourceTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)if got := queuedTaskCountFor(t, target.ID, agentID); got != 1 {t.Fatalf("cross-issue self-assignment should enqueue one run, got %d", got)}@@ -3516,7 +2946,6 @@ func TestBatchAssignFreshIssuesToSelfEnqueuesEach(t *testing.T) {target2 := createIssueForTest(t, map[string]any{"title": "batch target two", "status": "todo"})sourceTask := createHandlerTestTaskForAgentOnIssue(t, agentID, source.ID)- w := httptest.NewRecorder()req := newRequest("PATCH", "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{"issue_ids": []string{target1.ID, target2.ID},"updates": map[string]any{@@ -3526,10 +2955,7 @@ func TestBatchAssignFreshIssuesToSelfEnqueuesEach(t *testing.T) {})req.Header.Set("X-Agent-ID", agentID)req.Header.Set("X-Task-ID", sourceTask)- testHandler.BatchUpdateIssues(w, req)- if w.Code != http.StatusOK {- t.Fatalf("BatchUpdateIssues: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.BatchUpdateIssues, req).Want(http.StatusOK)for _, target := range []IssueResponse{target1, target2} {if got := queuedTaskCountFor(t, target.ID, agentID); got != 1 {t.Fatalf("fresh target %s should enqueue one run, got %d", target.ID, got)@@ -3549,17 +2975,13 @@ func TestAssignActiveIssueToDifferentAgentStillEnqueues(t *testing.T) {issue := createIssueForTest(t, map[string]any{"title": "active transfer", "status": "todo"})actorTask := createHandlerTestTaskForAgentOnIssue(t, actorAgent, issue.ID)- w := httptest.NewRecorder()req := withURLParam(newRequest("PUT", "/api/issues/"+issue.ID, map[string]any{"assignee_type": "agent","assignee_id": targetAgent,}), "id", issue.ID)req.Header.Set("X-Agent-ID", actorAgent)req.Header.Set("X-Task-ID", actorTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)if got := queuedTaskCountFor(t, issue.ID, targetAgent); got != 1 {t.Fatalf("new assignee should get one queued run, got %d", got)}@@ -3583,17 +3005,13 @@ func TestBatchBacklogToTodoByAgentTriggersAssignee(t *testing.T) {childAgent := createHandlerTestAgent(t, "Batch Child Agent", nil)parentTask := createHandlerTestTaskForAgent(t, parentAgent)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Batch backlog child","status": "backlog","assignee_type": "agent","assignee_id": childAgent,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {@@ -3602,25 +3020,19 @@ func TestBatchBacklogToTodoByAgentTriggersAssignee(t *testing.T) {})// Drive the batch endpoint with the same agent identity headers.- w = httptest.NewRecorder()req = newRequest("PATCH", "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{"issue_ids": []string{created.ID},"updates": map[string]any{"status": "todo"},})req.Header.Set("X-Agent-ID", parentAgent)req.Header.Set("X-Task-ID", parentTask)- testHandler.BatchUpdateIssues(w, req)- if w.Code != http.StatusOK {- t.Fatalf("BatchUpdateIssues: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.BatchUpdateIssues, req).Want(http.StatusOK)var childTasks int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,created.ID, childAgent,- ).Scan(&childTasks); err != nil {- t.Fatalf("failed to count child tasks: %v", err)- }+ ).Scan(&childTasks)if childTasks != 1 {t.Fatalf("expected exactly 1 task enqueued for child agent after batch agent-driven backlog→todo, got %d", childTasks)}@@ -3642,27 +3054,15 @@ func TestBacklogToTodoByAgentTriggersSquadLeader(t *testing.T) {driverAgent := createHandlerTestAgent(t, "Backlog Squad Driver", nil)driverTask := createHandlerTestTaskForAgent(t, driverAgent)- var squadID string- if err := testPool.QueryRow(ctx, `- INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)- VALUES ($1, $2, '', $3, $4)- RETURNING id- `, testWorkspaceID, "Backlog Trigger Squad", leaderAgent, testUserID).Scan(&squadID); err != nil {- t.Fatalf("create squad: %v", err)- }- t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM squad WHERE id = $1`, squadID) })+ squadID := dbfx.Squad(t, "Backlog Trigger Squad", leaderAgent)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Squad backlog issue","status": "backlog","assignee_type": "squad","assignee_id": squadID,})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var created IssueResponsejson.NewDecoder(w.Body).Decode(&created)t.Cleanup(func() {@@ -3672,30 +3072,23 @@ func TestBacklogToTodoByAgentTriggersSquadLeader(t *testing.T) {// Driver agent (not the leader, task is on no specific issue) promotes// the squad-assigned backlog issue. Squad leader must be enqueued.- w = httptest.NewRecorder()req = newRequest("PUT", "/api/issues/"+created.ID, map[string]any{"status": "todo"})req = withURLParam(req, "id", created.ID)req.Header.Set("X-Agent-ID", driverAgent)req.Header.Set("X-Task-ID", driverTask)- testHandler.UpdateIssue(w, req)- if w.Code != http.StatusOK {- t.Fatalf("UpdateIssue: expected 200, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.UpdateIssue, req).Want(http.StatusOK)var leaderTasks int- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'`,created.ID, leaderAgent,- ).Scan(&leaderTasks); err != nil {- t.Fatalf("failed to count leader tasks: %v", err)- }+ ).Scan(&leaderTasks)if leaderTasks != 1 {t.Fatalf("expected exactly 1 squad-leader task after agent-driven backlog→todo on squad issue, got %d", leaderTasks)}}func TestDaemonRegisterMissingWorkspaceReturns404(t *testing.T) {- w := httptest.NewRecorder()req := httptest.NewRequest("POST", "/api/daemon/register", bytes.NewBufferString(`{"workspace_id":"00000000-0000-0000-0000-000000000001","daemon_id":"local-daemon",@@ -3704,11 +3097,7 @@ func TestDaemonRegisterMissingWorkspaceReturns404(t *testing.T) {}`))req.Header.Set("Content-Type", "application/json")req.Header.Set("X-User-ID", testUserID)-- testHandler.DaemonRegister(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("DaemonRegister: expected 404, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusNotFound)if !strings.Contains(w.Body.String(), "workspace not found") {t.Fatalf("DaemonRegister: expected workspace not found error, got %s", w.Body.String())}@@ -3848,15 +3237,11 @@ func TestMemberReplyToAgentRootDoesNotInheritParentMentions(t *testing.T) {jAgent := createHandlerTestAgent(t, "J", nil)reviewerAgent := createHandlerTestAgent(t, "Reviewer", nil)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "PR review delegation no-leak test","status": "todo",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var issue IssueResponsejson.NewDecoder(w.Body).Decode(&issue)issueID := issue.ID@@ -3884,17 +3269,13 @@ func TestMemberReplyToAgentRootDoesNotInheritParentMentions(t *testing.T) {// X-Task-ID is required alongside X-Agent-ID for resolveActor to grant// the "agent" actor identity (defense against header forgery).jAgentTask := createHandlerTestTaskForAgent(t, jAgent)- w = httptest.NewRecorder()r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": fmt.Sprintf("PR ready. [@Reviewer](mention://agent/%s) please review this.", reviewerAgent),})r = withURLParam(r, "id", issueID)r.Header.Set("X-Agent-ID", jAgent)r.Header.Set("X-Task-ID", jAgentTask)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("J PR completion: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)var rootComment CommentResponsejson.NewDecoder(w.Body).Decode(&rootComment)if got := countTasks(reviewerAgent); got != 1 {@@ -3902,28 +3283,22 @@ func TestMemberReplyToAgentRootDoesNotInheritParentMentions(t *testing.T) {}// Cancel reviewer's task so it's free to be re-triggered if the bug returns.- if _, err := testPool.Exec(ctx,+ dbfx.Exec(t,`UPDATE agent_task_queue SET status = 'cancelled' WHERE issue_id = $1 AND agent_id = $2`,issueID, reviewerAgent,- ); err != nil {- t.Fatalf("cancel reviewer task: %v", err)- }+ )// 2. Member posts a plain follow-up reply under J's PR comment, with no// explicit mentions. The pre-fix code path inherited mentions from the// parent regardless of the parent author, which re-triggered Reviewer.// With the fix, the reply must NOT inherit because the parent was// authored by an agent.- w = httptest.NewRecorder()r = newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": "How do I test this after merging?","parent_id": rootComment.ID,})r = withURLParam(r, "id", issueID)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("member follow-up: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)if got := countTasks(reviewerAgent); got != 0 {t.Fatalf("expected 0 tasks for Reviewer after plain member reply (no inheritance from agent root), got %d", got)}@@ -3937,29 +3312,27 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- ctx := context.Background()assigneeAgent := createHandlerTestAgent(t, "Nested Mention Assignee", nil)mentionedAgent := createHandlerTestAgent(t, "Nested Mention Target", nil)parentAgent := createHandlerTestAgent(t, "Nested Direct Parent", nil)var number int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `UPDATE workspaceSET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1WHERE id = $1 RETURNING issue_counter- `, testWorkspaceID).Scan(&number); err != nil {- t.Fatalf("next issue number: %v", err)- }+ `, testWorkspaceID).Scan(&number)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)- VALUES ($1, 'member', $2, $3, 'agent', $4, $5)- RETURNING id- `, testWorkspaceID, testUserID, "nested mention inheritance regression", assigneeAgent, number).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ issueID := dbfx.Insert(t, "issue", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "creator_type": "member",+ "creator_id": testUserID,+ "title": "nested mention inheritance regression",+ "assignee_type": "agent",+ "assignee_id": assigneeAgent,+ "number": number,+ })t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)@@ -3969,27 +3342,19 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {countQueued := func(agentID string) int {t.Helper()var n int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, agentID).Scan(&n); err != nil {- t.Fatalf("count queued tasks: %v", err)- }+ `, issueID, agentID).Scan(&n)return n}postMemberComment := func(body map[string]any) CommentResponse {t.Helper()- w := httptest.NewRecorder()r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)r = withURLParam(r, "id", issueID)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)var resp CommentResponse- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode comment response: %v", err)- }+ w.JSON(&resp)return resp}@@ -3999,18 +3364,13 @@ func TestNestedMemberReplyUsesDirectParentForMentionInheritance(t *testing.T) {if got := countQueued(mentionedAgent); got != 1 {t.Fatalf("expected root mention to queue mentioned agent once, got %d", got)}- if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET status = 'cancelled' WHERE issue_id = $1`, issueID); err != nil {- t.Fatalf("cancel root mention task: %v", err)- }+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'cancelled' WHERE issue_id = $1`, issueID)- var directParentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)- VALUES ($1, $2, 'agent', $3, $4, $5)- RETURNING id- `, testWorkspaceID, issueID, parentAgent, "looks like redirect config", root.ID).Scan(&directParentID); err != nil {- t.Fatalf("insert direct parent reply: %v", err)- }+ directParentID := dbfx.Comment(t, issueID, "looks like redirect config", testutil.Cols{+ "author_type": "agent",+ "author_id": parentAgent,+ "parent_id": root.ID,+ })nested := postMemberComment(map[string]any{"content": "can you also check session expiry?",@@ -4035,27 +3395,25 @@ func TestNestedMemberReplyUnderMemberSkipsAssigneeFallback(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")}- ctx := context.Background()assigneeAgent := createHandlerTestAgent(t, "Nested Participation Assignee", nil)var number int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `UPDATE workspaceSET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1WHERE id = $1 RETURNING issue_counter- `, testWorkspaceID).Scan(&number); err != nil {- t.Fatalf("next issue number: %v", err)- }+ `, testWorkspaceID).Scan(&number)- var issueID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, creator_type, creator_id, title, assignee_type, assignee_id, number)- VALUES ($1, 'member', $2, $3, 'agent', $4, $5)- RETURNING id- `, testWorkspaceID, testUserID, "nested participation regression", assigneeAgent, number).Scan(&issueID); err != nil {- t.Fatalf("create issue: %v", err)- }+ issueID := dbfx.Insert(t, "issue", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "creator_type": "member",+ "creator_id": testUserID,+ "title": "nested participation regression",+ "assignee_type": "agent",+ "assignee_id": assigneeAgent,+ "number": number,+ })t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID)@@ -4065,52 +3423,30 @@ func TestNestedMemberReplyUnderMemberSkipsAssigneeFallback(t *testing.T) {countAssigneeQueued := func() int {t.Helper()var n int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'- `, issueID, assigneeAgent).Scan(&n); err != nil {- t.Fatalf("count queued tasks: %v", err)- }+ `, issueID, assigneeAgent).Scan(&n)return n}postMemberComment := func(body map[string]any) CommentResponse {t.Helper()- w := httptest.NewRecorder()r := newRequest("POST", "/api/issues/"+issueID+"/comments", body)r = withURLParam(r, "id", issueID)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)var resp CommentResponse- if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {- t.Fatalf("decode comment response: %v", err)- }+ w.JSON(&resp)return resp}- var rootID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content)- VALUES ($1, $2, 'member', $3, 'this cache question is for humans')- RETURNING id- `, testWorkspaceID, issueID, testUserID).Scan(&rootID); err != nil {- t.Fatalf("insert root comment: %v", err)- }- if _, err := testPool.Exec(ctx, `+ rootID := dbfx.Comment(t, issueID, "this cache question is for humans")+ dbfx.Exec(t, `INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)VALUES ($1, $2, 'agent', $3, 'expiration policy is the issue', $4)- `, testWorkspaceID, issueID, assigneeAgent, rootID); err != nil {- t.Fatalf("insert assignee reply: %v", err)- }- var humanParentID string- if err := testPool.QueryRow(ctx, `- INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, parent_id)- VALUES ($1, $2, 'member', $3, 'I have seen this too', $4)- RETURNING id- `, testWorkspaceID, issueID, testUserID, rootID).Scan(&humanParentID); err != nil {- t.Fatalf("insert human direct parent: %v", err)- }+ `, testWorkspaceID, issueID, assigneeAgent, rootID)+ humanParentID := dbfx.Comment(t, issueID, "I have seen this too", testutil.Cols{+ "parent_id": rootID,+ })nested := postMemberComment(map[string]any{"content": "what should the expiration be?",@@ -4138,15 +3474,11 @@ func TestAgentExplicitMentionStillTriggers(t *testing.T) {agentA := createHandlerTestAgent(t, "Handoff Agent A", nil)agentB := createHandlerTestAgent(t, "Handoff Agent B", nil)- w := httptest.NewRecorder()req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "Agent explicit handoff test","status": "todo",})- testHandler.CreateIssue(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusCreated)var issue IssueResponsejson.NewDecoder(w.Body).Decode(&issue)issueID := issue.ID@@ -4176,17 +3508,13 @@ func TestAgentExplicitMentionStillTriggers(t *testing.T) {// suppression (authorType=="agent") would not fire.agentATask := createHandlerTestTaskForAgent(t, agentA)explicitMention := fmt.Sprintf("[@Agent B](mention://agent/%s) please take it from here", agentB)- w = httptest.NewRecorder()r := newRequest("POST", "/api/issues/"+issueID+"/comments", map[string]any{"content": explicitMention,})r = withURLParam(r, "id", issueID)r.Header.Set("X-Agent-ID", agentA)r.Header.Set("X-Task-ID", agentATask)- testHandler.CreateComment(w, r)- if w.Code != http.StatusCreated {- t.Fatalf("agent A handoff: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w = testutil.Call(t, testHandler.CreateComment, r).Want(http.StatusCreated)if got := countTasks(agentB); got != 1 {t.Fatalf("expected 1 task for Agent B after explicit mention by Agent A, got %d", got)}diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.goindex 156ea76498..657bcd82d0 100644--- a/server/internal/handler/workspace_test.go+++ b/server/internal/handler/workspace_test.go@@ -7,12 +7,12 @@ import ("encoding/json""fmt""net/http"- "net/http/httptest""sort""strings""testing""time"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -27,12 +27,11 @@ func TestCreateWorkspace_RejectsReservedSlug(t *testing.T) {for _, slug := range reserved {t.Run(slug, func(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": fmt.Sprintf("Test %s", slug),"slug": slug,})- testHandler.CreateWorkspace(w, req)+ w := testutil.Call(t, testHandler.CreateWorkspace, req)if w.Code != http.StatusBadRequest {t.Fatalf("slug %q: expected 400, got %d: %s", slug, w.Code, w.Body.String())@@ -67,20 +66,14 @@ func TestCreateWorkspace_DoesNotMarkOnboarded(t *testing.T) {_, _ = testPool.Exec(context.Background(), `UPDATE "user" SET onboarded_at = NULL WHERE id = $1`, testUserID)})- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": "Onboarding Invariant Probe","slug": slug,})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusCreated)var onboardedAt *string- if err := testPool.QueryRow(ctx, `SELECT onboarded_at FROM "user" WHERE id = $1`, testUserID).Scan(&onboardedAt); err != nil {- t.Fatalf("lookup user: %v", err)- }+ dbfx.QueryRow(t, `SELECT onboarded_at FROM "user" WHERE id = $1`, testUserID).Scan(&onboardedAt)if onboardedAt != nil {t.Fatalf("CreateWorkspace marked user as onboarded; expected NULL, got %q. The workspace layout hard gate relies on this staying NULL until Step 3 CompleteOnboarding fires.", *onboardedAt)}@@ -98,9 +91,7 @@ func TestCreateWorkspace_DisabledByConfig(t *testing.T) {const slug = "handler-tests-disabled-create"ctx := context.Background()_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)- })+ dbfx.Cleanup(t, `DELETE FROM workspace WHERE slug = $1`, slug)prev := testHandler.cfgtestHandler.cfg = Config{@@ -109,20 +100,14 @@ func TestCreateWorkspace_DisabledByConfig(t *testing.T) {}t.Cleanup(func() { testHandler.cfg = prev })- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": "Disabled Create","slug": slug,})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusForbidden {- t.Fatalf("CreateWorkspace: expected 403 with flag on, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusForbidden)var count int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count); err != nil {- t.Fatalf("count workspaces: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count)if count != 0 {t.Fatalf("expected no workspace row to be written when gate fires, found %d", count)}@@ -140,38 +125,23 @@ func TestDeleteWorkspace_RequiresOwner(t *testing.T) {const slug = "handler-tests-delete-403"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description)-VALUES ($1, $2, $3)-RETURNING id-`, "Handler Test Delete 403", slug, "DeleteWorkspace handler permission test").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Handler Test Delete 403",+ "slug": slug,+ "description": "DeleteWorkspace handler permission test",})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, 'admin')-`, wsID, testUserID); err != nil {- t.Fatalf("create admin member: %v", err)- }+`, wsID, testUserID)- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)req = withURLParam(req, "id", wsID)- testHandler.DeleteWorkspace(w, req)-- if w.Code != http.StatusForbidden {- t.Fatalf("expected 403 from DeleteWorkspace handler for admin (non-owner), got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusForbidden)var exists bool- if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists); err != nil {- t.Fatalf("verify workspace: %v", err)- }+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists)if !exists {t.Fatal("workspace was deleted despite non-owner request — handler-level check did not fire")}@@ -186,196 +156,146 @@ func TestDeleteWorkspace_OwnerSucceeds(t *testing.T) {const slug = "handler-tests-delete-ok"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description)-VALUES ($1, $2, $3)-RETURNING id-`, "Handler Test Delete OK", slug, "DeleteWorkspace handler owner test").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Handler Test Delete OK",+ "slug": slug,+ "description": "DeleteWorkspace handler owner test",})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, 'owner')-`, wsID, testUserID); err != nil {- t.Fatalf("create owner member: %v", err)- }- if _, err := testPool.Exec(ctx, `+`, wsID, testUserID)+ dbfx.Exec(t, `INSERT INTO github_pending_check_suite (workspace_id, installation_id, repo_owner, repo_name, pr_number,suite_id, head_sha, app_id, status, suite_updated_at)VALUES ($1, 123456789, 'multica-ai', 'multica', 3366, 987654321, 'abc123', 15368, 'completed', now())-`, wsID); err != nil {- t.Fatalf("create pending check suite: %v", err)- }- var githubPRID string- if err := testPool.QueryRow(ctx, `-INSERT INTO github_pull_request (- workspace_id, installation_id, repo_owner, repo_name, pr_number,- title, state, html_url, pr_created_at, pr_updated_at, head_sha-)-VALUES ($1, 123456789, 'multica-ai', 'multica', 5265,- 'Workspace cleanup snapshot', 'open', 'https://github.com/multica-ai/multica/pull/5265',- now(), now(), 'head-a')-RETURNING id-`, wsID).Scan(&githubPRID); err != nil {- t.Fatalf("create github PR snapshot parent: %v", err)- }- if _, err := testPool.Exec(ctx, `+`, wsID)+ githubPRID := dbfx.Insert(t, "github_pull_request", testutil.Cols{+ "workspace_id": wsID,+ "installation_id": 123456789,+ "repo_owner": "multica-ai",+ "repo_name": "multica",+ "pr_number": 5265,+ "title": "Workspace cleanup snapshot",+ "state": "open",+ "html_url": "https://github.com/multica-ai/multica/pull/5265",+ "pr_created_at": testutil.Raw("now()"),+ "pr_updated_at": testutil.Raw("now()"),+ "head_sha": "head-a",+ })+ dbfx.Exec(t, `INSERT INTO github_pull_request_check_run (pr_id, head_sha, ordinal, name, status, conclusion, is_status_context)VALUES ($1, 'head-a', 0, 'backend', 'completed', 'success', false)-`, githubPRID); err != nil {- t.Fatalf("create github PR check run: %v", err)- }+`, githubPRID)t.Cleanup(func() {_, _ = testPool.Exec(context.Background(), `DELETE FROM github_pull_request_check_run WHERE pr_id = $1`, githubPRID)_, _ = testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, githubPRID)})- var propertyID string- if err := testPool.QueryRow(ctx, `-INSERT INTO issue_property (workspace_id, name, type)-VALUES ($1, 'Delete cleanup property', 'text')-RETURNING id-`, wsID).Scan(&propertyID); err != nil {- t.Fatalf("create issue property: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, propertyID)+ propertyID := dbfx.Insert(t, "issue_property", testutil.Cols{+ "workspace_id": wsID,+ "name": "Delete cleanup property",+ "type": "text",})- var runtimeID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_runtime (- workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id-)-VALUES ($1, 'Workspace delete runtime', 'cloud', 'delete-test', 'offline', '', '{}'::jsonb, $2)-RETURNING id-`, wsID, testUserID).Scan(&runtimeID); err != nil {- t.Fatalf("create workspace runtime: %v", err)- }+ runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{+ "workspace_id": wsID,+ "name": "Workspace delete runtime",+ "runtime_mode": "cloud",+ "provider": "delete-test",+ "status": "offline",+ "device_info": "",+ "metadata": testutil.Raw("'{}'::jsonb"),+ "owner_id": testUserID,+ })- var agentID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent (- workspace_id, name, runtime_mode, runtime_config, runtime_id, owner_id-)-VALUES ($1, 'Workspace delete agent', 'cloud', '{}'::jsonb, $2, $3)-RETURNING id-`, wsID, runtimeID, testUserID).Scan(&agentID); err != nil {- t.Fatalf("create workspace agent: %v", err)- }+ agentID := dbfx.Insert(t, "agent", testutil.Cols{+ "workspace_id": wsID,+ "name": "Workspace delete agent",+ "runtime_mode": "cloud",+ "runtime_config": testutil.Raw("'{}'::jsonb"),+ "runtime_id": runtimeID,+ "owner_id": testUserID,+ })- var issueID string- if err := testPool.QueryRow(ctx, `-INSERT INTO issue (workspace_id, title, creator_type, creator_id)-VALUES ($1, 'Workspace delete issue', 'member', $2)-RETURNING id-`, wsID, testUserID).Scan(&issueID); err != nil {- t.Fatalf("create workspace issue: %v", err)- }+ issueID := dbfx.Insert(t, "issue", testutil.Cols{+ "workspace_id": wsID,+ "title": "Workspace delete issue",+ "creator_type": "member",+ "creator_id": testUserID,+ })- var autopilotID string- if err := testPool.QueryRow(ctx, `-INSERT INTO autopilot (- workspace_id, title, assignee_id, created_by_type, created_by_id-)-VALUES ($1, 'Workspace delete autopilot', $2, 'member', $3)-RETURNING id-`, wsID, agentID, testUserID).Scan(&autopilotID); err != nil {- t.Fatalf("create workspace autopilot: %v", err)- }+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": wsID,+ "title": "Workspace delete autopilot",+ "assignee_id": agentID,+ "created_by_type": "member",+ "created_by_id": testUserID,+ })- var autopilotRunID string- if err := testPool.QueryRow(ctx, `-INSERT INTO autopilot_run (autopilot_id, source, status, issue_id)-VALUES ($1, 'manual', 'completed', $2)-RETURNING id-`, autopilotID, issueID).Scan(&autopilotRunID); err != nil {- t.Fatalf("create workspace autopilot run: %v", err)- }+ autopilotRunID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "completed",+ "issue_id": issueID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, autopilot_run_id-)-VALUES ($1, $2, $3, 'completed', 0, $4)-RETURNING id-`, agentID, runtimeID, issueID, autopilotRunID).Scan(&taskID); err != nil {- t.Fatalf("create workspace task: %v", err)- }- if _, err := testPool.Exec(ctx, `+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "completed",+ "autopilot_run_id": autopilotRunID,+ })+ dbfx.Exec(t, `UPDATE autopilot_run SET task_id = $2 WHERE id = $1-`, autopilotRunID, taskID); err != nil {- t.Fatalf("link workspace autopilot run to task: %v", err)- }- if _, err := testPool.Exec(ctx, `+`, autopilotRunID, taskID)+ dbfx.Exec(t, `INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)VALUES ($1, 'delete-test', 'workspace-delete', 10, 5)-`, taskID); err != nil {- t.Fatalf("create workspace task usage: %v", err)- }+`, taskID)var rollupRuntimeID, rollupAgentID string- if err := testPool.QueryRow(ctx, `SELECT gen_random_uuid(), gen_random_uuid()`).Scan(&rollupRuntimeID, &rollupAgentID); err != nil {- t.Fatalf("create rollup fixture IDs: %v", err)- }- if _, err := testPool.Exec(ctx, `+ dbfx.QueryRow(t, `SELECT gen_random_uuid(), gen_random_uuid()`).Scan(&rollupRuntimeID, &rollupAgentID)+ dbfx.Exec(t, `INSERT INTO task_usage_hourly (bucket_hour, workspace_id, runtime_id, agent_id, provider, model,input_tokens, output_tokens, task_count, event_count)VALUES (date_trunc('hour', now()), $1, $2, $3, 'delete-test', 'workspace-rollup', 10, 5, 1, 1)-`, wsID, rollupRuntimeID, rollupAgentID); err != nil {- t.Fatalf("create workspace hourly usage: %v", err)- }- if _, err := testPool.Exec(ctx, `+`, wsID, rollupRuntimeID, rollupAgentID)+ dbfx.Exec(t, `INSERT INTO task_usage_hourly_dirty (bucket_hour, workspace_id, runtime_id, agent_id, provider, model)VALUES (date_trunc('hour', now()), $1, $2, $3, 'delete-test', 'workspace-rollup')-`, wsID, rollupRuntimeID, rollupAgentID); err != nil {- t.Fatalf("create workspace dirty usage: %v", err)- }-- var runtimeProfileID string- if err := testPool.QueryRow(ctx, `-INSERT INTO runtime_profile (- workspace_id, display_name, protocol_family, command_name, created_by-)-VALUES ($1, 'Delete cleanup profile', 'codex', 'codex', $2)-RETURNING id-`, wsID, testUserID).Scan(&runtimeProfileID); err != nil {- t.Fatalf("create runtime profile: %v", err)- }+`, wsID, rollupRuntimeID, rollupAgentID)++ runtimeProfileID := dbfx.Insert(t, "runtime_profile", testutil.Cols{+ "workspace_id": wsID,+ "display_name": "Delete cleanup profile",+ "protocol_family": "codex",+ "command_name": "codex",+ "created_by": testUserID,+ })- var ruleVersionID string- if err := testPool.QueryRow(ctx, `-INSERT INTO autopilot_rule_version (- autopilot_id, workspace_id, published_by_type, published_by_id-)-VALUES (gen_random_uuid(), $1, 'member', $2)-RETURNING id-`, wsID, testUserID).Scan(&ruleVersionID); err != nil {- t.Fatalf("create autopilot rule version: %v", err)- }+ ruleVersionID := dbfx.Insert(t, "autopilot_rule_version", testutil.Cols{+ "autopilot_id": testutil.Raw("gen_random_uuid()"),+ "workspace_id": wsID,+ "published_by_type": "member",+ "published_by_id": testUserID,+ })const pendingObjectKey = "workspace-delete-pending-object"- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO channel_media_pending_object (storage_key, workspace_id, chat_message_id, storage_url)VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/pending-object')-`, pendingObjectKey, wsID); err != nil {- t.Fatalf("create pending channel media object: %v", err)- }+`, pendingObjectKey, wsID)t.Cleanup(func() {_, _ = testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE workspace_id = $1`, wsID)@@ -385,43 +305,30 @@ VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/pending-object')_, _ = testPool.Exec(context.Background(), `DELETE FROM channel_media_pending_object WHERE storage_key = $1`, pendingObjectKey)})- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)req = withURLParam(req, "id", wsID)- testHandler.DeleteWorkspace(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("expected 204 from DeleteWorkspace handler for owner, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusNoContent)var exists bool- if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists); err != nil {- t.Fatalf("verify workspace: %v", err)- }+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists)if exists {t.Fatal("workspace still exists after owner DELETE")}var pendingCount int- if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM github_pending_check_suite WHERE workspace_id = $1`, wsID).Scan(&pendingCount); err != nil {- t.Fatalf("verify pending check suites: %v", err)- }+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM github_pending_check_suite WHERE workspace_id = $1`, wsID).Scan(&pendingCount)if pendingCount != 0 {t.Fatalf("pending check suites were not cleaned up for deleted workspace: %d", pendingCount)}var checkRunCount int- if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM github_pull_request_check_run WHERE pr_id = $1`, githubPRID).Scan(&checkRunCount); err != nil {- t.Fatalf("verify github PR check-run cleanup: %v", err)- }+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM github_pull_request_check_run WHERE pr_id = $1`, githubPRID).Scan(&checkRunCount)if checkRunCount != 0 {t.Fatalf("github PR check runs were not cleaned up for deleted workspace: %d", checkRunCount)}var propertyCount int- if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM issue_property WHERE id = $1`, propertyID).Scan(&propertyCount); err != nil {- t.Fatalf("verify issue property cleanup: %v", err)- }+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM issue_property WHERE id = $1`, propertyID).Scan(&propertyCount)if propertyCount != 0 {t.Fatalf("issue properties were not cleaned up for deleted workspace: %d", propertyCount)}@@ -433,43 +340,36 @@ VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/pending-object')"autopilot_rule_version",} {var count int- if err := testPool.QueryRow(ctx, `SELECT COUNT(*) FROM `+table+` WHERE workspace_id = $1`, wsID).Scan(&count); err != nil {- t.Fatalf("verify %s cleanup: %v", table, err)- }+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM `+table+` WHERE workspace_id = $1`, wsID).Scan(&count)if count != 0 {t.Fatalf("%s rows survived workspace delete: %d", table, count)}}var pendingObjectState string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT stateFROM channel_media_pending_objectWHERE storage_key = $1-`, pendingObjectKey).Scan(&pendingObjectState); err != nil {- t.Fatalf("verify pending channel media object handoff: %v", err)- }+`, pendingObjectKey).Scan(&pendingObjectState)if pendingObjectState != "deleting" {t.Fatalf("pending channel media object state = %q, want deleting", pendingObjectState)}}func TestDeleteWorkspace_DirtyTriggersHaveTeardownGuard(t *testing.T) {- ctx := context.Background()for _, triggerName := range []string{"trg_atq_dirty_hourly","trg_issue_delete_dirty_hourly","trg_tu_dirty_hourly",} {var definition string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT pg_get_triggerdef(oid)FROM pg_triggerWHERE tgname = $1AND NOT tgisinternal-`, triggerName).Scan(&definition); err != nil {- t.Fatalf("read trigger %s: %v", triggerName, err)- }+`, triggerName).Scan(&definition)if !strings.Contains(definition, "multica.workspace_teardown") {t.Fatalf("trigger %s does not guard workspace teardown: %s", triggerName, definition)}@@ -600,20 +500,16 @@ func TestDeleteWorkspace_PreservesOtherWorkspaceData(t *testing.T) {_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug IN ($1, $2)`, targetSlug, neighborSlug)var targetWorkspaceID, neighborWorkspaceID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO workspace (name, slug)VALUES ('Workspace delete tenant target', $1)RETURNING id-`, targetSlug).Scan(&targetWorkspaceID); err != nil {- t.Fatalf("create target workspace: %v", err)- }- if err := testPool.QueryRow(ctx, `+`, targetSlug).Scan(&targetWorkspaceID)+ dbfx.QueryRow(t, `INSERT INTO workspace (name, slug)VALUES ('Workspace delete tenant neighbor', $1)RETURNING id-`, neighborSlug).Scan(&neighborWorkspaceID); err != nil {- t.Fatalf("create neighbor workspace: %v", err)- }+`, neighborSlug).Scan(&neighborWorkspaceID)t.Cleanup(func() {for _, workspaceID := range []string{targetWorkspaceID, neighborWorkspaceID} {_, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)@@ -623,12 +519,10 @@ RETURNING id}})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, 'owner')-`, targetWorkspaceID, testUserID); err != nil {- t.Fatalf("create target owner: %v", err)- }+`, targetWorkspaceID, testUserID)type tenantFixture struct {workspaceID string@@ -640,60 +534,44 @@ VALUES ($1, $2, 'owner'){workspaceID: neighborWorkspaceID, mediaKey: neighborMediaKey},}for _, fixture := range fixtures {- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO issue (workspace_id, title, creator_type, creator_id)VALUES ($1, 'Workspace delete tenant isolation', 'member', $2)RETURNING id-`, fixture.workspaceID, testUserID).Scan(&fixture.issueID); err != nil {- t.Fatalf("create issue for workspace %s: %v", fixture.workspaceID, err)- }- if _, err := testPool.Exec(ctx, `+`, fixture.workspaceID, testUserID).Scan(&fixture.issueID)+ dbfx.Exec(t, `INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)VALUES ($1, $2, 'member', $3, 'Workspace delete tenant isolation')-`, fixture.issueID, fixture.workspaceID, testUserID); err != nil {- t.Fatalf("create comment for workspace %s: %v", fixture.workspaceID, err)- }- if _, err := testPool.Exec(ctx, `+`, fixture.issueID, fixture.workspaceID, testUserID)+ dbfx.Exec(t, `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, issue_id, title)VALUES ($1, 'member', $2, 'workspace-delete-test', $3, 'Workspace delete tenant isolation')-`, fixture.workspaceID, testUserID, fixture.issueID); err != nil {- t.Fatalf("create inbox item for workspace %s: %v", fixture.workspaceID, err)- }- if _, err := testPool.Exec(ctx, `+`, fixture.workspaceID, testUserID, fixture.issueID)+ dbfx.Exec(t, `INSERT INTO runtime_profile (workspace_id, display_name, protocol_family, command_name, created_by)VALUES ($1, 'Workspace delete tenant isolation', 'codex', 'codex', $2)-`, fixture.workspaceID, testUserID); err != nil {- t.Fatalf("create runtime profile for workspace %s: %v", fixture.workspaceID, err)- }- if _, err := testPool.Exec(ctx, `+`, fixture.workspaceID, testUserID)+ dbfx.Exec(t, `INSERT INTO task_usage_hourly_dirty (bucket_hour, workspace_id, runtime_id, agent_id, provider, model)VALUES (date_trunc('hour', now()), $1, gen_random_uuid(), gen_random_uuid(), 'workspace-delete-tenant', 'isolation')-`, fixture.workspaceID); err != nil {- t.Fatalf("create dirty usage for workspace %s: %v", fixture.workspaceID, err)- }- if _, err := testPool.Exec(ctx, `+`, fixture.workspaceID)+ dbfx.Exec(t, `INSERT INTO channel_media_pending_object (storage_key, workspace_id, chat_message_id, storage_url)VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/tenant-isolation')-`, fixture.mediaKey, fixture.workspaceID); err != nil {- t.Fatalf("create media ledger for workspace %s: %v", fixture.workspaceID, err)- }+`, fixture.mediaKey, fixture.workspaceID)}- recorder := httptest.NewRecorder()request := newRequest(http.MethodDelete, "/api/workspaces/"+targetWorkspaceID, nil)request = withURLParam(request, "id", targetWorkspaceID)- testHandler.DeleteWorkspace(recorder, request)- if recorder.Code != http.StatusNoContent {- t.Fatalf("DeleteWorkspace returned %d: %s", recorder.Code, recorder.Body.String())- }+ testutil.Call(t, testHandler.DeleteWorkspace, request).Want(http.StatusNoContent)for table, predicate := range map[string]string{"workspace": "id",@@ -705,24 +583,20 @@ VALUES ($1, $2, gen_random_uuid(), 's3://workspace-delete/tenant-isolation')"channel_media_pending_object": "workspace_id",} {var count int- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT COUNT(*) FROM `+table+` WHERE `+predicate+` = $1-`, neighborWorkspaceID).Scan(&count); err != nil {- t.Fatalf("count neighbor %s rows: %v", table, err)- }+`, neighborWorkspaceID).Scan(&count)if count != 1 {t.Fatalf("neighbor %s rows = %d, want 1", table, count)}}var neighborMediaState string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `SELECT stateFROM channel_media_pending_objectWHERE storage_key = $1-`, neighborMediaKey).Scan(&neighborMediaState); err != nil {- t.Fatalf("read neighbor media state: %v", err)- }+`, neighborMediaKey).Scan(&neighborMediaState)if neighborMediaState != "pending" {t.Fatalf("neighbor media state = %q, want pending", neighborMediaState)}@@ -740,42 +614,27 @@ func TestUpdateWorkspace_AvatarURL(t *testing.T) {const slug = "handler-tests-avatar-url"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description)-VALUES ($1, $2, $3)-RETURNING id-`, "Handler Test Avatar URL", slug, "UpdateWorkspace avatar_url test").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Handler Test Avatar URL",+ "slug": slug,+ "description": "UpdateWorkspace avatar_url test",})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, 'owner')-`, wsID, testUserID); err != nil {- t.Fatalf("create owner member: %v", err)- }+`, wsID, testUserID)const avatarURL = "https://cdn.example.com/workspaces/abc/logo.png"- w := httptest.NewRecorder()req := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{"avatar_url": avatarURL,})req = withURLParam(req, "id", wsID)- testHandler.UpdateWorkspace(w, req)-- if w.Code != http.StatusOK {- t.Fatalf("expected 200 from UpdateWorkspace, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusOK)var resp WorkspaceResponse- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if resp.AvatarURL == nil || *resp.AvatarURL != avatarURL {t.Fatalf("expected avatar_url %q in response, got %v", avatarURL, resp.AvatarURL)}@@ -784,29 +643,20 @@ VALUES ($1, $2, 'owner')}var dbAvatar *string- if err := testPool.QueryRow(ctx, `SELECT avatar_url FROM workspace WHERE id = $1`, wsID).Scan(&dbAvatar); err != nil {- t.Fatalf("read avatar_url back: %v", err)- }+ dbfx.QueryRow(t, `SELECT avatar_url FROM workspace WHERE id = $1`, wsID).Scan(&dbAvatar)if dbAvatar == nil || *dbAvatar != avatarURL {t.Fatalf("expected avatar_url %q persisted, got %v", avatarURL, dbAvatar)}// A follow-up update that doesn't include avatar_url must leave it alone.- w2 := httptest.NewRecorder()req2 := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{"description": "new description",})req2 = withURLParam(req2, "id", wsID)- testHandler.UpdateWorkspace(w2, req2)-- if w2.Code != http.StatusOK {- t.Fatalf("expected 200 from second UpdateWorkspace, got %d: %s", w2.Code, w2.Body.String())- }+ w2 := testutil.Call(t, testHandler.UpdateWorkspace, req2).Want(http.StatusOK)var resp2 WorkspaceResponse- if err := json.Unmarshal(w2.Body.Bytes(), &resp2); err != nil {- t.Fatalf("decode second response: %v", err)- }+ w2.JSON(&resp2)if resp2.AvatarURL == nil || *resp2.AvatarURL != avatarURL {t.Fatalf("avatar_url should be preserved by partial update, got %v", resp2.AvatarURL)}@@ -818,50 +668,34 @@ func TestUpdateWorkspace_ReposValidation(t *testing.T) {const slug = "handler-tests-repos-validation"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description)-VALUES ($1, $2, $3)-RETURNING id-`, "Handler Test Repos Validation", slug, "UpdateWorkspace repos validation test").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Handler Test Repos Validation",+ "slug": slug,+ "description": "UpdateWorkspace repos validation test",})- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role)VALUES ($1, $2, 'owner')-`, wsID, testUserID); err != nil {- t.Fatalf("create owner member: %v", err)- }+`, wsID, testUserID)t.Run("rejects invalid repo URLs without persisting", func(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{"repos": []map[string]any{{"url": "not-a-url"},},})req = withURLParam(req, "id", wsID)- testHandler.UpdateWorkspace(w, req)-- if w.Code != http.StatusBadRequest {- t.Fatalf("expected 400 from invalid repos update, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusBadRequest)var raw []byte- if err := testPool.QueryRow(ctx, `SELECT repos FROM workspace WHERE id = $1`, wsID).Scan(&raw); err != nil {- t.Fatalf("read repos: %v", err)- }+ dbfx.QueryRow(t, `SELECT repos FROM workspace WHERE id = $1`, wsID).Scan(&raw)if string(raw) != "[]" {t.Fatalf("invalid repos update should not persist, got %s", raw)}})t.Run("normalizes valid repos", func(t *testing.T) {- w := httptest.NewRecorder()req := newRequest("PATCH", "/api/workspaces/"+wsID, map[string]any{"repos": []map[string]any{{@@ -877,16 +711,10 @@ VALUES ($1, $2, 'owner')},})req = withURLParam(req, "id", wsID)- testHandler.UpdateWorkspace(w, req)-- if w.Code != http.StatusOK {- t.Fatalf("expected 200 from valid repos update, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusOK)var raw []byte- if err := testPool.QueryRow(ctx, `SELECT repos FROM workspace WHERE id = $1`, wsID).Scan(&raw); err != nil {- t.Fatalf("read repos: %v", err)- }+ dbfx.QueryRow(t, `SELECT repos FROM workspace WHERE id = $1`, wsID).Scan(&raw)var repos []workspaceRepoRefif err := json.Unmarshal(raw, &repos); err != nil {t.Fatalf("decode repos: %v", err)@@ -924,31 +752,25 @@ func setupRevocationFixture(t *testing.T, slug, daemonID string) revocationFixtu_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description, issue_prefix)-VALUES ($1, $2, $3, $4)-RETURNING id-`, "Revocation "+slug, slug, "revocation test", "REV").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Revocation " + slug,+ "slug": slug,+ "description": "revocation test",+ "issue_prefix": "REV",+ })// Requester (= testUserID) is always an owner so DeleteMember authorization// passes. Two owners total so LeaveWorkspace doesn't trip the "must keep// at least one owner" guard.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')-`, wsID, testUserID); err != nil {- t.Fatalf("create requester member: %v", err)- }+`, wsID, testUserID)targetEmail := fmt.Sprintf("revocation-%[email protected]", slug)- var targetUserID string- if err := testPool.QueryRow(ctx, `-INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id-`, "Revocation Target "+slug, targetEmail).Scan(&targetUserID); err != nil {- t.Fatalf("create target user: %v", err)- }+ targetUserID := dbfx.Insert(t, "user", testutil.Cols{+ "name": "Revocation Target " + slug,+ "email": targetEmail,+ })// Cleanup ordering: workspace first (cascade clears agent_runtime,// agent, member, daemon_token), then user (whose deletion would@@ -958,57 +780,40 @@ INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id_, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, targetUserID)})- var memberID string- if err := testPool.QueryRow(ctx, `-INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner') RETURNING id-`, wsID, targetUserID).Scan(&memberID); err != nil {- t.Fatalf("create target member: %v", err)- }+ memberID := dbfx.Insert(t, "member", testutil.Cols{+ "workspace_id": wsID,+ "user_id": targetUserID,+ "role": "owner",+ })- var runtimeID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status,- device_info, metadata, owner_id, last_seen_at-)-VALUES ($1, $2, 'Target Runtime', 'local', 'multica_daemon', 'online', '', '{}'::jsonb, $3, now())-RETURNING id-`, wsID, daemonID, targetUserID).Scan(&runtimeID); err != nil {- t.Fatalf("insert runtime: %v", err)- }+ runtimeID := dbfx.Runtime(t, "Target Runtime", testutil.Cols{+ "workspace_id": wsID,+ "daemon_id": daemonID,+ "runtime_mode": "local",+ "provider": "multica_daemon",+ "owner_id": targetUserID,+ })- var agentID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent (- workspace_id, name, description, runtime_mode, runtime_config,- runtime_id, visibility, max_concurrent_tasks, owner_id-)-VALUES ($1, 'Target Agent', '', 'local', '{}'::jsonb, $2, 'workspace', 1, $3)-RETURNING id-`, wsID, runtimeID, targetUserID).Scan(&agentID); err != nil {- t.Fatalf("insert agent: %v", err)- }+ agentID := dbfx.Agent(t, "Target Agent", runtimeID, testutil.Cols{+ "workspace_id": wsID,+ "runtime_mode": "local",+ "visibility": "workspace",+ "owner_id": targetUserID,+ })- var taskID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority)-VALUES ($1, $2, 'queued', 0)-RETURNING id-`, agentID, runtimeID).Scan(&taskID); err != nil {- t.Fatalf("insert task: %v", err)- }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ })// daemon_token row — paired with the runtime's daemon_id so the// revocation should sweep its hash up via DeleteDaemonTokensByWorkspaceAndDaemons.rawToken := "mdt_test_" + slugsum := sha256.Sum256([]byte(rawToken))tokenHash := hex.EncodeToString(sum[:])- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at)VALUES ($1, $2, $3, now() + interval '1 day')-`, tokenHash, wsID, daemonID); err != nil {- t.Fatalf("insert daemon_token: %v", err)- }+`, tokenHash, wsID, daemonID)return revocationFixture{WorkspaceID: wsID,@@ -1024,44 +829,33 @@ VALUES ($1, $2, $3, now() + interval '1 day')func assertRevoked(t *testing.T, fx revocationFixture) {t.Helper()- ctx := context.Background()var memberExists bool- if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM member WHERE id = $1)`, fx.MemberID).Scan(&memberExists); err != nil {- t.Fatalf("query member: %v", err)- }+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM member WHERE id = $1)`, fx.MemberID).Scan(&memberExists)if memberExists {t.Fatal("member row was not deleted")}var runtimeStatus string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_runtime WHERE id = $1`, fx.RuntimeID).Scan(&runtimeStatus); err != nil {- t.Fatalf("query runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_runtime WHERE id = $1`, fx.RuntimeID).Scan(&runtimeStatus)if runtimeStatus != "offline" {t.Fatalf("expected runtime offline, got %q", runtimeStatus)}var archivedAt *string- if err := testPool.QueryRow(ctx, `SELECT archived_at::text FROM agent WHERE id = $1`, fx.AgentID).Scan(&archivedAt); err != nil {- t.Fatalf("query agent: %v", err)- }+ dbfx.QueryRow(t, `SELECT archived_at::text FROM agent WHERE id = $1`, fx.AgentID).Scan(&archivedAt)if archivedAt == nil {t.Fatal("agent was not archived")}var taskStatus string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, fx.TaskID).Scan(&taskStatus); err != nil {- t.Fatalf("query task: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, fx.TaskID).Scan(&taskStatus)if taskStatus != "cancelled" {t.Fatalf("expected task cancelled, got %q", taskStatus)}var tokenExists bool- if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM daemon_token WHERE token_hash = $1)`, fx.TokenHash).Scan(&tokenExists); err != nil {- t.Fatalf("query daemon_token: %v", err)- }+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM daemon_token WHERE token_hash = $1)`, fx.TokenHash).Scan(&tokenExists)if tokenExists {t.Fatal("daemon_token row was not deleted")}@@ -1075,15 +869,10 @@ func assertRevoked(t *testing.T, fx revocationFixture) {func TestDeleteMember_RevokesTargetRuntimes(t *testing.T) {fx := setupRevocationFixture(t, "handler-tests-revoke-kick", "daemon-revoke-kick")- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)req.Header.Set("X-Workspace-ID", fx.WorkspaceID)req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)- testHandler.DeleteMember(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)assertRevoked(t, fx)}@@ -1094,7 +883,6 @@ func TestDeleteMember_RevokesTargetRuntimes(t *testing.T) {// the member-row delete, while leaving a remaining member's binding intact.func TestDeleteMember_PrunesChannelUserBindings(t *testing.T) {fx := setupRevocationFixture(t, "handler-tests-revoke-binding", "daemon-revoke-binding")- ctx := context.Background()const appID = "cli_revoke_binding"const removedOpenID = "ou_revoke_binding_removed"@@ -1114,55 +902,40 @@ func TestDeleteMember_PrunesChannelUserBindings(t *testing.T) {t.Cleanup(cleanChannel)var installID string- if err := testPool.QueryRow(ctx, `+ dbfx.QueryRow(t, `INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id)VALUES ($1, $2, 'feishu', jsonb_build_object('app_id', $3::text), $4)RETURNING id-`, fx.WorkspaceID, fx.AgentID, appID, testUserID).Scan(&installID); err != nil {- t.Fatalf("insert channel_installation: %v", err)- }+`, fx.WorkspaceID, fx.AgentID, appID, testUserID).Scan(&installID)// Binding for the member being removed — must be pruned.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id)VALUES ($1, $2, $3, 'feishu', $4)-`, fx.WorkspaceID, fx.TargetUserID, installID, removedOpenID); err != nil {- t.Fatalf("insert removed-member binding: %v", err)- }+`, fx.WorkspaceID, fx.TargetUserID, installID, removedOpenID)// Binding for the requester (an owner who stays) — must survive, proving// the prune is scoped to the removed user, not the whole workspace.- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_id, channel_type, channel_user_id)VALUES ($1, $2, $3, 'feishu', $4)-`, fx.WorkspaceID, testUserID, installID, keepOpenID); err != nil {- t.Fatalf("insert remaining-member binding: %v", err)- }+`, fx.WorkspaceID, testUserID, installID, keepOpenID)- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)req.Header.Set("X-Workspace-ID", fx.WorkspaceID)req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)- testHandler.DeleteMember(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)var removedExists bool- if err := testPool.QueryRow(ctx,- `SELECT EXISTS (SELECT 1 FROM channel_user_binding WHERE channel_user_id = $1)`, removedOpenID).Scan(&removedExists); err != nil {- t.Fatalf("query removed-member binding: %v", err)- }+ dbfx.QueryRow(t,+ `SELECT EXISTS (SELECT 1 FROM channel_user_binding WHERE channel_user_id = $1)`, removedOpenID).Scan(&removedExists)if removedExists {t.Fatal("removed member's channel_user_binding was not pruned")}var keepExists bool- if err := testPool.QueryRow(ctx,- `SELECT EXISTS (SELECT 1 FROM channel_user_binding WHERE channel_user_id = $1)`, keepOpenID).Scan(&keepExists); err != nil {- t.Fatalf("query remaining-member binding: %v", err)- }+ dbfx.QueryRow(t,+ `SELECT EXISTS (SELECT 1 FROM channel_user_binding WHERE channel_user_id = $1)`, keepOpenID).Scan(&keepExists)if !keepExists {t.Fatal("remaining member's channel_user_binding was wrongly pruned")}@@ -1176,16 +949,11 @@ func TestLeaveWorkspace_RevokesOwnRuntimes(t *testing.T) {// Re-target the request from the leaving member's perspective: the// leaver is the request actor, not the workspace owner.- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/leave", nil)req.Header.Set("X-User-ID", fx.TargetUserID)req.Header.Set("X-Workspace-ID", fx.WorkspaceID)req = withURLParam(req, "id", fx.WorkspaceID)- testHandler.LeaveWorkspace(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("LeaveWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.LeaveWorkspace, req).Want(http.StatusNoContent)assertRevoked(t, fx)}@@ -1201,43 +969,27 @@ func TestLeaveWorkspace_RevokesOwnRuntimes(t *testing.T) {// queued tasks would remain claimable.func TestDeleteMember_CancelsTasksFromAgentReassignment(t *testing.T) {fx := setupRevocationFixture(t, "handler-tests-revoke-reassign", "daemon-revoke-reassign")- ctx := context.Background()// Create a SECOND runtime in the workspace owned by the requester// (not the leaving member). The agent originally lived here.- var otherRuntimeID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_runtime (- workspace_id, daemon_id, name, runtime_mode, provider, status,- device_info, metadata, owner_id, last_seen_at-)-VALUES ($1, $2, 'Other Runtime', 'local', 'multica_daemon', 'online', '', '{}'::jsonb, $3, now())-RETURNING id-`, fx.WorkspaceID, "daemon-revoke-reassign-other", testUserID).Scan(&otherRuntimeID); err != nil {- t.Fatalf("insert other runtime: %v", err)- }+ otherRuntimeID := dbfx.Runtime(t, "Other Runtime", testutil.Cols{+ "workspace_id": fx.WorkspaceID,+ "daemon_id": "daemon-revoke-reassign-other",+ "runtime_mode": "local",+ "provider": "multica_daemon",+ })// Queue a task on the agent while it was still pinned to the OTHER// runtime (simulating a task created before the agent was reassigned// to the leaving member's runtime).- var orphanTaskID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority)-VALUES ($1, $2, 'queued', 0)-RETURNING id-`, fx.AgentID, otherRuntimeID).Scan(&orphanTaskID); err != nil {- t.Fatalf("insert orphan task: %v", err)- }+ orphanTaskID := dbfx.Task(t, fx.AgentID, testutil.Cols{+ "runtime_id": otherRuntimeID,+ })- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)req.Header.Set("X-Workspace-ID", fx.WorkspaceID)req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)- testHandler.DeleteMember(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)assertRevoked(t, fx)@@ -1245,9 +997,7 @@ RETURNING id// cancelled. Without the by-agent leg in CancelAgentTasksByRuntimeOrAgent// this stays 'queued' and would be picked up by the other runtime.var orphanStatus string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, orphanTaskID).Scan(&orphanStatus); err != nil {- t.Fatalf("query orphan task: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, orphanTaskID).Scan(&orphanStatus)if orphanStatus != "cancelled" {t.Fatalf("expected orphan task cancelled (archived agent leftover on other runtime), got %q", orphanStatus)}@@ -1255,9 +1005,7 @@ RETURNING id// And the OTHER runtime — owned by an active member — must still be// online: revocation is scoped to the leaving member's owned runtimes.var otherStatus string- if err := testPool.QueryRow(ctx, `SELECT status FROM agent_runtime WHERE id = $1`, otherRuntimeID).Scan(&otherStatus); err != nil {- t.Fatalf("query other runtime: %v", err)- }+ dbfx.QueryRow(t, `SELECT status FROM agent_runtime WHERE id = $1`, otherRuntimeID).Scan(&otherStatus)if otherStatus != "online" {t.Fatalf("expected other-member runtime to stay online, got %q", otherStatus)}@@ -1269,37 +1017,26 @@ RETURNING id// after its owner and runtime access have been removed.func TestDeleteMember_CancelsDeferredTasks(t *testing.T) {fx := setupRevocationFixture(t, "handler-tests-revoke-deferred", "daemon-revoke-deferred")- ctx := context.Background()- var deferredTaskID string- if err := testPool.QueryRow(ctx, `-INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, fire_at)-VALUES ($1, $2, 'deferred', 0, now() + interval '1 hour')-RETURNING id-`, fx.AgentID, fx.RuntimeID).Scan(&deferredTaskID); err != nil {- t.Fatalf("insert deferred task: %v", err)- }+ deferredTaskID := dbfx.Task(t, fx.AgentID, testutil.Cols{+ "runtime_id": fx.RuntimeID,+ "status": "deferred",+ "fire_at": testutil.Raw("now() + interval '1 hour'"),+ })- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)req.Header.Set("X-Workspace-ID", fx.WorkspaceID)req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)- testHandler.DeleteMember(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)assertRevoked(t, fx)var status stringvar completedAt *time.Time- if err := testPool.QueryRow(ctx,+ dbfx.QueryRow(t,`SELECT status, completed_at FROM agent_task_queue WHERE id = $1`,deferredTaskID,- ).Scan(&status, &completedAt); err != nil {- t.Fatalf("query deferred task: %v", err)- }+ ).Scan(&status, &completedAt)if status != "cancelled" || completedAt == nil {t.Fatalf("deferred task = (%q, %v), want cancelled with completed_at", status, completedAt)}@@ -1314,53 +1051,39 @@ func TestDeleteMember_NoRuntimes_DeletesMember(t *testing.T) {const slug = "handler-tests-revoke-no-runtimes"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- var wsID string- if err := testPool.QueryRow(ctx, `-INSERT INTO workspace (name, slug, description, issue_prefix)-VALUES ($1, $2, $3, $4)-RETURNING id-`, "Revocation no runtimes", slug, "revocation no-runtimes test", "REV").Scan(&wsID); err != nil {- t.Fatalf("create workspace: %v", err)- }+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Revocation no runtimes",+ "slug": slug,+ "description": "revocation no-runtimes test",+ "issue_prefix": "REV",+ })- if _, err := testPool.Exec(ctx, `+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')-`, wsID, testUserID); err != nil {- t.Fatalf("create requester member: %v", err)- }+`, wsID, testUserID)- var targetUserID string- if err := testPool.QueryRow(ctx, `-INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id-`, "Revocation No Runtimes Target", "[email protected]").Scan(&targetUserID); err != nil {- t.Fatalf("create target user: %v", err)- }+ targetUserID := dbfx.Insert(t, "user", testutil.Cols{+ "name": "Revocation No Runtimes Target",+ "email": "[email protected]",+ })t.Cleanup(func() {_, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)_, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, targetUserID)})- var memberID string- if err := testPool.QueryRow(ctx, `-INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin') RETURNING id-`, wsID, targetUserID).Scan(&memberID); err != nil {- t.Fatalf("create target member: %v", err)- }+ memberID := dbfx.Insert(t, "member", testutil.Cols{+ "workspace_id": wsID,+ "user_id": targetUserID,+ "role": "admin",+ })- w := httptest.NewRecorder()req := newRequest("DELETE", "/api/workspaces/"+wsID+"/members/"+memberID, nil)req.Header.Set("X-Workspace-ID", wsID)req = withURLParams(req, "id", wsID, "memberId", memberID)- testHandler.DeleteMember(w, req)-- if w.Code != http.StatusNoContent {- t.Fatalf("DeleteMember: expected 204, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)var memberExists bool- if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM member WHERE id = $1)`, memberID).Scan(&memberExists); err != nil {- t.Fatalf("query member: %v", err)- }+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM member WHERE id = $1)`, memberID).Scan(&memberExists)if memberExists {t.Fatal("member row was not deleted")}@@ -1502,24 +1225,16 @@ func TestCreateWorkspace_ChineseNameDerivesPrefixFromSlug(t *testing.T) {ctx := context.Background()const slug = "handler-tests-frontend-team"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)- })+ dbfx.Cleanup(t, `DELETE FROM workspace WHERE slug = $1`, slug)- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": "前端团队","slug": slug,})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusCreated)var resp WorkspaceResponse- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if resp.IssuePrefix != "HAND" {t.Fatalf("issue_prefix = %q, want %q (derived from the slug, not the name)", resp.IssuePrefix, "HAND")}@@ -1538,25 +1253,17 @@ func TestCreateWorkspace_HonorsExplicitIssuePrefix(t *testing.T) {ctx := context.Background()const slug = "handler-tests-explicit-prefix"_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)- })+ dbfx.Cleanup(t, `DELETE FROM workspace WHERE slug = $1`, slug)- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": "前端团队","slug": slug,"issue_prefix": "fe",})- testHandler.CreateWorkspace(w, req)- if w.Code != http.StatusCreated {- t.Fatalf("CreateWorkspace: expected 201, got %d: %s", w.Code, w.Body.String())- }+ w := testutil.Call(t, testHandler.CreateWorkspace, req).Want(http.StatusCreated)var resp WorkspaceResponse- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("decode response: %v", err)- }+ w.JSON(&resp)if resp.IssuePrefix != "FE" {t.Fatalf("issue_prefix = %q, want %q", resp.IssuePrefix, "FE")}@@ -1583,25 +1290,20 @@ func TestCreateWorkspace_RejectsInvalidIssuePrefix(t *testing.T) {slug := "handler-tests-bad-prefix-" + labelctx := context.Background()_, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)- })+ dbfx.Cleanup(t, `DELETE FROM workspace WHERE slug = $1`, slug)- w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces", map[string]any{"name": "Prefix Validation Probe","slug": slug,"issue_prefix": prefix,})- testHandler.CreateWorkspace(w, req)+ w := testutil.Call(t, testHandler.CreateWorkspace, req)if w.Code != http.StatusBadRequest {t.Fatalf("issue_prefix %q: expected 400, got %d: %s", prefix, w.Code, w.Body.String())}var count int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count); err != nil {- t.Fatalf("count workspaces: %v", err)- }+ dbfx.QueryRow(t, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count)if count != 0 {t.Fatalf("expected no workspace row for a rejected prefix, found %d", count)}@@ -1616,26 +1318,17 @@ func TestUpdateWorkspace_RejectsInvalidIssuePrefix(t *testing.T) {t.Skip("database not available")}- ctx := context.Background()var before string- if err := testPool.QueryRow(ctx, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&before); err != nil {- t.Fatalf("read current prefix: %v", err)- }+ dbfx.QueryRow(t, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&before)- w := httptest.NewRecorder()req := withURLParam(newRequest("PATCH", "/api/workspaces/"+testWorkspaceID, map[string]any{"issue_prefix": "前端团队前端团队前端"}),"id", testWorkspaceID,)- testHandler.UpdateWorkspace(w, req)- if w.Code != http.StatusBadRequest {- t.Fatalf("expected 400 for a non-ASCII issue_prefix, got %d: %s", w.Code, w.Body.String())- }+ testutil.Call(t, testHandler.UpdateWorkspace, req).Want(http.StatusBadRequest)var after string- if err := testPool.QueryRow(ctx, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&after); err != nil {- t.Fatalf("re-read prefix: %v", err)- }+ dbfx.QueryRow(t, `SELECT issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&after)if after != before {t.Fatalf("issue_prefix changed on a rejected update: %q → %q", before, after)}diff --git a/server/internal/testutil/db.go b/server/internal/testutil/db.gonew file mode 100644index 0000000000..fc4aa6b4bc--- /dev/null+++ b/server/internal/testutil/db.go@@ -0,0 +1,357 @@+package testutil++import (+ "context"+ "fmt"+ "sort"+ "strings"++ "github.com/jackc/pgx/v5/pgxpool"+)++// Cols is one fixture row: column name to value. Values are bound as query+// parameters unless they are Raw.+type Cols map[string]any++// Raw is a SQL expression inlined into the statement instead of being bound as+// a parameter, for the defaults a fixture cannot express as a Go value —+// `now() - interval '2 hours'`, or the next issue number in a workspace.+//+// It is inlined verbatim. Never build one out of anything but literals and+// ids the fixture itself produced.+type Raw string++// Fixture inserts rows for one test workspace and removes them again when the+// test that asked for them finishes.+//+// The zero value is not usable; call New. WorkspaceID and UserID are the+// defaults every builder falls back to, so a test that only cares about one+// column names only that column.+type Fixture struct {+ Pool *pgxpool.Pool+ WorkspaceID string+ UserID string+}++// New returns a Fixture bound to the workspace and user a test suite set up in+// its TestMain.+func New(pool *pgxpool.Pool, workspaceID, userID string) *Fixture {+ return &Fixture{Pool: pool, WorkspaceID: workspaceID, UserID: userID}+}++// Insert writes one row into table, registers its deletion with t.Cleanup and+// returns the new row's id.+//+// Cleanup runs in reverse creation order, so a row inserted after the row it+// references is deleted before it and foreign keys hold without the test+// spelling out a teardown order.+func (f *Fixture) Insert(t TB, table string, cols Cols) string {+ t.Helper()++ names, placeholders, args := compile(cols)+ sql := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s) RETURNING id",+ quoteIdent(table), strings.Join(names, ", "), strings.Join(placeholders, ", "))++ var id string+ if err := f.Pool.QueryRow(context.Background(), sql, args...).Scan(&id); err != nil {+ t.Fatalf("setup: insert into %s: %v", table, err)+ }+ f.deleteOnCleanup(t, table, id)+ return id+}++// InsertNoID writes one row into a table that has no id column — a join table,+// typically — and deletes it again with the WHERE clause the caller gives.+// where is appended to `DELETE FROM <table> WHERE `, and its parameters are+// numbered from $1.+func (f *Fixture) InsertNoID(t TB, table string, cols Cols, where string, whereArgs ...any) {+ t.Helper()++ names, placeholders, args := compile(cols)+ sql := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)",+ quoteIdent(table), strings.Join(names, ", "), strings.Join(placeholders, ", "))+ if _, err := f.Pool.Exec(context.Background(), sql, args...); err != nil {+ t.Fatalf("setup: insert into %s: %v", table, err)+ }++ t.Cleanup(func() {+ _, _ = f.Pool.Exec(context.Background(),+ fmt.Sprintf("DELETE FROM %s WHERE %s", quoteIdent(table), where), whereArgs...)+ })+}++// Exec runs a statement and fails the test if it errors.+func (f *Fixture) Exec(t TB, sql string, args ...any) {+ t.Helper()+ if _, err := f.Pool.Exec(context.Background(), sql, args...); err != nil {+ t.Fatalf("exec: %v\nSQL: %s", err, strings.TrimSpace(sql))+ }+}++// Cleanup runs a statement when the test finishes, ignoring its error the way+// teardown always should: a failing test has usually already left the row in a+// state teardown cannot reach, and reporting that on top of the real failure+// buries it.+func (f *Fixture) Cleanup(t TB, sql string, args ...any) {+ t.Helper()+ t.Cleanup(func() {+ _, _ = f.Pool.Exec(context.Background(), sql, args...)+ })+}++// Row is a pending single-row query.+type Row struct {+ f *Fixture+ t TB+ sql string+ args []any+}++// QueryRow prepares a single-row query whose Scan fails the test on error.+func (f *Fixture) QueryRow(t TB, sql string, args ...any) *Row {+ t.Helper()+ return &Row{f: f, t: t, sql: sql, args: args}+}++// Scan reads the row into dest, failing the test if the query errors or+// matched nothing.+func (r *Row) Scan(dest ...any) {+ r.t.Helper()+ if err := r.f.Pool.QueryRow(context.Background(), r.sql, r.args...).Scan(dest...); err != nil {+ r.t.Fatalf("query: %v\nSQL: %s", err, strings.TrimSpace(r.sql))+ }+}++// Count returns the count a `SELECT count(*) ...` query produced.+func (f *Fixture) Count(t TB, sql string, args ...any) int {+ t.Helper()+ var n int+ f.QueryRow(t, sql, args...).Scan(&n)+ return n+}++// ---- typed builders -------------------------------------------------------+//+// Each one fills the columns a row cannot be inserted without, and takes+// optional overrides for the column the test is actually about. Defaults are+// deliberately boring: a test that depends on one must name it.++// User inserts a user row.+func (f *Fixture) User(t TB, name, email string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "user", merge(Cols{+ "name": name,+ "email": email,+ }, over))+}++// Workspace inserts a workspace row.+func (f *Fixture) Workspace(t TB, name, slug string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "workspace", merge(Cols{+ "name": name,+ "slug": slug,+ "description": "",+ "issue_prefix": "",+ }, over))+}++// Member joins a user to a workspace.+func (f *Fixture) Member(t TB, workspaceID, userID, role string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "member", merge(Cols{+ "workspace_id": workspaceID,+ "user_id": userID,+ "role": role,+ }, over))+}++// Issue inserts an issue owned by the fixture's workspace and user.+//+// number is derived from the workspace's existing issues rather than fixed, so+// two issues built by the same test do not collide on the workspace's issue+// numbering.+func (f *Fixture) Issue(t TB, title string, over ...Cols) string {+ t.Helper()+ cols := merge(Cols{+ "workspace_id": f.WorkspaceID,+ "title": title,+ "status": "todo",+ "priority": "none",+ "creator_type": "member",+ "creator_id": f.UserID,+ "position": 0,+ }, over)+ if _, ok := cols["number"]; !ok {+ workspaceID, _ := cols["workspace_id"].(string)+ cols["number"] = Raw(fmt.Sprintf(+ "(SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = %s)",+ quoteLiteral(workspaceID)))+ }+ return f.Insert(t, "issue", cols)+}++// Comment inserts a comment on issueID.+func (f *Fixture) Comment(t TB, issueID, content string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "comment", merge(Cols{+ "issue_id": issueID,+ "workspace_id": f.WorkspaceID,+ "author_type": "member",+ "author_id": f.UserID,+ "content": content,+ "type": "comment",+ }, over))+}++// Runtime inserts an online cloud runtime.+func (f *Fixture) Runtime(t TB, name string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "agent_runtime", merge(Cols{+ "workspace_id": f.WorkspaceID,+ "daemon_id": nil,+ "name": name,+ "runtime_mode": "cloud",+ "provider": "handler_test_runtime",+ "status": "online",+ "device_info": "",+ "metadata": Raw("'{}'::jsonb"),+ "last_seen_at": Raw("now()"),+ "visibility": "private",+ "owner_id": f.UserID,+ }, over))+}++// Agent inserts an agent bound to runtimeID. Pass an empty runtimeID for an+// agent with no runtime.+func (f *Fixture) Agent(t TB, name, runtimeID string, over ...Cols) string {+ t.Helper()+ cols := merge(Cols{+ "workspace_id": f.WorkspaceID,+ "name": name,+ "description": "",+ "runtime_mode": "cloud",+ "runtime_config": Raw("'{}'::jsonb"),+ "visibility": "private",+ "permission_mode": "private",+ "max_concurrent_tasks": 1,+ "owner_id": f.UserID,+ }, over)+ if _, ok := cols["runtime_id"]; !ok && runtimeID != "" {+ cols["runtime_id"] = runtimeID+ }+ return f.Insert(t, "agent", cols)+}++// Task queues a task for agentID.+func (f *Fixture) Task(t TB, agentID string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "agent_task_queue", merge(Cols{+ "agent_id": agentID,+ "status": "queued",+ "priority": 0,+ }, over))+}++// Squad inserts a squad led by leaderID.+func (f *Fixture) Squad(t TB, name, leaderID string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "squad", merge(Cols{+ "workspace_id": f.WorkspaceID,+ "name": name,+ "description": "",+ "leader_id": leaderID,+ "creator_id": f.UserID,+ }, over))+}++// SquadMember adds an agent or member to a squad.+func (f *Fixture) SquadMember(t TB, squadID, memberType, memberID string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "squad_member", merge(Cols{+ "squad_id": squadID,+ "member_type": memberType,+ "member_id": memberID,+ }, over))+}++// Project inserts a project.+func (f *Fixture) Project(t TB, title string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "project", merge(Cols{+ "workspace_id": f.WorkspaceID,+ "title": title,+ "status": "planned",+ "priority": "none",+ }, over))+}++// ChatSession inserts a chat session with agentID.+func (f *Fixture) ChatSession(t TB, agentID string, over ...Cols) string {+ t.Helper()+ return f.Insert(t, "chat_session", merge(Cols{+ "workspace_id": f.WorkspaceID,+ "agent_id": agentID,+ "creator_id": f.UserID,+ "title": "",+ "status": "active",+ }, over))+}++// ---- internals ------------------------------------------------------------++func (f *Fixture) deleteOnCleanup(t TB, table, id string) {+ t.Cleanup(func() {+ _, _ = f.Pool.Exec(context.Background(),+ fmt.Sprintf("DELETE FROM %s WHERE id = $1", quoteIdent(table)), id)+ })+}++// compile turns a column map into column names, value placeholders and bound+// arguments. Columns are sorted so the generated SQL is stable, which keeps a+// failing statement readable and diffable between runs.+func compile(cols Cols) (names []string, placeholders []string, args []any) {+ names = make([]string, 0, len(cols))+ for name := range cols {+ names = append(names, name)+ }+ sort.Strings(names)++ placeholders = make([]string, 0, len(names))+ args = make([]any, 0, len(names))+ for _, name := range names {+ if raw, ok := cols[name].(Raw); ok {+ placeholders = append(placeholders, string(raw))+ continue+ }+ args = append(args, cols[name])+ placeholders = append(placeholders, fmt.Sprintf("$%d", len(args)))+ }+ for i, name := range names {+ names[i] = quoteIdent(name)+ }+ return names, placeholders, args+}++func merge(base Cols, over []Cols) Cols {+ out := make(Cols, len(base))+ for k, v := range base {+ out[k] = v+ }+ for _, o := range over {+ for k, v := range o {+ out[k] = v+ }+ }+ return out+}++// quoteIdent double-quotes an identifier so reserved words — `user`, the+// table, is one — survive as table and column names.+func quoteIdent(s string) string {+ return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`+}++func quoteLiteral(s string) string {+ return `'` + strings.ReplaceAll(s, `'`, `''`) + `'`+}diff --git a/server/internal/testutil/db_test.go b/server/internal/testutil/db_test.gonew file mode 100644index 0000000000..c330303d62--- /dev/null+++ b/server/internal/testutil/db_test.go@@ -0,0 +1,209 @@+package testutil++import (+ "context"+ "fmt"+ "os"+ "testing"++ "github.com/jackc/pgx/v5/pgxpool"+)++var (+ testPool *pgxpool.Pool+ testWorkspaceID string+ testUserID string+)++const (+ fixtureEmail = "[email protected]"+ fixtureSlug = "testutil-fixtures"+)++// TestMain builds the workspace the fixture builders hang off, in the same+// shape internal/handler's TestMain builds it. Without a database the suite+// exits green rather than red: the same contract every other DB-backed package+// here follows, so a laptop without Postgres still runs the rest of the tree.+func TestMain(m *testing.M) {+ ctx := context.Background()+ dbURL := os.Getenv("DATABASE_URL")+ if dbURL == "" {+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"+ }++ pool, err := pgxpool.New(ctx, dbURL)+ if err != nil {+ fmt.Printf("Skipping DB fixture tests: could not connect: %v\n", err)+ os.Exit(m.Run())+ }+ if err := pool.Ping(ctx); err != nil {+ fmt.Printf("Skipping DB fixture tests: database not reachable: %v\n", err)+ pool.Close()+ os.Exit(m.Run())+ }++ if err := seedFixtureWorkspace(ctx, pool); err != nil {+ fmt.Printf("Skipping DB fixture tests: seed failed: %v\n", err)+ pool.Close()+ os.Exit(m.Run())+ }+ testPool = pool++ code := m.Run()+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, fixtureSlug)+ _, _ = pool.Exec(ctx, `DELETE FROM "user" WHERE email = $1`, fixtureEmail)+ pool.Close()+ os.Exit(code)+}++func seedFixtureWorkspace(ctx context.Context, pool *pgxpool.Pool) error {+ if _, err := pool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, fixtureSlug); err != nil {+ return err+ }+ if _, err := pool.Exec(ctx, `DELETE FROM "user" WHERE email = $1`, fixtureEmail); err != nil {+ return err+ }+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,+ "Testutil Fixture User", fixtureEmail).Scan(&testUserID); err != nil {+ return err+ }+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, issue_prefix) VALUES ($1, $2, $3) RETURNING id`,+ "Testutil Fixtures", fixtureSlug, "TUF").Scan(&testWorkspaceID); err != nil {+ return err+ }+ _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,+ testWorkspaceID, testUserID)+ return err+}++func newFixture(t *testing.T) *Fixture {+ t.Helper()+ if testPool == nil {+ t.Skip("database not available")+ }+ return New(testPool, testWorkspaceID, testUserID)+}++// TestBuildersInsertRowsTheSchemaAccepts is the test that makes the shared+// defaults safe to migrate onto: every builder writes a real row against the+// real schema, so a column that gets added NOT NULL without a default breaks+// here — once — instead of in each of the suites that adopted the builder.+func TestBuildersInsertRowsTheSchemaAccepts(t *testing.T) {+ f := newFixture(t)++ runtimeID := f.Runtime(t, "fixture runtime")+ agentID := f.Agent(t, "fixture agent", runtimeID)+ issueID := f.Issue(t, "fixture issue")+ commentID := f.Comment(t, issueID, "fixture comment")+ taskID := f.Task(t, agentID, Cols{"runtime_id": runtimeID, "issue_id": issueID})+ squadID := f.Squad(t, "fixture squad", agentID)+ f.SquadMember(t, squadID, "agent", agentID)+ projectID := f.Project(t, "fixture project")+ sessionID := f.ChatSession(t, agentID)++ for _, tt := range []struct {+ table string+ id string+ }{+ {"agent_runtime", runtimeID},+ {"agent", agentID},+ {"issue", issueID},+ {"comment", commentID},+ {"agent_task_queue", taskID},+ {"squad", squadID},+ {"project", projectID},+ {"chat_session", sessionID},+ } {+ if n := f.Count(t, fmt.Sprintf(`SELECT count(*) FROM %s WHERE id = $1`, tt.table), tt.id); n != 1 {+ t.Fatalf("%s: expected the fixture row to exist, found %d", tt.table, n)+ }+ }+}++// TestInsertedRowsAreGoneAfterTheirTest pins the half of the contract the+// builders exist for. Rows that outlive their test are what forced suites to+// hand-write a DELETE beside every INSERT, and a builder that quietly stopped+// registering cleanup would leak into the next test's counts instead of+// failing.+func TestInsertedRowsAreGoneAfterTheirTest(t *testing.T) {+ f := newFixture(t)++ var issueID string+ t.Run("creates", func(t *testing.T) {+ issueID = f.Issue(t, "disappearing issue")+ if n := f.Count(t, `SELECT count(*) FROM issue WHERE id = $1`, issueID); n != 1 {+ t.Fatalf("expected the issue to exist inside its test, found %d", n)+ }+ })++ if n := f.Count(t, `SELECT count(*) FROM issue WHERE id = $1`, issueID); n != 0 {+ t.Fatalf("issue survived the test that created it, found %d", n)+ }+}++// TestOverridesReplaceDefaults keeps the builders honest about which value+// wins: a test that names a column is describing the thing it asserts on, so a+// default that quietly survived would make the assertion test the fixture+// rather than the code.+func TestOverridesReplaceDefaults(t *testing.T) {+ f := newFixture(t)++ issueID := f.Issue(t, "overridden", Cols{"status": "in_progress", "priority": "urgent"})+ var status, priority string+ f.QueryRow(t, `SELECT status, priority FROM issue WHERE id = $1`, issueID).Scan(&status, &priority)+ if status != "in_progress" || priority != "urgent" {+ t.Fatalf("status/priority = %q/%q, want in_progress/urgent", status, priority)+ }+}++// TestRawValuesAreInlinedAsSQL covers the escape hatch the timing fixtures+// need: `dispatched_at` in the past cannot be written as a bound Go value+// without the test pinning a clock the query does not read.+func TestRawValuesAreInlinedAsSQL(t *testing.T) {+ f := newFixture(t)++ runtimeID := f.Runtime(t, "raw runtime")+ agentID := f.Agent(t, "raw agent", runtimeID)+ taskID := f.Task(t, agentID, Cols{+ "runtime_id": runtimeID,+ "status": "dispatched",+ "dispatched_at": Raw("now() - interval '2 hours'"),+ })++ var ageSeconds float64+ f.QueryRow(t, `SELECT EXTRACT(EPOCH FROM (now() - dispatched_at)) FROM agent_task_queue WHERE id = $1`, taskID).+ Scan(&ageSeconds)+ if ageSeconds < 7100 {+ t.Fatalf("dispatched_at is %.0fs old, want ~7200s — the Raw expression was bound as a value", ageSeconds)+ }+}++// TestIssueNumbersDoNotCollide covers the one default that cannot be a+// constant: issue.number is unique per workspace, so two issues built by one+// test have to negotiate it.+func TestIssueNumbersDoNotCollide(t *testing.T) {+ f := newFixture(t)++ first := f.Issue(t, "first")+ second := f.Issue(t, "second")++ var a, b int+ f.QueryRow(t, `SELECT number FROM issue WHERE id = $1`, first).Scan(&a)+ f.QueryRow(t, `SELECT number FROM issue WHERE id = $1`, second).Scan(&b)+ if a == b {+ t.Fatalf("both issues took number %d", a)+ }+}++// TestUserTableIsQuoted guards the identifier quoting: `user` is reserved, and+// an unquoted INSERT INTO user is a syntax error rather than a wrong row.+func TestUserTableIsQuoted(t *testing.T) {+ f := newFixture(t)++ userID := f.User(t, "Quoted Name", "[email protected]")+ var name string+ f.QueryRow(t, `SELECT name FROM "user" WHERE id = $1`, userID).Scan(&name)+ if name != "Quoted Name" {+ t.Fatalf("name = %q, want Quoted Name", name)+ }+}diff --git a/server/internal/testutil/doc.go b/server/internal/testutil/doc.gonew file mode 100644index 0000000000..0d40196b21--- /dev/null+++ b/server/internal/testutil/doc.go@@ -0,0 +1,27 @@+// Package testutil holds the fixtures the server's DB-backed tests build+// their scenarios from: row builders that insert a fixture row and delete it+// again when the test ends, and HTTP helpers that run one handler and assert+// on what it wrote.+//+// It exists because the cost of changing shared behaviour was scaling with+// the number of test files. Before this package `internal/handler` alone held+// ~1000 hand-written `INSERT INTO ... RETURNING id` blocks, ~1150+// `DELETE FROM` cleanups and ~1200 copies of the+// recorder/call/status/decode quartet, each one an independent statement of+// the same contract. Changing an insert's column set, or the shape of a+// failure message, meant editing every copy.+//+// Two rules keep it that way:+//+// - New DB-backed tests build their rows through a Fixture and drive+// handlers through Call. Do not open-code an INSERT + t.Cleanup pair or a+// recorder/status/decode quartet in a new test.+// - Helpers here stay behaviour-free. They insert rows, run handlers and+// report mismatches; they never assert a product rule on the test's+// behalf. A helper that knows what a correct response looks like moves+// the assertion out of the test that is supposed to make it.+//+// The package imports "testing" and must only be imported from _test files.+// Importing it from production code links the testing flag set into the+// binary.+package testutildiff --git a/server/internal/testutil/http.go b/server/internal/testutil/http.gonew file mode 100644index 0000000000..efcae5ef66--- /dev/null+++ b/server/internal/testutil/http.go@@ -0,0 +1,157 @@+package testutil++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"++ "github.com/go-chi/chi/v5"+)++// JSONRequest builds a request whose body is body encoded as JSON.+//+// body is passed through unencoded when it is already a string, []byte or+// io.Reader, so a test can post a malformed payload — the malformed-response+// tests the endpoint checklist asks for would otherwise have to bypass this+// helper and rebuild the headers by hand.+func JSONRequest(method, path string, body any) *http.Request {+ var reader io.Reader+ switch v := body.(type) {+ case nil:+ reader = &bytes.Buffer{}+ case string:+ reader = strings.NewReader(v)+ case []byte:+ reader = bytes.NewReader(v)+ case io.Reader:+ reader = v+ default:+ var buf bytes.Buffer+ if err := json.NewEncoder(&buf).Encode(v); err != nil {+ // Encoding a literal built inside a test can only fail on a value+ // no test means to send (a channel, a NaN); panicking here reports+ // it at the call site instead of as a confusing empty body later.+ panic(fmt.Sprintf("testutil: encode request body for %s %s: %v", method, path, err))+ }+ reader = &buf+ }+ req := httptest.NewRequest(method, path, reader)+ req.Header.Set("Content-Type", "application/json")+ return req+}++// WithHeaders sets alternating key/value header pairs and returns req.+func WithHeaders(req *http.Request, kv ...string) *http.Request {+ if len(kv)%2 != 0 {+ panic("testutil: WithHeaders needs an even number of key/value arguments")+ }+ for i := 0; i < len(kv); i += 2 {+ req.Header.Set(kv[i], kv[i+1])+ }+ return req+}++// WithURLParams attaches alternating chi URL param key/value pairs, which is+// how a handler called directly — without its router — reads path segments.+func WithURLParams(req *http.Request, kv ...string) *http.Request {+ if len(kv)%2 != 0 {+ panic("testutil: WithURLParams needs an even number of key/value arguments")+ }+ rctx := chi.NewRouteContext()+ for i := 0; i < len(kv); i += 2 {+ rctx.URLParams.Add(kv[i], kv[i+1])+ }+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+}++// TB is the part of *testing.T these helpers use. Taking the interface rather+// than the concrete type is what lets this package assert on its own failure+// messages — the messages are the reason a shared assertion is worth having,+// so they need a test of their own.+type TB interface {+ Helper()+ Fatalf(format string, args ...any)+ Cleanup(func())+}++// Response is the recorded result of one handler call. Its assertions are+// fatal: a test that misread the status has already misread everything it+// would decode out of the body.+type Response struct {+ *httptest.ResponseRecorder++ t TB+ req *http.Request+}++// Call runs h against req and records what it wrote.+func Call(t TB, h http.HandlerFunc, req *http.Request) *Response {+ t.Helper()+ rec := httptest.NewRecorder()+ h(rec, req)+ return &Response{ResponseRecorder: rec, t: t, req: req}+}++// Want fails the test unless the handler wrote status code want. The failure+// message carries the request line and the response body, because the body is+// where a handler says which of its several rejections fired.+func (r *Response) Want(want int) *Response {+ r.t.Helper()+ if r.Code != want {+ r.t.Fatalf("%s %s: expected %d, got %d: %s",+ r.req.Method, r.req.URL.RequestURI(), want, r.Code, r.Body.String())+ }+ return r+}++// WantOneOf fails the test unless the status is one of want. Use it only where+// more than one status is genuinely correct; asserting a set to dodge a flake+// hides the flake.+func (r *Response) WantOneOf(want ...int) *Response {+ r.t.Helper()+ for _, code := range want {+ if r.Code == code {+ return r+ }+ }+ r.t.Fatalf("%s %s: expected one of %v, got %d: %s",+ r.req.Method, r.req.URL.RequestURI(), want, r.Code, r.Body.String())+ return r+}++// JSON decodes the response body into dest.+func (r *Response) JSON(dest any) *Response {+ r.t.Helper()+ if err := json.Unmarshal(r.Body.Bytes(), dest); err != nil {+ r.t.Fatalf("%s %s: decode response: %v: %s",+ r.req.Method, r.req.URL.RequestURI(), err, r.Body.String())+ }+ return r+}++// Map decodes the body into a generic object, for assertions that only touch+// one or two fields and do not earn a named struct.+func (r *Response) Map() map[string]any {+ r.t.Helper()+ out := map[string]any{}+ r.JSON(&out)+ return out+}++// Text returns the raw response body.+func (r *Response) Text() string { return r.Body.String() }++// Decode runs the handler, asserts the status and decodes the body in one+// expression, for the common case where the caller wants a typed payload and+// has no other use for the response.+func Decode[T any](t TB, h http.HandlerFunc, req *http.Request, want int) T {+ t.Helper()+ var out T+ Call(t, h, req).Want(want).JSON(&out)+ return out+}diff --git a/server/internal/testutil/http_test.go b/server/internal/testutil/http_test.gonew file mode 100644index 0000000000..f8662898af--- /dev/null+++ b/server/internal/testutil/http_test.go@@ -0,0 +1,157 @@+package testutil++import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "testing"++ "github.com/go-chi/chi/v5"+)++func TestJSONRequestEncodesValuesAndPassesRawBodiesThrough(t *testing.T) {+ t.Parallel()++ // A struct is encoded. A string is not: the malformed-payload tests the+ // endpoint checklist asks for send bodies that are not valid JSON, and+ // encoding them would turn every one of those into a well-formed string+ // literal that the handler happily parses.+ tests := []struct {+ name string+ body any+ want string+ }{+ {"map", map[string]any{"a": 1}, `{"a":1}`},+ {"string passthrough", `{"broken":`, `{"broken":`},+ {"bytes passthrough", []byte("not json"), "not json"},+ {"reader passthrough", strings.NewReader("streamed"), "streamed"},+ {"nil is empty", nil, ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := JSONRequest("POST", "/api/thing", tt.body)+ got, err := io.ReadAll(req.Body)+ if err != nil {+ t.Fatalf("read body: %v", err)+ }+ if strings.TrimSpace(string(got)) != tt.want {+ t.Fatalf("body = %q, want %q", got, tt.want)+ }+ if ct := req.Header.Get("Content-Type"); ct != "application/json" {+ t.Fatalf("Content-Type = %q, want application/json", ct)+ }+ })+ }+}++func TestWithURLParamsFeedsChiRouteParams(t *testing.T) {+ t.Parallel()++ req := WithURLParams(JSONRequest("GET", "/api/issues/x", nil), "issueId", "abc", "commentId", "def")+ if got := chi.URLParam(req, "issueId"); got != "abc" {+ t.Fatalf("issueId = %q, want abc", got)+ }+ if got := chi.URLParam(req, "commentId"); got != "def" {+ t.Fatalf("commentId = %q, want def", got)+ }+}++func TestWithHeadersSetsPairs(t *testing.T) {+ t.Parallel()++ req := WithHeaders(JSONRequest("GET", "/api/me", nil), "X-User-ID", "u1", "X-Workspace-ID", "w1")+ if got := req.Header.Get("X-User-ID"); got != "u1" {+ t.Fatalf("X-User-ID = %q, want u1", got)+ }+ if got := req.Header.Get("X-Workspace-ID"); got != "w1" {+ t.Fatalf("X-Workspace-ID = %q, want w1", got)+ }+}++func TestCallRecordsStatusAndDecodesBody(t *testing.T) {+ t.Parallel()++ h := func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "issue-1"})+ }++ var out struct {+ ID string `json:"id"`+ }+ Call(t, h, JSONRequest("POST", "/api/issues", nil)).Want(http.StatusCreated).JSON(&out)+ if out.ID != "issue-1" {+ t.Fatalf("id = %q, want issue-1", out.ID)+ }++ if got := Decode[struct {+ ID string `json:"id"`+ }](t, h, JSONRequest("POST", "/api/issues", nil), http.StatusCreated); got.ID != "issue-1" {+ t.Fatalf("Decode id = %q, want issue-1", got.ID)+ }+}++// TestWantReportsTheBodyOnMismatch pins the one thing the shared assertion has+// to keep doing: a handler that rejects a request says which rejection fired+// in the body, and a helper that swallowed it would make every 400 look alike.+func TestWantReportsTheBodyOnMismatch(t *testing.T) {+ t.Parallel()++ h := func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusBadRequest)+ _, _ = w.Write([]byte(`{"error":"slug is reserved"}`))+ }++ spy := &spyTB{}+ spy.capture(func() {+ Call(spy, h, JSONRequest("POST", "/api/workspaces", nil)).Want(http.StatusCreated)+ })++ if !spy.failed {+ t.Fatal("Want did not fail on a status mismatch")+ }+ for _, want := range []string{"POST", "/api/workspaces", "expected 201", "got 400", "slug is reserved"} {+ if !strings.Contains(spy.message, want) {+ t.Fatalf("failure message %q missing %q", spy.message, want)+ }+ }+}++// spyTB stands in for *testing.T so a test can assert on what a failing helper+// reports. Fatalf panics because the real one ends the goroutine, and a helper+// that kept running past its own Fatalf would read as passing here.+type spyTB struct {+ failed bool+ message string+}++type spyFatal struct{}++func (s *spyTB) Helper() {}+func (s *spyTB) Cleanup(func()) {}++func (s *spyTB) Fatalf(format string, args ...any) {+ s.failed = true+ s.message = fmt.Sprintf(format, args...)+ panic(spyFatal{})+}++func (s *spyTB) capture(fn func()) {+ defer func() {+ if r := recover(); r != nil {+ if _, ok := r.(spyFatal); !ok {+ panic(r)+ }+ }+ }()+ fn()+}++func TestWantOneOfAcceptsAnyListedStatus(t *testing.T) {+ t.Parallel()++ h := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusConflict) }+ Call(t, h, JSONRequest("POST", "/api/tasks", nil)).WantOneOf(http.StatusOK, http.StatusConflict)+}