Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(my-issues): cover squad assignees via involves_user_id (MUL-2364) (#2801)
Naiyuan Qing3c510c31edbb
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 927aa8c752..dfb195a66f 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -259,6 +259,47 @@ describe("ApiClient", () => {});});+ describe("involves_user_id wiring", () => {+ // The my-issues "My Agents / Squads" tab passes involves_user_id so the+ // server expands it to "user + agents they own + squads they relate to"+ // in a single UNION query. These tests pin the client wiring so a typo+ // can't silently downgrade the tab to fetching everything.+ it("listIssues forwards involves_user_id into the querystring", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ issues: [], total: 0 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ await client.listIssues({ involves_user_id: "user-1" });++ const [url] = fetchMock.mock.calls[0]!;+ expect(url).toContain("involves_user_id=user-1");+ });++ it("listGroupedIssues forwards involves_user_id into the querystring", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ groups: [] }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ await client.listGroupedIssues({+ group_by: "assignee",+ involves_user_id: "user-1",+ });++ const [url] = fetchMock.mock.calls[0]!;+ expect(url).toContain("involves_user_id=user-1");+ });+ });+describe("chat attachment wiring", () => {it("uploadFile includes chat_session_id in the FormData body", async () => {const fetchMock = vi.fn().mockResolvedValue(diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex bab49472d7..620507f596 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -481,6 +481,7 @@ export class ApiClient {if (params?.creator_id) search.set("creator_id", params.creator_id);if (params?.project_id) search.set("project_id", params.project_id);if (params?.open_only) search.set("open_only", "true");+ if (params?.involves_user_id) search.set("involves_user_id", params.involves_user_id);const path = `/api/issues?${search}`;const raw = await this.fetch<unknown>(path);return parseWithFallback(raw, ListIssuesResponseSchema, EMPTY_LIST_ISSUES_RESPONSE, {@@ -512,6 +513,7 @@ export class ApiClient {if (params.label_ids?.length) search.set("label_ids", params.label_ids.join(","));if (params.group_assignee_type) search.set("group_assignee_type", params.group_assignee_type);if (params.group_assignee_id) search.set("group_assignee_id", params.group_assignee_id);+ if (params.involves_user_id) search.set("involves_user_id", params.involves_user_id);const raw = await this.fetch<unknown>(`/api/issues/grouped?${search}`);return parseWithFallback(raw, GroupedIssuesResponseSchema, EMPTY_GROUPED_ISSUES_RESPONSE, {endpoint: "GET /api/issues/grouped",diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 12de9387f1..684e850da7 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -55,7 +55,7 @@ export const issueKeys = {export type MyIssuesFilter = Pick<ListIssuesParams,- "assignee_id" | "assignee_ids" | "creator_id" | "project_id"+ "assignee_id" | "assignee_ids" | "creator_id" | "project_id" | "involves_user_id">;export type AssigneeGroupedIssuesFilter = Omit<diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 698467defa..a3cd50d292 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -46,6 +46,14 @@ export interface ListIssuesParams {creator_id?: string;project_id?: string;open_only?: boolean;+ /**+ * Server-side "involves user" expansion: matches issues assigned directly+ * to this user, to an agent they own, or to a squad where they are a+ * member, the leader (via canonical squad.leader_id), or the owner of an+ * agent member. Backed by a single UNION subquery in issue.sql so the+ * client doesn't have to fan out into multiple requests.+ */+ involves_user_id?: string;}export interface IssueActorRef {@@ -73,6 +81,8 @@ export interface ListGroupedIssuesParams {label_ids?: string[];group_assignee_type?: IssueAssigneeType | "none";group_assignee_id?: string;+ /** See ListIssuesParams.involves_user_id — same semantics in the grouped path. */+ involves_user_id?: string;}/** Raw backend response shape for `GET /api/issues`. */diff --git a/packages/views/locales/en/my-issues.json b/packages/views/locales/en/my-issues.jsonindex f193d79336..05609a1a81 100644--- a/packages/views/locales/en/my-issues.json+++ b/packages/views/locales/en/my-issues.json@@ -11,8 +11,8 @@"assigned_description": "Issues assigned to me","created_label": "Created","created_description": "Issues I created",- "agents_label": "My Agents",- "agents_description": "Issues assigned to my agents"+ "agents_label": "My Agents / Squads",+ "agents_description": "Issues assigned to me, my agents, or squads I'm part of or lead"},"filter_button": "Filter","filter_status": "Status",diff --git a/packages/views/locales/zh-Hans/my-issues.json b/packages/views/locales/zh-Hans/my-issues.jsonindex 65a57ae4ee..8c87a1b8bc 100644--- a/packages/views/locales/zh-Hans/my-issues.json+++ b/packages/views/locales/zh-Hans/my-issues.json@@ -11,8 +11,8 @@"assigned_description": "分配给我的 issue","created_label": "我创建的","created_description": "我创建的 issue",- "agents_label": "我的智能体",- "agents_description": "分配给我的智能体的 issue"+ "agents_label": "我的智能体 / 小队",+ "agents_description": "分配给我、我的智能体,或我所在 / 我领导的小队的 issue"},"filter_button": "筛选","filter_status": "状态",diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsxindex 9a3dc6426b..457ce33b34 100644--- a/packages/views/my-issues/components/my-issues-page.tsx+++ b/packages/views/my-issues/components/my-issues-page.tsx@@ -10,7 +10,6 @@ import { useAuthStore } from "@multica/core/auth";import { useCurrentWorkspace } from "@multica/core/paths";import { WorkspaceAvatar } from "../../workspace/workspace-avatar";import { useQuery } from "@tanstack/react-query";-import { agentListOptions } from "@multica/core/workspace/queries";import { filterIssues } from "../../issues/utils/filter";import { BOARD_STATUSES } from "@multica/core/issues/config";import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";@@ -32,7 +31,6 @@ export function MyIssuesPage() {const user = useAuthStore((s) => s.user);const workspace = useCurrentWorkspace();const wsId = useWorkspaceId();- const { data: agents = [] } = useQuery(agentListOptions(wsId));const viewMode = useStore(myIssuesViewStore, (s) => s.viewMode);const statusFilters = useStore(myIssuesViewStore, (s) => s.statusFilters);@@ -48,15 +46,11 @@ export function MyIssuesPage() {useIssueSelectionStore.getState().clear();}, [viewMode, scope]);- // Build server-side filter based on scope- const myAgentIds = useMemo(() => {- if (!user) return [] as string[];- return agents- .filter((a) => a.owner_id === user.id)- .map((a) => a.id)- .sort();- }, [agents, user]);-+ // Build server-side filter based on scope. The "agents" scope is the+ // "My Agents / Squads" tab — it uses involves_user_id so the server expands+ // it to "me + agents I own + squads I'm related to" in a single UNION+ // query. See packages/core/types/api.ts for the full semantics and+ // server/pkg/db/queries/issue.sql for the SQL.const filter: MyIssuesFilter = useMemo(() => {if (!user) return {};switch (scope) {@@ -65,11 +59,11 @@ export function MyIssuesPage() {case "created":return { creator_id: user.id };case "agents":- return { assignee_ids: myAgentIds };+ return { involves_user_id: user.id };default:return { assignee_id: user.id };}- }, [scope, user, myAgentIds]);+ }, [scope, user]);const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(() => ({diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 0dec18e5bc..3b19b1538d 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -741,16 +741,30 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {}projectFilter = id}+ // involves_user_id is the user UUID (matches user.id, the same actor id+ // member rows expose externally — see onboarding.go:402, squad.go:571).+ // Server-side it expands to (assignee=user OR assignee=agent-owned-by-user+ // OR assignee=squad-where-user-is-leader-member-or-agent-owner) via the+ // UNION subquery in issue.sql.+ var involvesUserID pgtype.UUID+ if raw := r.URL.Query().Get("involves_user_id"); raw != "" {+ id, ok := parseUUIDOrBadRequest(w, raw, "involves_user_id")+ if !ok {+ return+ }+ involvesUserID = id+ }// open_only=true returns all non-done/cancelled issues (no limit).if r.URL.Query().Get("open_only") == "true" {issues, err := h.Queries.ListOpenIssues(ctx, db.ListOpenIssuesParams{- WorkspaceID: wsUUID,- Priority: priorityFilter,- AssigneeID: assigneeFilter,- AssigneeIds: assigneeIdsFilter,- CreatorID: creatorFilter,- ProjectID: projectFilter,+ WorkspaceID: wsUUID,+ Priority: priorityFilter,+ AssigneeID: assigneeFilter,+ AssigneeIds: assigneeIdsFilter,+ CreatorID: creatorFilter,+ ProjectID: projectFilter,+ InvolvesUserID: involvesUserID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -799,15 +813,16 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {}issues, err := h.Queries.ListIssues(ctx, db.ListIssuesParams{- WorkspaceID: wsUUID,- Limit: int32(limit),- Offset: int32(offset),- Status: statusFilter,- Priority: priorityFilter,- AssigneeID: assigneeFilter,- AssigneeIds: assigneeIdsFilter,- CreatorID: creatorFilter,- ProjectID: projectFilter,+ WorkspaceID: wsUUID,+ Limit: int32(limit),+ Offset: int32(offset),+ Status: statusFilter,+ Priority: priorityFilter,+ AssigneeID: assigneeFilter,+ AssigneeIds: assigneeIdsFilter,+ CreatorID: creatorFilter,+ ProjectID: projectFilter,+ InvolvesUserID: involvesUserID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -816,13 +831,14 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {// Get the true total count for pagination awareness.total, err := h.Queries.CountIssues(ctx, db.CountIssuesParams{- WorkspaceID: wsUUID,- Status: statusFilter,- Priority: priorityFilter,- AssigneeID: assigneeFilter,- AssigneeIds: assigneeIdsFilter,- CreatorID: creatorFilter,- ProjectID: projectFilter,+ WorkspaceID: wsUUID,+ Status: statusFilter,+ Priority: priorityFilter,+ AssigneeID: assigneeFilter,+ AssigneeIds: assigneeIdsFilter,+ CreatorID: creatorFilter,+ ProjectID: projectFilter,+ InvolvesUserID: involvesUserID,})if err != nil {total = int64(len(issues))@@ -1015,6 +1031,51 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {}where = append(where, fmt.Sprintf("i.project_id = %s::uuid", addArg(id)))}+ // Mirror the involves_user_id semantics from ListIssues — see issue.sql+ // for the rationale. The squad subquery has three independent branches+ // (human-member / canonical-leader / agent-member); leader stays separate+ // because squad_member's leader copy row is best-effort and may be missing.+ // All subqueries are workspace-scoped via $1 (the outer i.workspace_id arg)+ // to keep the cross-workspace guarantee identical to the outer filter.+ if raw := r.URL.Query().Get("involves_user_id"); raw != "" {+ userID, ok := parseUUIDOrBadRequest(w, raw, "involves_user_id")+ if !ok {+ return+ }+ uidRef := addArg(userID)+ where = append(where, fmt.Sprintf(`(+ (i.assignee_type = 'member' AND i.assignee_id = %[1]s::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = %[1]s::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = %[1]s::uuid+ UNION+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = %[1]s::uuid+ UNION+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = %[1]s::uuid+ ))+ )`, uidRef))+ }assigneeFilters, ok := parseActorFilterList(w, r.URL.Query().Get("assignee_filters"), "assignee_filters")if !ok {diff --git a/server/internal/handler/issue_involves_test.go b/server/internal/handler/issue_involves_test.gonew file mode 100644index 0000000000..02f215db24--- /dev/null+++ b/server/internal/handler/issue_involves_test.go@@ -0,0 +1,520 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++// involvesFixture seeds the rows every involves-user-id test variant needs:+// a second user, their owned agent, plus an issue counter helper for stable+// numbering. Tests scope further insertions (squads, members, more issues) on+// top of these baseline rows.+type involvesFixture struct {+ userID string+ agentID string+ otherWsID string+}++func setupInvolvesFixture(t *testing.T) *involvesFixture {+ t.Helper()+ ctx := context.Background()+ suffix := time.Now().UnixNano()++ var userID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id+ `, "Involves Test User", fmt.Sprintf("involves-%[email protected]", suffix)).Scan(&userID); err != nil {+ t.Fatalf("create user: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')+ `, testWorkspaceID, userID); err != nil {+ t.Fatalf("add member: %v", err)+ }++ // Agent owned by the involves user, in the test workspace, on the seeded runtime.+ 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, 'workspace', 1, $4)+ RETURNING id+ `, testWorkspaceID, fmt.Sprintf("Involves Agent %d", suffix), testRuntimeID, userID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)+ })++ // Sibling workspace + runtime so we can prove workspace scoping with+ // agents that share an owner across workspaces.+ var otherWsID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ($1, $2, '', 'OTH')+ RETURNING id+ `, fmt.Sprintf("Involves Other WS %d", suffix), fmt.Sprintf("involves-other-%d", suffix)).Scan(&otherWsID); err != nil {+ t.Fatalf("create other workspace: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, otherWsID)+ })++ return &involvesFixture{userID: userID, agentID: agentID, otherWsID: otherWsID}+}++// nextIssueNumber claims the next issue number in the test workspace using+// the same row update the production CreateIssue path runs, so direct INSERTs+// from these tests don't collide with anything else seeded in the suite.+func nextIssueNumber(t *testing.T, ctx context.Context, workspaceID string) int32 {+ t.Helper()+ var n int32+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(+ issue_counter,+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)+ ) + 1+ WHERE id = $1+ RETURNING issue_counter+ `, workspaceID).Scan(&n); err != nil {+ t.Fatalf("next issue number: %v", err)+ }+ return n+}++func insertIssueTo(t *testing.T, ctx context.Context, workspaceID, title, assigneeType, assigneeID string) string {+ t.Helper()+ number := nextIssueNumber(t, ctx, workspaceID)+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, description, status, priority,+ assignee_type, assignee_id, creator_type, creator_id,+ position, number+ )+ VALUES ($1, $2, NULL, 'todo', 'none', $3, $4, 'member', $5, 0, $6)+ RETURNING id+ `, workspaceID, title, assigneeType, assigneeID, testUserID, number).Scan(&id); err != nil {+ t.Fatalf("insert issue %q: %v", title, err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, id)+ })+ return id+}++func insertSquad(t *testing.T, ctx context.Context, workspaceID, name, leaderID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)+ VALUES ($1, $2, '', $3, $4)+ RETURNING id+ `, workspaceID, name, leaderID, testUserID).Scan(&id); err != nil {+ t.Fatalf("insert squad: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, id)+ })+ return id+}++func insertSquadMember(t *testing.T, ctx context.Context, squadID, memberType, memberID string) {+ t.Helper()+ if _, err := testPool.Exec(ctx, `+ INSERT INTO squad_member (squad_id, member_type, member_id, role)+ VALUES ($1, $2, $3, '')+ `, squadID, memberType, memberID); err != nil {+ t.Fatalf("insert squad_member: %v", err)+ }+}++func listIssuesInvolves(t *testing.T, involvesUserID string) []IssueResponse {+ t.Helper()+ // limit=1000 is way above anything any of these tests seed; we just want+ // to avoid relying on the 100-row default page size hiding rows the+ // assertion depends on.+ path := fmt.Sprintf(+ "/api/issues?workspace_id=%s&involves_user_id=%s&limit=1000",+ testWorkspaceID, involvesUserID,+ )+ w := httptest.NewRecorder()+ testHandler.ListIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListIssues: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Issues []IssueResponse `json:"issues"`+ Total int64 `json:"total"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp.Issues+}++func containsIssueID(issues []IssueResponse, id string) bool {+ for _, i := range issues {+ if i.ID == id {+ return true+ }+ }+ return false+}++func TestListIssues_InvolvesUserID_MatchesSquadMember(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ // Seeded test agent leads the squad; the involves user joins as a human member.+ var leaderAgentID string+ if err := testPool.QueryRow(ctx, `+ SELECT id FROM agent WHERE workspace_id = $1 AND id <> $2 ORDER BY created_at ASC LIMIT 1+ `, testWorkspaceID, fix.agentID).Scan(&leaderAgentID); err != nil {+ t.Fatalf("load seeded leader agent: %v", err)+ }+ squadID := insertSquad(t, ctx, testWorkspaceID, fmt.Sprintf("Squad Member %d", time.Now().UnixNano()), leaderAgentID)+ insertSquadMember(t, ctx, squadID, "member", fix.userID)++ issueID := insertIssueTo(t, ctx, testWorkspaceID, "involves member squad", "squad", squadID)+ if got := listIssuesInvolves(t, fix.userID); !containsIssueID(got, issueID) {+ t.Fatalf("expected involves match via squad_member.member, got %d issues", len(got))+ }+}++// Pins the v3 semantics that the leader relation is sourced from canonical+// squad.leader_id, not from squad_member. Inserts a squad whose leader is the+// involves user's agent and deliberately skips the squad_member copy row that+// the production handler best-effort-creates (see squad.go:177-188).+func TestListIssues_InvolvesUserID_MatchesLeaderViaCanonicalRelation(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ squadID := insertSquad(t, ctx, testWorkspaceID, fmt.Sprintf("Canonical Leader %d", time.Now().UnixNano()), fix.agentID)+ // Deliberately no squad_member row for the leader.+ var sanity int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM squad_member+ WHERE squad_id = $1 AND member_type = 'agent' AND member_id = $2+ `, squadID, fix.agentID).Scan(&sanity); err != nil {+ t.Fatalf("sanity check: %v", err)+ }+ if sanity != 0 {+ t.Fatalf("test invariant broken: expected no leader squad_member row, found %d", sanity)+ }++ issueID := insertIssueTo(t, ctx, testWorkspaceID, "involves canonical leader", "squad", squadID)+ if got := listIssuesInvolves(t, fix.userID); !containsIssueID(got, issueID) {+ t.Fatalf("expected involves match via canonical squad.leader_id even without squad_member copy row, got %d issues", len(got))+ }+}++func TestListIssues_InvolvesUserID_MatchesSquadAgentMember(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ // Seeded test agent is the leader; user's own agent is added as a plain member.+ var leaderAgentID string+ if err := testPool.QueryRow(ctx, `+ SELECT id FROM agent WHERE workspace_id = $1 AND id <> $2 ORDER BY created_at ASC LIMIT 1+ `, testWorkspaceID, fix.agentID).Scan(&leaderAgentID); err != nil {+ t.Fatalf("load seeded leader agent: %v", err)+ }+ squadID := insertSquad(t, ctx, testWorkspaceID, fmt.Sprintf("Agent Member %d", time.Now().UnixNano()), leaderAgentID)+ insertSquadMember(t, ctx, squadID, "agent", fix.agentID)++ issueID := insertIssueTo(t, ctx, testWorkspaceID, "involves agent member", "squad", squadID)+ if got := listIssuesInvolves(t, fix.userID); !containsIssueID(got, issueID) {+ t.Fatalf("expected involves match via squad_member.agent, got %d issues", len(got))+ }+}++func TestListIssues_InvolvesUserID_MatchesOwnedAgentAssignee(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ issueID := insertIssueTo(t, ctx, testWorkspaceID, "involves agent direct", "agent", fix.agentID)+ if got := listIssuesInvolves(t, fix.userID); !containsIssueID(got, issueID) {+ t.Fatalf("expected involves match via owned agent assignee, got %d issues", len(got))+ }+}++func TestListIssues_InvolvesUserID_MatchesDirectMemberAssignee(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ issueID := insertIssueTo(t, ctx, testWorkspaceID, "involves member direct", "member", fix.userID)+ if got := listIssuesInvolves(t, fix.userID); !containsIssueID(got, issueID) {+ t.Fatalf("expected involves match via direct member assignee, got %d issues", len(got))+ }+}++// Pins workspace scoping on the UNION's agent branch (issue.sql:18). The+// issue itself sits in testWorkspaceID so the outer `i.workspace_id = $1`+// can't mask a missing `a.workspace_id = $1`; assignee_id is polymorphic and+// has no FK (server/migrations/001_init.up.sql:61), so DB-level it's fine to+// point at a foreign-workspace agent.+func TestListIssues_InvolvesUserID_ExcludesOtherWorkspaceAgent(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ var otherRuntimeID, otherAgentID 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, 'Other Runtime', 'cloud', 'other', 'online', '', '{}'::jsonb, now())+ RETURNING id+ `, fix.otherWsID).Scan(&otherRuntimeID); err != nil {+ t.Fatalf("create other runtime: %v", err)+ }+ 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, 'Other WS Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id+ `, fix.otherWsID, otherRuntimeID, fix.userID).Scan(&otherAgentID); err != nil {+ t.Fatalf("create other-ws agent: %v", err)+ }++ leakID := insertIssueTo(t, ctx, testWorkspaceID, "current-ws issue, foreign agent assignee", "agent", otherAgentID)+ for _, issue := range listIssuesInvolves(t, fix.userID) {+ if issue.ID == leakID {+ t.Fatalf("involves match leaked: agent UNION branch did not enforce workspace scoping")+ }+ }+}++// Pins workspace scoping on the UNION's canonical-leader branch+// (issue.sql:36-37). Current-workspace issue points at a foreign squad whose+// leader is a foreign-workspace agent owned by the involves user; only+// `s.workspace_id = $1` / `a.workspace_id = $1` can drop it.+func TestListIssues_InvolvesUserID_ExcludesOtherWorkspaceLeader(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ var otherRuntimeID, otherAgentID 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, 'Other Runtime Leader', 'cloud', 'other2', 'online', '', '{}'::jsonb, now())+ RETURNING id+ `, fix.otherWsID).Scan(&otherRuntimeID); err != nil {+ t.Fatalf("create other runtime: %v", err)+ }+ 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, 'Other WS Leader Agent', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id+ `, fix.otherWsID, otherRuntimeID, fix.userID).Scan(&otherAgentID); err != nil {+ t.Fatalf("create other-ws leader agent: %v", err)+ }++ otherSquadID := insertSquad(t, ctx, fix.otherWsID, "Other WS Squad", otherAgentID)+ leakID := insertIssueTo(t, ctx, testWorkspaceID, "current-ws issue, foreign squad assignee (leader)", "squad", otherSquadID)++ for _, issue := range listIssuesInvolves(t, fix.userID) {+ if issue.ID == leakID {+ t.Fatalf("involves match leaked: canonical-leader UNION branch did not enforce workspace scoping")+ }+ }+}++// Pins workspace scoping on the UNION's squad_member.member branch+// (issue.sql:26). Current-workspace issue points at a foreign squad whose+// human member is the involves user; only `s.workspace_id = $1` can drop it.+func TestListIssues_InvolvesUserID_ExcludesOtherWorkspaceSquadMember(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ var otherRuntimeID, otherLeaderID 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, 'Other Runtime Member', 'cloud', 'other3', 'online', '', '{}'::jsonb, now())+ RETURNING id+ `, fix.otherWsID).Scan(&otherRuntimeID); err != nil {+ t.Fatalf("create other runtime: %v", err)+ }+ 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, 'Other WS Leader (member test)', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id+ `, fix.otherWsID, otherRuntimeID, testUserID).Scan(&otherLeaderID); err != nil {+ t.Fatalf("create other leader agent: %v", err)+ }++ otherSquadID := insertSquad(t, ctx, fix.otherWsID, "Other WS Squad Member", otherLeaderID)+ insertSquadMember(t, ctx, otherSquadID, "member", fix.userID)+ leakID := insertIssueTo(t, ctx, testWorkspaceID, "current-ws issue, foreign squad assignee (member)", "squad", otherSquadID)++ for _, issue := range listIssuesInvolves(t, fix.userID) {+ if issue.ID == leakID {+ t.Fatalf("involves match leaked: squad_member.member UNION branch did not enforce workspace scoping")+ }+ }+}++// Pins workspace scoping on the UNION's squad_member.agent branch+// (issue.sql:45-47). Current-workspace issue points at a foreign squad whose+// agent member is a foreign-workspace agent owned by the involves user; only+// `s.workspace_id = $1` / `a.workspace_id = $1` can drop it.+func TestListIssues_InvolvesUserID_ExcludesOtherWorkspaceSquadAgentMember(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ var otherRuntimeID, otherLeaderID, otherAgentMemberID 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, 'Other Runtime AgentMember', 'cloud', 'other4', 'online', '', '{}'::jsonb, now())+ RETURNING id+ `, fix.otherWsID).Scan(&otherRuntimeID); err != nil {+ t.Fatalf("create other runtime: %v", err)+ }+ // Foreign-workspace leader so the squad satisfies its leader_id workspace+ // CHECK; owned by testUserID so it can't itself match the involves filter.+ 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, 'Other WS Leader (agent-member test)', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id+ `, fix.otherWsID, otherRuntimeID, testUserID).Scan(&otherLeaderID); err != nil {+ t.Fatalf("create other leader agent: %v", err)+ }+ // Foreign-workspace agent owned by the involves user — the row whose+ // owner_id alone would mistakenly match if `a.workspace_id = $1` were+ // dropped from the agent-member subquery.+ 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, 'Other WS Agent (foreign squad member)', '', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3)+ RETURNING id+ `, fix.otherWsID, otherRuntimeID, fix.userID).Scan(&otherAgentMemberID); err != nil {+ t.Fatalf("create other agent member: %v", err)+ }++ otherSquadID := insertSquad(t, ctx, fix.otherWsID, "Other WS Squad AgentMember", otherLeaderID)+ insertSquadMember(t, ctx, otherSquadID, "agent", otherAgentMemberID)+ leakID := insertIssueTo(t, ctx, testWorkspaceID, "current-ws issue, foreign squad assignee (agent member)", "squad", otherSquadID)++ for _, issue := range listIssuesInvolves(t, fix.userID) {+ if issue.ID == leakID {+ t.Fatalf("involves match leaked: squad_member.agent UNION branch did not enforce workspace scoping")+ }+ }+}++func TestListIssues_InvolvesUserID_CombinesWithCreatorID(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ // One issue matches both creator_id=testUserID (default) and involves+ // (assignee = involves user's agent). Another matches only involves+ // (assignee = involves user's agent, but creator is the involves user).+ // Asserting creator_id AND involves_user_id keeps the first, drops the second.+ hit := insertIssueTo(t, ctx, testWorkspaceID, "creator AND involves", "agent", fix.agentID)++ miss := nextIssueNumber(t, ctx, testWorkspaceID)+ var missID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, description, status, priority,+ assignee_type, assignee_id, creator_type, creator_id,+ position, number+ )+ VALUES ($1, 'involves only, different creator', NULL, 'todo', 'none', 'agent', $2, 'member', $3, 0, $4)+ RETURNING id+ `, testWorkspaceID, fix.agentID, fix.userID, miss).Scan(&missID); err != nil {+ t.Fatalf("insert miss: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, missID)+ })++ path := fmt.Sprintf(+ "/api/issues?workspace_id=%s&involves_user_id=%s&creator_id=%s&limit=1000",+ testWorkspaceID, fix.userID, testUserID,+ )+ w := httptest.NewRecorder()+ testHandler.ListIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListIssues: %d %s", w.Code, w.Body.String())+ }+ var resp struct {+ Issues []IssueResponse `json:"issues"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if !containsIssueID(resp.Issues, hit) {+ t.Fatalf("expected combined filter to keep hit issue %s", hit)+ }+ if containsIssueID(resp.Issues, missID) {+ t.Fatalf("expected combined filter to exclude issue created by involves user (id=%s)", missID)+ }+}++func TestListIssues_InvolvesUserID_InvalidUUIDReturns400(t *testing.T) {+ path := fmt.Sprintf("/api/issues?workspace_id=%s&involves_user_id=not-a-uuid", testWorkspaceID)+ w := httptest.NewRecorder()+ testHandler.ListIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for malformed involves_user_id, got %d: %s", w.Code, w.Body.String())+ }+}++// Grouped path mirrors the same UNION fragment; this test pins that the+// dynamic SQL injection at issue.go also respects involves_user_id and stays+// workspace-scoped.+func TestListGroupedIssues_InvolvesUserID_MatchesLeaderViaCanonicalRelation(t *testing.T) {+ ctx := context.Background()+ fix := setupInvolvesFixture(t)++ squadID := insertSquad(t, ctx, testWorkspaceID, fmt.Sprintf("Grouped Canonical %d", time.Now().UnixNano()), fix.agentID)+ issueID := insertIssueTo(t, ctx, testWorkspaceID, "grouped involves leader", "squad", squadID)++ path := fmt.Sprintf(+ "/api/issues/grouped?workspace_id=%s&group_by=assignee&statuses=todo&involves_user_id=%s",+ testWorkspaceID, fix.userID,+ )+ w := httptest.NewRecorder()+ testHandler.ListGroupedIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListGroupedIssues: %d %s", w.Code, w.Body.String())+ }+ var resp GroupedIssuesResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ found := false+ for _, group := range resp.Groups {+ for _, i := range group.Issues {+ if i.ID == issueID {+ found = true+ }+ }+ }+ if !found {+ t.Fatalf("expected grouped involves match for canonical leader, response: %+v", resp.Groups)+ }+}diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 45184f0a76..4e2686dddb 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -94,24 +94,58 @@ func (q *Queries) CountCreatedIssueAssignees(ctx context.Context, arg CountCreat}const countIssues = `-- name: CountIssues :one-SELECT count(*) FROM issue-WHERE workspace_id = $1- AND ($2::text IS NULL OR status = $2)- AND ($3::text IS NULL OR priority = $3)- AND ($4::uuid IS NULL OR assignee_id = $4)- AND ($5::uuid[] IS NULL OR assignee_id = ANY($5::uuid[]))- AND ($6::uuid IS NULL OR creator_id = $6)- AND ($7::uuid IS NULL OR project_id = $7)+SELECT count(*) FROM issue i+WHERE i.workspace_id = $1+ AND ($2::text IS NULL OR i.status = $2)+ AND ($3::text IS NULL OR i.priority = $3)+ AND ($4::uuid IS NULL OR i.assignee_id = $4)+ AND ($5::uuid[] IS NULL OR i.assignee_id = ANY($5::uuid[]))+ AND ($6::uuid IS NULL OR i.creator_id = $6)+ AND ($7::uuid IS NULL OR i.project_id = $7)+ AND (+ $8::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = $8::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = $8::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = $8::uuid+ UNION+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = $8::uuid+ UNION+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = $8::uuid+ ))+ )`type CountIssuesParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Status pgtype.Text `json:"status"`- Priority pgtype.Text `json:"priority"`- AssigneeID pgtype.UUID `json:"assignee_id"`- AssigneeIds []pgtype.UUID `json:"assignee_ids"`- CreatorID pgtype.UUID `json:"creator_id"`- ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Status pgtype.Text `json:"status"`+ Priority pgtype.Text `json:"priority"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ AssigneeIds []pgtype.UUID `json:"assignee_ids"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`}func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64, error) {@@ -123,6 +157,7 @@ func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64arg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.InvolvesUserID,)var count int64err := row.Scan(&count)@@ -295,7 +330,7 @@ func (q *Queries) DeleteIssue(ctx context.Context, id pgtype.UUID) error {}const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date FROM issueWHERE workspace_id = $1AND status NOT IN ('done', 'cancelled')AND project_id IS NOT DISTINCT FROM $2::uuid@@ -343,6 +378,7 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu&i.OriginType,&i.OriginID,&i.FirstExecutedAt,+ &i.StartDate,)return i, err}@@ -566,31 +602,70 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID}const listIssues = `-- name: ListIssues :many-SELECT id, workspace_id, title, description, status, priority,- assignee_type, assignee_id, creator_type, creator_id,- parent_issue_id, position, start_date, due_date, created_at, updated_at, number, project_id-FROM issue-WHERE workspace_id = $1- AND ($4::text IS NULL OR status = $4)- AND ($5::text IS NULL OR priority = $5)- AND ($6::uuid IS NULL OR assignee_id = $6)- AND ($7::uuid[] IS NULL OR assignee_id = ANY($7::uuid[]))- AND ($8::uuid IS NULL OR creator_id = $8)- AND ($9::uuid IS NULL OR project_id = $9)-ORDER BY position ASC, created_at DESC+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+FROM issue i+WHERE i.workspace_id = $1+ AND ($4::text IS NULL OR i.status = $4)+ AND ($5::text IS NULL OR i.priority = $5)+ AND ($6::uuid IS NULL OR i.assignee_id = $6)+ AND ($7::uuid[] IS NULL OR i.assignee_id = ANY($7::uuid[]))+ AND ($8::uuid IS NULL OR i.creator_id = $8)+ AND ($9::uuid IS NULL OR i.project_id = $9)+ AND (+ $10::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = $10::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = $10::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ -- (a) I am a human member of the squad.+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = $10::uuid+ UNION+ -- (b) Canonical leader relation. Independent of squad_member copy row+ -- because AddSquadMember errors are ignored in+ -- server/internal/handler/squad.go (create + update-leader paths).+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = $10::uuid+ UNION+ -- (c) Squad has an agent member whose owner is me.+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = $10::uuid+ ))+ )+ORDER BY i.position ASC, i.created_at DESCLIMIT $2 OFFSET $3`type ListIssuesParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Limit int32 `json:"limit"`- Offset int32 `json:"offset"`- Status pgtype.Text `json:"status"`- Priority pgtype.Text `json:"priority"`- AssigneeID pgtype.UUID `json:"assignee_id"`- AssigneeIds []pgtype.UUID `json:"assignee_ids"`- CreatorID pgtype.UUID `json:"creator_id"`- ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int32 `json:"limit"`+ Offset int32 `json:"offset"`+ Status pgtype.Text `json:"status"`+ Priority pgtype.Text `json:"priority"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ AssigneeIds []pgtype.UUID `json:"assignee_ids"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`}type ListIssuesRow struct {@@ -625,6 +700,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListIarg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.InvolvesUserID,)if err != nil {return nil, err@@ -664,27 +740,61 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI}const listOpenIssues = `-- name: ListOpenIssues :many-SELECT id, workspace_id, title, description, status, priority,- assignee_type, assignee_id, creator_type, creator_id,- parent_issue_id, position, start_date, due_date, created_at, updated_at, number, project_id-FROM issue-WHERE workspace_id = $1- AND status NOT IN ('done', 'cancelled')- AND ($2::text IS NULL OR priority = $2)- AND ($3::uuid IS NULL OR assignee_id = $3)- AND ($4::uuid[] IS NULL OR assignee_id = ANY($4::uuid[]))- AND ($5::uuid IS NULL OR creator_id = $5)- AND ($6::uuid IS NULL OR project_id = $6)-ORDER BY position ASC, created_at DESC+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+FROM issue i+WHERE i.workspace_id = $1+ AND i.status NOT IN ('done', 'cancelled')+ AND ($2::text IS NULL OR i.priority = $2)+ AND ($3::uuid IS NULL OR i.assignee_id = $3)+ AND ($4::uuid[] IS NULL OR i.assignee_id = ANY($4::uuid[]))+ AND ($5::uuid IS NULL OR i.creator_id = $5)+ AND ($6::uuid IS NULL OR i.project_id = $6)+ AND (+ $7::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = $7::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = $7::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = $7::uuid+ UNION+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = $7::uuid+ UNION+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = $7::uuid+ ))+ )+ORDER BY i.position ASC, i.created_at DESC`type ListOpenIssuesParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Priority pgtype.Text `json:"priority"`- AssigneeID pgtype.UUID `json:"assignee_id"`- AssigneeIds []pgtype.UUID `json:"assignee_ids"`- CreatorID pgtype.UUID `json:"creator_id"`- ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Priority pgtype.Text `json:"priority"`+ AssigneeID pgtype.UUID `json:"assignee_id"`+ AssigneeIds []pgtype.UUID `json:"assignee_ids"`+ CreatorID pgtype.UUID `json:"creator_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`}type ListOpenIssuesRow struct {@@ -716,6 +826,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)arg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.InvolvesUserID,)if err != nil {return nil, err@@ -758,8 +869,8 @@ const lockIssueDuplicateKey = `-- name: LockIssueDuplicateKey :execSELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))`-func (q *Queries) LockIssueDuplicateKey(ctx context.Context, key string) error {- _, err := q.db.Exec(ctx, lockIssueDuplicateKey, key)+func (q *Queries) LockIssueDuplicateKey(ctx context.Context, dollar_1 string) error {+ _, err := q.db.Exec(ctx, lockIssueDuplicateKey, dollar_1)return err}diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex dc0dcc7849..891b49c62b 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -1,16 +1,54 @@-- name: ListIssues :many-SELECT id, workspace_id, title, description, status, priority,- assignee_type, assignee_id, creator_type, creator_id,- parent_issue_id, position, start_date, due_date, created_at, updated_at, number, project_id-FROM issue-WHERE workspace_id = $1- AND (sqlc.narg('status')::text IS NULL OR status = sqlc.narg('status'))- AND (sqlc.narg('priority')::text IS NULL OR priority = sqlc.narg('priority'))- AND (sqlc.narg('assignee_id')::uuid IS NULL OR assignee_id = sqlc.narg('assignee_id'))- AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))- AND (sqlc.narg('creator_id')::uuid IS NULL OR creator_id = sqlc.narg('creator_id'))- AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))-ORDER BY position ASC, created_at DESC+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+FROM issue i+WHERE i.workspace_id = $1+ AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))+ AND (sqlc.narg('priority')::text IS NULL OR i.priority = sqlc.narg('priority'))+ AND (sqlc.narg('assignee_id')::uuid IS NULL OR i.assignee_id = sqlc.narg('assignee_id'))+ AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR i.assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))+ AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.narg('involves_user_id')::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = sqlc.narg('involves_user_id')::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ -- (a) I am a human member of the squad.+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = sqlc.narg('involves_user_id')::uuid+ UNION+ -- (b) Canonical leader relation. Independent of squad_member copy row+ -- because AddSquadMember errors are ignored in+ -- server/internal/handler/squad.go (create + update-leader paths).+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ UNION+ -- (c) Squad has an agent member whose owner is me.+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ )+ORDER BY i.position ASC, i.created_at DESCLIMIT $2 OFFSET $3;-- name: GetIssue :one@@ -76,9 +114,9 @@ SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0));SELECT * FROM issueWHERE workspace_id = $1AND status NOT IN ('done', 'cancelled')- AND project_id IS NOT DISTINCT FROM $2::uuid- AND parent_issue_id IS NOT DISTINCT FROM $3::uuid- AND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = $4+ AND project_id IS NOT DISTINCT FROM sqlc.arg('project_id')::uuid+ AND parent_issue_id IS NOT DISTINCT FROM sqlc.arg('parent_issue_id')::uuid+ AND lower(btrim(regexp_replace(title, '[[:space:]]+', ' ', 'g'))) = sqlc.arg('normalized_title')ORDER BY created_at ASCLIMIT 1;@@ -86,28 +124,94 @@ LIMIT 1;DELETE FROM issue WHERE id = $1;-- name: ListOpenIssues :many-SELECT id, workspace_id, title, description, status, priority,- assignee_type, assignee_id, creator_type, creator_id,- parent_issue_id, position, start_date, due_date, created_at, updated_at, number, project_id-FROM issue-WHERE workspace_id = $1- AND status NOT IN ('done', 'cancelled')- AND (sqlc.narg('priority')::text IS NULL OR priority = sqlc.narg('priority'))- AND (sqlc.narg('assignee_id')::uuid IS NULL OR assignee_id = sqlc.narg('assignee_id'))- AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))- AND (sqlc.narg('creator_id')::uuid IS NULL OR creator_id = sqlc.narg('creator_id'))- AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))-ORDER BY position ASC, created_at DESC;+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id+FROM issue i+WHERE i.workspace_id = $1+ AND i.status NOT IN ('done', 'cancelled')+ AND (sqlc.narg('priority')::text IS NULL OR i.priority = sqlc.narg('priority'))+ AND (sqlc.narg('assignee_id')::uuid IS NULL OR i.assignee_id = sqlc.narg('assignee_id'))+ AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR i.assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))+ AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.narg('involves_user_id')::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = sqlc.narg('involves_user_id')::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = sqlc.narg('involves_user_id')::uuid+ UNION+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ UNION+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ )+ORDER BY i.position ASC, i.created_at DESC;-- name: CountIssues :one-SELECT count(*) FROM issue-WHERE workspace_id = $1- AND (sqlc.narg('status')::text IS NULL OR status = sqlc.narg('status'))- AND (sqlc.narg('priority')::text IS NULL OR priority = sqlc.narg('priority'))- AND (sqlc.narg('assignee_id')::uuid IS NULL OR assignee_id = sqlc.narg('assignee_id'))- AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))- AND (sqlc.narg('creator_id')::uuid IS NULL OR creator_id = sqlc.narg('creator_id'))- AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'));+SELECT count(*) FROM issue i+WHERE i.workspace_id = $1+ AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))+ AND (sqlc.narg('priority')::text IS NULL OR i.priority = sqlc.narg('priority'))+ AND (sqlc.narg('assignee_id')::uuid IS NULL OR i.assignee_id = sqlc.narg('assignee_id'))+ AND (sqlc.narg('assignee_ids')::uuid[] IS NULL OR i.assignee_id = ANY(sqlc.narg('assignee_ids')::uuid[]))+ AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.narg('involves_user_id')::uuid IS NULL+ OR (i.assignee_type = 'member' AND i.assignee_id = sqlc.narg('involves_user_id')::uuid)+ OR (i.assignee_type = 'agent' AND i.assignee_id IN (+ SELECT a.id FROM agent a+ WHERE a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'member'+ AND sm.member_id = sqlc.narg('involves_user_id')::uuid+ UNION+ SELECT s.id+ FROM squad s+ JOIN agent a ON a.id = s.leader_id+ WHERE s.workspace_id = $1+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ UNION+ SELECT sm.squad_id+ FROM squad_member sm+ JOIN squad s ON s.id = sm.squad_id+ JOIN agent a ON a.id = sm.member_id+ WHERE s.workspace_id = $1+ AND sm.member_type = 'agent'+ AND a.workspace_id = $1+ AND a.owner_id = sqlc.narg('involves_user_id')::uuid+ ))+ );-- name: ListChildIssues :manySELECT * FROM issue