Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8472: feat(projects): private project access and member management (#9868)
Bohan Jiang9adeb9822580
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex f16d631d14..6b112c516e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -114,6 +114,7 @@ import type {CreateProjectRequest,UpdateProjectRequest,ListProjectsResponse,+ ListProjectMembersResponse,ProjectResource,CreateProjectResourceRequest,UpdateProjectResourceRequest,@@ -365,6 +366,7 @@ import {RuntimeUsageListSchema,SearchIssuesResponseSchema,ProjectSchema,+ ListProjectMembersResponseSchema,ListProjectsResponseSchema,EMPTY_PROJECT,EMPTY_LIST_PROJECTS_RESPONSE,@@ -4295,6 +4297,9 @@ export class ApiClient {}async createProject(data: CreateProjectRequest): Promise<Project> {+ if (data.visibility === "private" && configStore.getState().featureFlags.private_projects_v1 !== true) {+ throw new Error("Private projects are not enabled on this server.");+ }const raw = await this.fetch<unknown>("/api/projects", {method: "POST",body: JSON.stringify(data),@@ -4314,6 +4319,26 @@ export class ApiClient {await this.fetch(`/api/projects/${id}`, { method: "DELETE" });}+ async getProjectMembers(id: string): Promise<ListProjectMembersResponse> {+ const raw = await this.fetch<unknown>(`/api/projects/${id}/members`);+ return parseWithFallback(raw, ListProjectMembersResponseSchema, { members: [], total: 0 }, {+ endpoint: "GET /api/projects/:id/members",+ });+ }++ async addProjectMembers(id: string, userIds: string[]): Promise<ListProjectMembersResponse> {+ const raw = await this.fetch<unknown>(`/api/projects/${id}/members`, {+ method: "POST", body: JSON.stringify({ user_ids: userIds }),+ });+ return parseWithFallback(raw, ListProjectMembersResponseSchema, { members: [], total: 0 }, {+ endpoint: "POST /api/projects/:id/members",+ });+ }++ async removeProjectMember(id: string, userId: string): Promise<void> {+ await this.fetch(`/api/projects/${id}/members/${userId}`, { method: "DELETE" });+ }+// Project resourcesasync listProjectResources(projectId: string,diff --git a/packages/core/api/project-access.test.ts b/packages/core/api/project-access.test.tsnew file mode 100644index 0000000000..e2b1381077--- /dev/null+++ b/packages/core/api/project-access.test.ts@@ -0,0 +1,46 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";+import { configStore } from "../config";+import { ProjectSchema, EMPTY_PROJECT } from "./schemas";++afterEach(() => { vi.unstubAllGlobals(); configStore.getState().setFeatureFlags({}); });++describe("project access API contracts", () => {+ it("keeps old projects readable and treats unknown visibility as restricted", () => {+ expect(ProjectSchema.parse(EMPTY_PROJECT).visibility).toBe("workspace");+ expect(ProjectSchema.parse({ ...EMPTY_PROJECT, visibility: "future-scope" }).visibility).toBe("private");+ expect(ProjectSchema.parse({ ...EMPTY_PROJECT, visibility: null }).visibility).toBe("private");+ });++ it("blocks private creation on an older server before it can drop access fields", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ await expect(client.createProject({ title: "Secret", visibility: "private", member_ids: ["member-1"] })).rejects.toThrow(/not enabled/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("sends private creation and member changes with their project-scoped contracts", async () => {+ configStore.getState().setFeatureFlags({ private_projects_v1: true });+ const member = { project_id: "p1", user_id: "m1", name: "Alice", email: "[email protected]" };+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({ ...EMPTY_PROJECT, id: "p1", visibility: "private" })))+ .mockResolvedValueOnce(new Response(JSON.stringify({ members: [member], total: 1 })))+ .mockResolvedValueOnce(new Response(JSON.stringify({ members: "invalid", total: 1 })))+ .mockResolvedValueOnce(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ const created = await client.createProject({ title: "Secret", visibility: "private", member_ids: ["m1"] });+ expect(created.visibility).toBe("private");+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1].body)).toMatchObject({ visibility: "private", member_ids: ["m1"] });+ const added = await client.addProjectMembers("p1", ["m1"]);+ expect(added.members[0]).toEqual({ ...member, avatar_url: null });+ expect(fetchMock.mock.calls[1]?.[0]).toBe("https://api.example.test/api/projects/p1/members");+ expect(JSON.parse(fetchMock.mock.calls[1]?.[1].body)).toEqual({ user_ids: ["m1"] });+ expect(await client.getProjectMembers("p1")).toEqual({ members: [], total: 0 });+ await client.removeProjectMember("p1", "m1");+ expect(fetchMock.mock.calls[3]?.[0]).toBe("https://api.example.test/api/projects/p1/members/m1");+ expect(fetchMock.mock.calls[3]?.[1].method).toBe("DELETE");+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 3686b3fbfd..2ac6937ca5 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1581,6 +1581,7 @@ export const ProjectSchema = z.object({id: z.string(),workspace_id: z.string(),title: z.string(),+ visibility: z.enum(["workspace", "private"]).default("workspace").catch("private"),description: z.string().nullable(),icon: z.string().nullable(),status: z.string(),@@ -1616,6 +1617,19 @@ export const ListProjectsResponseSchema = z.object({export const EMPTY_LIST_PROJECTS_RESPONSE: ListProjectsResponse = { projects: [], total: 0 };+export const ProjectMemberSchema = z.object({+ project_id: z.string(),+ user_id: z.string(),+ name: z.string(),+ email: z.string(),+ avatar_url: z.string().nullable().default(null),+}).loose();++export const ListProjectMembersResponseSchema = z.object({+ members: z.array(ProjectMemberSchema),+ total: z.number(),+}).loose();+const SearchProjectResultSchema = ProjectSchema.extend({match_source: z.string(),matched_snippet: z.string().optional(),diff --git a/packages/core/package.json b/packages/core/package.jsonindex 7ceb4efccf..8748221238 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -101,6 +101,7 @@"./projects/deletion-permissions": "./projects/deletion-permissions.ts","./projects/queries": "./projects/queries.ts","./projects/mutations": "./projects/mutations.ts",+ "./projects/access": "./projects/access.ts","./projects/config": "./projects/config.ts","./plugins": "./plugins/index.ts","./plugins/queries": "./plugins/queries.ts",diff --git a/packages/core/projects/access.ts b/packages/core/projects/access.tsnew file mode 100644index 0000000000..6e7acee5c0--- /dev/null+++ b/packages/core/projects/access.ts@@ -0,0 +1,47 @@+import { onlineManager, useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { projectKeys } from "./queries";+import { issueKeys } from "../issues/queries";+import type { Project, ProjectVisibility } from "../types";++// Mirrors the server: owners/admins, or the member lead of a private project.+// Anyone may set the lead of a workspace-visible project, so leading one+// grants nothing; making it private takes an owner/admin.+export function canManageProjectAccess(project: Pick<Project, "lead_type" | "lead_id" | "visibility">, userId: string | null | undefined, role: string | null | undefined): boolean {+ if (!userId) return false;+ if (role === "owner" || role === "admin") return true;+ return project.visibility === "private" && project.lead_type === "member" && project.lead_id === userId;+}++// The lead of a private project manages its access, so only access managers+// may change it there; elsewhere the lead stays an ordinary field.+export function canChangeProjectLead(project: Pick<Project, "lead_type" | "lead_id" | "visibility">, userId: string | null | undefined, role: string | null | undefined): boolean {+ return project.visibility !== "private" || canManageProjectAccess(project, userId, role);+}++type AccessChange =+ | { type: "visibility"; visibility: ProjectVisibility; memberIds: string[] }+ | { type: "add"; userId: string }+ | { type: "remove"; userId: string };++export function useProjectAccessMutation(wsId: string, projectId: string) {+ const qc = useQueryClient();+ return useMutation({+ networkMode: "always",+ retry: false,+ mutationFn: async (change: AccessChange) => {+ if (!onlineManager.isOnline()) throw new Error("You're offline. Reconnect and try again.");+ if (change.type === "visibility") {+ await api.updateProject(projectId, { visibility: change.visibility, member_ids: change.memberIds });+ } else if (change.type === "add") {+ await api.addProjectMembers(projectId, [change.userId]);+ } else {+ await api.removeProjectMember(projectId, change.userId);+ }+ },+ onSettled: async () => {+ await qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });+ await qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });+ },+ });+}diff --git a/packages/core/projects/draft-store.ts b/packages/core/projects/draft-store.tsindex 56fcbe0ec9..7cf74b7347 100644--- a/packages/core/projects/draft-store.ts+++ b/packages/core/projects/draft-store.ts@@ -1,4 +1,4 @@-import type { ProjectStatus, ProjectPriority } from "../types";+import type { ProjectStatus, ProjectPriority, ProjectVisibility } from "../types";import { createDraftStore } from "../drafts/create-draft-store";interface ProjectDraft {@@ -12,6 +12,8 @@ interface ProjectDraft {// Calendar days ("YYYY-MM-DD"); empty/undefined means unset.startDate?: string;dueDate?: string;+ visibility?: ProjectVisibility;+ memberIds?: string[];}const EMPTY_DRAFT: ProjectDraft = {@@ -24,6 +26,8 @@ const EMPTY_DRAFT: ProjectDraft = {icon: undefined,startDate: undefined,dueDate: undefined,+ visibility: "workspace",+ memberIds: [],};export const useProjectDraftStore = createDraftStore<ProjectDraft>({diff --git a/packages/core/projects/queries.ts b/packages/core/projects/queries.tsindex 7787c7deea..0acbf6f409 100644--- a/packages/core/projects/queries.ts+++ b/packages/core/projects/queries.ts@@ -6,6 +6,7 @@ export const projectKeys = {list: (wsId: string) => [...projectKeys.all(wsId), "list"] as const,detail: (wsId: string, id: string) =>[...projectKeys.all(wsId), "detail", id] as const,+ members: (wsId: string, id: string) => [...projectKeys.detail(wsId, id), "members"] as const,};export function projectListOptions(wsId: string) {@@ -22,3 +23,10 @@ export function projectDetailOptions(wsId: string, id: string) {queryFn: () => api.getProject(id),});}++export function projectMembersOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: projectKeys.members(wsId, id),+ queryFn: () => api.getProjectMembers(id),+ });+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 287c095556..a6c6f04521 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -199,6 +199,9 @@ export type { StorageAdapter } from "./storage";export type {Project,ProjectStatus,+ ProjectVisibility,+ ProjectMember,+ ListProjectMembersResponse,ProjectPriority,CreateProjectRequest,UpdateProjectRequest,diff --git a/packages/core/types/project.ts b/packages/core/types/project.tsindex 5db35b2419..707e6127d8 100644--- a/packages/core/types/project.ts+++ b/packages/core/types/project.ts@@ -3,10 +3,26 @@ export type ProjectStatus = "planned" | "in_progress" | "paused" | "completed" |export type ProjectPriority = "urgent" | "high" | "medium" | "low" | "none";+export type ProjectVisibility = "workspace" | "private";++export interface ProjectMember {+ project_id: string;+ user_id: string;+ name: string;+ email: string;+ avatar_url: string | null;+}++export interface ListProjectMembersResponse {+ members: ProjectMember[];+ total: number;+}+export interface Project {id: string;workspace_id: string;title: string;+ visibility?: ProjectVisibility;description: string | null;icon: string | null;status: ProjectStatus;@@ -34,6 +50,8 @@ export interface Project {export interface CreateProjectRequest {title: string;+ visibility?: ProjectVisibility;+ member_ids?: string[];description?: string;icon?: string;status?: ProjectStatus;@@ -51,6 +69,8 @@ export interface CreateProjectRequest {export interface UpdateProjectRequest {title?: string;+ visibility?: ProjectVisibility;+ member_ids?: string[];description?: string | null;icon?: string | null;status?: ProjectStatus;diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 5698e8b509..6518799f0e 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -206,5 +206,27 @@"issue_pricing": "Pricing comparison table","issue_blog": "Paginate the blog list"}+ },+ "access": {+ "label": "Access",+ "title": "Access to {{title}}",+ "description": "Controls who can see this project and its issues, comments, and attachments.",+ "workspace": "Entire workspace",+ "private": "Project members only",+ "members_count": "Project members · {{count}}",+ "add": "Add workspace member",+ "search": "Search name or email...",+ "no_members": "No matching members",+ "no_selected": "No project members",+ "admin_notice": "Workspace owners and admins always have access.",+ "you": "You",+ "remove": "Remove {{name}}",+ "failed": "Could not save access changes.",+ "load_failed": "Could not load project members.",+ "publish_title": "Make this project visible to the workspace?",+ "publish_description": "All workspace members will be able to see this project and its issues, comments, and attachments.",+ "disabled": "Private projects are not enabled on this server.",+ "done": "Done",+ "retry": "Retry"}}diff --git a/packages/views/locales/es/projects.json b/packages/views/locales/es/projects.jsonindex 09adfaa36e..6bef2d7de3 100644--- a/packages/views/locales/es/projects.json+++ b/packages/views/locales/es/projects.json@@ -206,5 +206,27 @@"issue_pricing": "Tabla comparativa de precios","issue_blog": "Paginar la lista del blog"}+ },+ "access": {+ "label": "Acceso",+ "title": "Acceso a {{title}}",+ "description": "Define quién puede ver este proyecto, sus tareas, comentarios y archivos adjuntos.",+ "workspace": "Todo el espacio de trabajo",+ "private": "Solo miembros del proyecto",+ "members_count": "Miembros del proyecto · {{count}}",+ "add": "Añadir miembro",+ "search": "Buscar nombre o correo...",+ "no_members": "No hay miembros coincidentes",+ "no_selected": "No hay miembros del proyecto",+ "admin_notice": "Los owner y admin del espacio de trabajo siempre tienen acceso.",+ "you": "Tú",+ "remove": "Quitar a {{name}}",+ "failed": "No se pudieron guardar los permisos.",+ "load_failed": "No se pudieron cargar los miembros.",+ "publish_title": "¿Hacer visible el proyecto a todo el espacio de trabajo?",+ "publish_description": "Todos los miembros podrán ver este proyecto, sus tareas, comentarios y archivos adjuntos.",+ "disabled": "Los proyectos privados no están activados en este servidor.",+ "done": "Listo",+ "retry": "Reintentar"}}diff --git a/packages/views/locales/fr/projects.json b/packages/views/locales/fr/projects.jsonindex 82b8014f9e..946752e41d 100644--- a/packages/views/locales/fr/projects.json+++ b/packages/views/locales/fr/projects.json@@ -206,5 +206,27 @@"issue_pricing": "Tableau comparatif des tarifs","issue_blog": "Paginer la liste du blog"}+ },+ "access": {+ "label": "Accès",+ "title": "Accès à {{title}}",+ "description": "Définit qui peut voir ce projet, ses tâches, commentaires et pièces jointes.",+ "workspace": "Tout l’espace de travail",+ "private": "Membres du projet uniquement",+ "members_count": "Membres du projet · {{count}}",+ "add": "Ajouter un membre",+ "search": "Rechercher un nom ou un e-mail...",+ "no_members": "Aucun membre correspondant",+ "no_selected": "Aucun membre du projet",+ "admin_notice": "Les owner et admin de l’espace de travail ont toujours accès.",+ "you": "Vous",+ "remove": "Retirer {{name}}",+ "failed": "Impossible d’enregistrer les accès.",+ "load_failed": "Impossible de charger les membres.",+ "publish_title": "Rendre ce projet visible à tout l’espace de travail ?",+ "publish_description": "Tous les membres pourront voir ce projet, ses tâches, commentaires et pièces jointes.",+ "disabled": "Les projets privés ne sont pas activés sur ce serveur.",+ "done": "Terminé",+ "retry": "Réessayer"}}diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.jsonindex 07c1b3711f..f809efc5bd 100644--- a/packages/views/locales/ja/projects.json+++ b/packages/views/locales/ja/projects.json@@ -206,5 +206,27 @@"issue_pricing": "料金ページの比較表","issue_blog": "ブログ一覧のページ送り"}+ },+ "access": {+ "label": "アクセス権",+ "title": "{{title}}のアクセス権",+ "description": "プロジェクトとそのタスク、コメント、添付ファイルの閲覧範囲を設定します。",+ "workspace": "ワークスペース全体",+ "private": "プロジェクトメンバーのみ",+ "members_count": "プロジェクトメンバー · {{count}}",+ "add": "ワークスペースメンバーを追加",+ "search": "名前またはメールで検索...",+ "no_members": "該当するメンバーはいません",+ "no_selected": "メンバーはいません",+ "admin_notice": "ワークスペースの owner と admin は常にアクセスできます。",+ "you": "あなた",+ "remove": "{{name}}を削除",+ "failed": "アクセス権を保存できませんでした。",+ "load_failed": "メンバーを読み込めませんでした。",+ "publish_title": "ワークスペース全体に公開しますか?",+ "publish_description": "すべてのワークスペースメンバーがこのプロジェクトとタスク、コメント、添付ファイルを閲覧できるようになります。",+ "disabled": "このサーバーでは非公開プロジェクトが有効になっていません。",+ "done": "完了",+ "retry": "再試行"}}diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.jsonindex 0282ccbec4..4ce4463e15 100644--- a/packages/views/locales/ko/projects.json+++ b/packages/views/locales/ko/projects.json@@ -206,5 +206,27 @@"issue_pricing": "요금제 비교표","issue_blog": "블로그 목록 페이지네이션"}+ },+ "access": {+ "label": "접근 권한",+ "title": "{{title}} 접근 권한",+ "description": "프로젝트와 해당 태스크, 댓글, 첨부 파일을 볼 수 있는 사람을 설정합니다.",+ "workspace": "전체 워크스페이스",+ "private": "프로젝트 멤버만",+ "members_count": "프로젝트 멤버 · {{count}}",+ "add": "워크스페이스 멤버 추가",+ "search": "이름 또는 이메일로 검색...",+ "no_members": "일치하는 멤버가 없습니다",+ "no_selected": "프로젝트 멤버가 없습니다",+ "admin_notice": "워크스페이스 owner와 admin은 항상 접근할 수 있습니다.",+ "you": "나",+ "remove": "{{name}} 제거",+ "failed": "접근 권한을 저장할 수 없습니다.",+ "load_failed": "멤버를 불러올 수 없습니다.",+ "publish_title": "전체 워크스페이스에 공개할까요?",+ "publish_description": "모든 워크스페이스 멤버가 프로젝트와 해당 태스크, 댓글, 첨부 파일을 볼 수 있게 됩니다.",+ "disabled": "이 서버에서는 비공개 프로젝트가 활성화되지 않았습니다.",+ "done": "완료",+ "retry": "다시 시도"}}diff --git a/packages/views/locales/ru/projects.json b/packages/views/locales/ru/projects.jsonindex e77fa03271..821cd2059e 100644--- a/packages/views/locales/ru/projects.json+++ b/packages/views/locales/ru/projects.json@@ -206,5 +206,27 @@}},"title": "Разбивайте большую работу на проекты"+ },+ "access": {+ "label": "Доступ",+ "title": "Доступ к {{title}}",+ "description": "Определяет, кто видит проект, его задачи, комментарии и вложения.",+ "workspace": "Всё рабочее пространство",+ "private": "Только участники проекта",+ "members_count": "Участники проекта · {{count}}",+ "add": "Добавить участника",+ "search": "Поиск по имени или почте...",+ "no_members": "Участники не найдены",+ "no_selected": "Нет участников проекта",+ "admin_notice": "У owner и admin рабочего пространства всегда есть доступ.",+ "you": "Вы",+ "remove": "Удалить {{name}}",+ "failed": "Не удалось сохранить права доступа.",+ "load_failed": "Не удалось загрузить участников.",+ "publish_title": "Открыть проект всему рабочему пространству?",+ "publish_description": "Все участники смогут видеть проект, его задачи, комментарии и вложения.",+ "disabled": "На этом сервере приватные проекты не включены.",+ "done": "Готово",+ "retry": "Повторить"}}diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex dd7112c0b0..084a5976ca 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -206,5 +206,27 @@"issue_pricing": "定价页对比表","issue_blog": "博客列表分页"}+ },+ "access": {+ "label": "访问权限",+ "title": "{{title}}的访问权限",+ "description": "控制谁能查看项目及其中的任务、评论和附件。",+ "workspace": "整个工作区",+ "private": "仅项目成员",+ "members_count": "项目成员 · {{count}}",+ "add": "添加工作区成员",+ "search": "搜索姓名或邮箱...",+ "no_members": "没有匹配的成员",+ "no_selected": "暂无项目成员",+ "admin_notice": "工作区 owner 和 admin 始终可以访问。",+ "you": "你",+ "remove": "移除{{name}}",+ "failed": "无法保存访问权限。",+ "load_failed": "无法加载项目成员。",+ "publish_title": "将项目设为整个工作区可见?",+ "publish_description": "工作区所有成员都将能查看这个项目及其中的任务、评论和附件。",+ "disabled": "此服务器尚未启用私有项目。",+ "done": "完成",+ "retry": "重试"}}diff --git a/packages/views/locales/zh-Hant/projects.json b/packages/views/locales/zh-Hant/projects.jsonindex 7ef2f611de..66f6a3f66f 100644--- a/packages/views/locales/zh-Hant/projects.json+++ b/packages/views/locales/zh-Hant/projects.json@@ -206,5 +206,27 @@"issue_pricing": "定價頁對比表","issue_blog": "部落格列表分頁"}+ },+ "access": {+ "label": "存取權限",+ "title": "{{title}}的存取權限",+ "description": "控制誰能查看專案及其中的任務、評論和附件。",+ "workspace": "整個工作區",+ "private": "僅專案成員",+ "members_count": "專案成員 · {{count}}",+ "add": "新增工作區成員",+ "search": "搜尋姓名或電子郵件...",+ "no_members": "沒有相符的成員",+ "no_selected": "尚無專案成員",+ "admin_notice": "工作區 owner 和 admin 一律可以存取。",+ "you": "你",+ "remove": "移除{{name}}",+ "failed": "無法儲存存取權限。",+ "load_failed": "無法載入專案成員。",+ "publish_title": "讓整個工作區都能看到專案?",+ "publish_description": "工作區所有成員都將能查看這個專案及其中的任務、評論和附件。",+ "disabled": "此伺服器尚未啟用私人專案。",+ "done": "完成",+ "retry": "重試"}}diff --git a/packages/views/modals/create-project-local-mode.test.tsx b/packages/views/modals/create-project-local-mode.test.tsxindex e69e1021c1..81c552dce1 100644--- a/packages/views/modals/create-project-local-mode.test.tsx+++ b/packages/views/modals/create-project-local-mode.test.tsx@@ -91,8 +91,8 @@ vi.mock("@multica/core/projects", () => ({// release before the worktree save gate.let serverValidatesWorktree = true;vi.mock("@multica/core/config", () => ({- useConfigStore: (selector: (state: { localWorktreeSupported: boolean }) => unknown) =>- selector({ localWorktreeSupported: serverValidatesWorktree }),+ useConfigStore: (selector: (state: { localWorktreeSupported: boolean; featureFlags: Record<string, boolean> }) => unknown) =>+ selector({ localWorktreeSupported: serverValidatesWorktree, featureFlags: {} }),}));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsxindex 7fbd1e0797..11a05b8c70 100644--- a/packages/views/modals/create-project.tsx+++ b/packages/views/modals/create-project.tsx@@ -34,7 +34,7 @@ import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";import { useActorName } from "@multica/core/workspace/hooks";-import type { ProjectStatus, ProjectPriority } from "@multica/core/types";+import type { ProjectStatus, ProjectPriority, ProjectVisibility } from "@multica/core/types";import { cn } from "@multica/ui/lib/utils";import { toast } from "sonner";import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";@@ -61,6 +61,7 @@ import {} from "../projects/components/labels";import { ProjectStartDatePicker } from "../projects/components/project-start-date-picker";import { ProjectDueDatePicker } from "../projects/components/project-due-date-picker";+import { ProjectAccessDraftPicker } from "../projects/components/project-access";import { PillButton } from "../common/pill-button";import { WorkflowPill } from "../workflows/workflow-pill";import { githubShortLabel } from "../common/github-url";@@ -170,6 +171,9 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {const [icon, setIcon] = useState<string | undefined>(draft.icon);const [startDate, setStartDate] = useState<string>(draft.startDate ?? "");const [dueDate, setDueDate] = useState<string>(draft.dueDate ?? "");+ const [visibility, setVisibility] = useState<ProjectVisibility>(draft.visibility ?? "workspace");+ const [memberIds, setMemberIds] = useState<string[]>(draft.memberIds ?? []);+ const privateEnabled = useConfigStore((s) => s.featureFlags.private_projects_v1 === true);// Dates are collapsed into the ⋯ overflow by default (progressive// disclosure, mirroring create-issue); these flip a pill inline + open.const [startDatePickerOpen, setStartDatePickerOpen] = useState(false);@@ -353,6 +357,10 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {// Checked here as well as on the button: TitleEditor's onSubmit calls this// directly, so a disabled button alone leaves the keyboard path open.if (!title.trim() || submitting) return;+ if (visibility === "private" && !privateEnabled) {+ toast.error(tProjects(($) => $.access.disabled));+ return;+ }if (sourceMode === "repos" && hasRejectedRepoRef) return;// `sourceMode` decides which side's stash gets persisted — the other// side is silently dropped, so repos picked then abandoned for local@@ -402,6 +410,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {...(workflowId ? { workflow_id: workflowId } : {}),// Server attaches these in the same transaction as the project.resources,+ ...(visibility === "private" ? { visibility, member_ids: memberIds } : {}),});clearDraft();onClose();@@ -625,6 +634,9 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {</DropdownMenu><WorkflowPill value={workflowId} onChange={setWorkflowId} />+ {(privateEnabled || visibility === "private") && <ProjectAccessDraftPicker visibility={visibility} memberIds={memberIds} members={members}+ leadId={leadType === "member" ? leadId : undefined}+ onChange={(value, ids) => { setVisibility(value); setMemberIds(ids); setDraft({ visibility: value, memberIds: ids }); }} />}<Popoveropen={leadOpen}@@ -1129,6 +1141,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {disabled={!title.trim() ||submitting ||+ (visibility === "private" && !privateEnabled) ||(sourceMode === "repos" && hasRejectedRepoRef)}className="shrink-0"diff --git a/packages/views/projects/components/project-access.test.tsx b/packages/views/projects/components/project-access.test.tsxnew file mode 100644index 0000000000..0758818b81--- /dev/null+++ b/packages/views/projects/components/project-access.test.tsx@@ -0,0 +1,150 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { configStore } from "@multica/core/config";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import type { Project, MemberWithUser } from "@multica/core/types";+import { EMPTY_PROJECT } from "@multica/core/api/schemas";+import { renderWithI18n } from "../../test/i18n";+import { ProjectAccessControl, ProjectAccessDraftPicker } from "./project-access";+import { ProjectLeadPicker } from "./project-lead-picker";++const state = vi.hoisted(() => ({ viewer: "owner" }));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));+vi.mock("@multica/core/auth", () => ({ useAuthStore: Object.assign((selector: (s: { user: { id: string } }) => unknown) => selector({ user: { id: state.viewer } }), { getState: () => ({ user: { id: state.viewer } }) }) }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span aria-hidden="true" /> }));+vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Lead" }) }));++const members: MemberWithUser[] = [+ { id: "1", workspace_id: "ws", user_id: "owner", name: "Owner", email: "owner@test", role: "owner", avatar_url: null, created_at: "" },+ { id: "2", workspace_id: "ws", user_id: "lead", name: "Lead", email: "lead@test", role: "member", avatar_url: null, created_at: "" },+ { id: "3", workspace_id: "ws", user_id: "member", name: "Member", email: "member@test", role: "member", avatar_url: null, created_at: "" },+ { id: "4", workspace_id: "ws", user_id: "outsider", name: "Outside Person", email: "outside@test", role: "member", avatar_url: null, created_at: "" },+];+const project = { ...EMPTY_PROJECT, id: "p1", workspace_id: "ws", title: "Secret Plan", visibility: "private" as const, lead_type: "member" as const, lead_id: "lead" };+let qc: QueryClient;+let ids: string[];+let api: { listMembers: ReturnType<typeof vi.fn>; listAgents: ReturnType<typeof vi.fn>; getProjectMembers: ReturnType<typeof vi.fn>; addProjectMembers: ReturnType<typeof vi.fn>; removeProjectMember: ReturnType<typeof vi.fn>; updateProject: ReturnType<typeof vi.fn> };++function renderControl(value: Project = project) {+ return renderWithI18n(<QueryClientProvider client={qc}><ProjectAccessControl project={value} /></QueryClientProvider>);+}++beforeEach(() => {+ state.viewer = "owner";+ configStore.getState().setFeatureFlags({ private_projects_v1: true });+ qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ ids = ["owner", "lead", "member"];+ const response = () => ({ members: members.filter((m) => ids.includes(m.user_id)).map((m) => ({ ...m, project_id: "p1" })), total: ids.length });+ api = {+ listMembers: vi.fn().mockResolvedValue(members),+ listAgents: vi.fn().mockResolvedValue([]),+ getProjectMembers: vi.fn().mockImplementation(async () => response()),+ addProjectMembers: vi.fn().mockImplementation(async (_id, added: string[]) => { ids = [...ids, ...added]; return response(); }),+ removeProjectMember: vi.fn().mockImplementation(async (_id, removed: string) => { ids = ids.filter((id) => id !== removed); }),+ updateProject: vi.fn().mockResolvedValue(project),+ };+ setApiInstance(api as unknown as ApiClient);+});+afterEach(() => { qc.clear(); configStore.getState().setFeatureFlags({}); });++it("loads the member list, finds people by email, and adds and removes only after success", async () => {+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ expect(screen.getByText(/owners and admins always have access/)).toBeVisible();+ await user.click(screen.getByRole("button", { name: "Add workspace member" }));+ await user.type(screen.getByRole("combobox"), "outside@test");+ await user.click(screen.getByRole("option", { name: /Outside Person/ }));+ await waitFor(() => expect(api.addProjectMembers).toHaveBeenCalledWith("p1", ["outsider"]));+ await screen.findByRole("button", { name: "Remove Outside Person" });+ api.removeProjectMember.mockRejectedValueOnce(new Error("Remove denied"));+ await user.click(screen.getByRole("button", { name: "Remove Outside Person" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Remove denied");+ expect(screen.getByText("outside@test")).toBeVisible();+ expect(screen.getByRole("dialog")).toBeVisible();+});++it("keeps project membership read-only for a regular member, including their own membership", async () => {+ state.viewer = "member";+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ expect(screen.getByRole("radio", { name: "Entire workspace" })).toBeDisabled();+ expect(screen.queryByRole("button", { name: "Add workspace member" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Remove Owner" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Remove Lead" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Remove Member" })).not.toBeInTheDocument();+ expect(api.removeProjectMember).not.toHaveBeenCalled();+});++it.each(["owner", "lead"])("allows %s to manage project members", async (viewer) => {+ state.viewer = viewer;+ renderControl();+ await userEvent.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ expect(screen.getByRole("button", { name: "Add workspace member" })).toBeEnabled();+ expect(screen.getByRole("button", { name: "Remove Member" })).toBeEnabled();+ expect(screen.queryByRole("button", { name: "Remove Lead" })).not.toBeInTheDocument();+});++it.each(["owner", "lead", "member"])("guards the lead picker for %s", async (viewer) => {+ state.viewer = viewer;+ const update = vi.fn();+ renderWithI18n(<QueryClientProvider client={qc}><ProjectLeadPicker project={project} handleUpdate={update} renderTrigger={() => <button type="button">Change lead</button>} /></QueryClientProvider>);+ const trigger = screen.getByRole("button", { name: "Change lead" });+ if (viewer === "member") {+ expect(trigger).toBeDisabled();+ await userEvent.click(trigger);+ expect(screen.queryByPlaceholderText("Assign lead...")).not.toBeInTheDocument();+ expect(update).not.toHaveBeenCalled();+ } else {+ await waitFor(() => expect(trigger).toBeEnabled());+ await userEvent.click(trigger);+ await userEvent.click(screen.getByRole("button", { name: "Outside Person" }));+ expect(update).toHaveBeenCalledWith({ lead_type: "member", lead_id: "outsider" });+ }+});++it("requires confirmation before making private content visible to the workspace", async () => {+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ await user.click(screen.getByRole("radio", { name: "Entire workspace" }));+ await user.click(screen.getByRole("button", { name: "Save" }));+ const confirmation = await screen.findByRole("alertdialog");+ expect(api.updateProject).not.toHaveBeenCalled();+ await user.click(within(confirmation).getByRole("button", { name: "Confirm" }));+ await waitFor(() => expect(api.updateProject).toHaveBeenCalledWith("p1", { visibility: "workspace", member_ids: ["owner", "lead", "member"] }));+});++it("keeps existing private memberships manageable with the creation flag off", async () => {+ configStore.getState().setFeatureFlags({ private_projects_v1: false });+ const user = userEvent.setup();+ renderControl();+ await user.click(screen.getByRole("button", { name: "Access" }));+ await screen.findByText("member@test");+ expect(screen.getByRole("button", { name: "Add workspace member" })).toBeEnabled();+});++it("does not show private creation controls when the backend has not enabled them", () => {+ configStore.getState().setFeatureFlags({});+ renderControl({ ...project, visibility: "workspace" });+ expect(screen.queryByRole("button", { name: "Access" })).not.toBeInTheDocument();+});++it("keeps new-project access in the draft until the project is created", async () => {+ const changed = vi.fn();+ const user = userEvent.setup();+ renderWithI18n(<ProjectAccessDraftPicker visibility="workspace" memberIds={[]} leadId="lead" members={members} onChange={changed} />);+ await user.click(screen.getByRole("button", { name: "Access" }));+ await user.click(screen.getByRole("radio", { name: "Project members only" }));+ expect(changed).toHaveBeenCalledWith("private", ["owner", "lead"]);+ expect(api.updateProject).not.toHaveBeenCalled();+ expect(api.addProjectMembers).not.toHaveBeenCalled();+});diff --git a/packages/views/projects/components/project-access.tsx b/packages/views/projects/components/project-access.tsxnew file mode 100644index 0000000000..2435a56f1b--- /dev/null+++ b/packages/views/projects/components/project-access.tsx@@ -0,0 +1,219 @@+"use client";++import { useId, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Globe, Lock, Shield, UserPlus, X } from "@multica/ui/icons";+import type { MemberWithUser, Project, ProjectVisibility } from "@multica/core/types";+import { useAuthStore } from "@multica/core/auth";+import { useConfigStore } from "@multica/core/config";+import { useWorkspaceId } from "@multica/core/hooks";+import { memberListOptions } from "@multica/core/workspace/queries";+import { projectMembersOptions } from "@multica/core/projects/queries";+import { canManageProjectAccess, useProjectAccessMutation } from "@multica/core/projects/access";+import { Button } from "@multica/ui/components/ui/button";+import { Spinner } from "@multica/ui/components/ui/spinner";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@multica/ui/components/ui/dialog";+import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";+import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "@multica/ui/components/ui/command";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@multica/ui/components/ui/alert-dialog";+import { ActorAvatar } from "../../common/actor-avatar";+import { useT } from "../../i18n";++const EMPTY_IDS: string[] = [];++function AccessFields({ visibility, onVisibilityChange, members, selected, leadId, userId, disabled, canChangeScope, canUsePrivate, canAdd, canRemove, onAdd, onRemove }: {+ visibility: ProjectVisibility;+ onVisibilityChange: (value: ProjectVisibility) => void;+ members: MemberWithUser[];+ selected: string[];+ leadId?: string | null;+ userId?: string;+ disabled: boolean;+ canChangeScope: boolean;+ canUsePrivate: boolean;+ canAdd: boolean;+ canRemove: (id: string) => boolean;+ onAdd: (id: string) => Promise<boolean | void> | void;+ onRemove: (id: string) => Promise<void> | void;+}) {+ const { t } = useT("projects");+ const groupId = useId();+ const [adding, setAdding] = useState(false);+ const recipients = members.filter((member) => selected.includes(member.user_id));+ return (+ <div className="space-y-5">+ <fieldset disabled={disabled} className="divide-y rounded-lg border">+ <legend className="sr-only">{t(($) => $.access.label)}</legend>+ {(["workspace", "private"] as const).map((value) => {+ const Icon = value === "private" ? Lock : Globe;+ return (+ <label key={value} className={`flex cursor-pointer items-center gap-3 px-4 py-3 has-disabled:cursor-default has-disabled:opacity-60 ${visibility === value ? "bg-muted/60" : "hover:bg-surface-hover"}`}>+ <input type="radio" name={groupId} value={value} checked={visibility === value}+ disabled={!canChangeScope || (value === "private" && !canUsePrivate)}+ onChange={() => onVisibilityChange(value)} className="size-4 accent-foreground" />+ <Icon className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />+ <span className="text-body font-medium">{value === "private" ? t(($) => $.access.private) : t(($) => $.access.workspace)}</span>+ </label>+ );+ })}+ </fieldset>+ {visibility === "private" ? (+ <div className="space-y-3">+ <p className="text-caption font-medium">{t(($) => $.access.members_count, { count: recipients.length })}</p>+ {canAdd ? (+ <Popover open={adding} onOpenChange={setAdding}>+ <PopoverTrigger render={<Button type="button" variant="outline" disabled={disabled} className="w-full justify-start text-muted-foreground"><UserPlus />{t(($) => $.access.add)}</Button>} />+ <PopoverContent align="start" className="w-80 p-0">+ <Command>+ <CommandInput placeholder={t(($) => $.access.search)} aria-label={t(($) => $.access.search)} />+ <CommandList>+ <CommandEmpty>{t(($) => $.access.no_members)}</CommandEmpty>+ {members.filter((member) => !selected.includes(member.user_id)).map((member) => (+ <CommandItem key={member.user_id} value={`${member.name} ${member.email}`} disabled={disabled}+ onSelect={async () => { if (await onAdd(member.user_id) !== false) setAdding(false); }}>+ <ActorAvatar actorType="member" actorId={member.user_id} size="sm" />+ <div className="min-w-0"><p className="truncate">{member.name}</p><p className="truncate text-caption text-muted-foreground">{member.email}</p></div>+ </CommandItem>+ ))}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ ) : null}+ <div className="max-h-64 divide-y overflow-y-auto rounded-lg border">+ {recipients.map((member) => (+ <div key={member.user_id} className="flex items-center gap-3 px-3 py-2.5">+ <ActorAvatar actorType="member" actorId={member.user_id} size="sm" />+ <div className="min-w-0 flex-1">+ <p className="truncate text-body">{member.name}{member.user_id === userId ? <span className="ml-1.5 text-caption text-muted-foreground">{t(($) => $.access.you)}</span> : null}</p>+ <p className="truncate text-caption text-muted-foreground">{member.email}</p>+ </div>+ {member.user_id === leadId ? <span className="shrink-0 text-caption text-muted-foreground">{t(($) => $.table.lead)}</span> : member.role === "owner" || member.role === "admin" ? (+ <span className="shrink-0 text-caption text-muted-foreground">{member.role}</span>+ ) : canRemove(member.user_id) ? (+ <Button type="button" variant="ghost" size="icon-xs" disabled={disabled}+ aria-label={t(($) => $.access.remove, { name: member.name })}+ onClick={() => void onRemove(member.user_id)}><X /></Button>+ ) : null}+ </div>+ ))}+ {recipients.length === 0 ? <p className="p-3 text-caption text-muted-foreground">{t(($) => $.access.no_selected)}</p> : null}+ </div>+ </div>+ ) : null}+ <p className="flex items-start gap-2 text-caption text-muted-foreground"><Shield className="mt-0.5 size-4 shrink-0" aria-hidden="true" />{t(($) => $.access.admin_notice)}</p>+ </div>+ );+}++export function ProjectAccessControl({ project }: { project: Project }) {+ const { t } = useT("projects");+ const enabled = useConfigStore((s) => s.featureFlags.private_projects_v1 === true);+ const [open, setOpen] = useState(false);+ const wsId = useWorkspaceId();+ const changeAccess = useProjectAccessMutation(wsId, project.id);+ if (!enabled && project.visibility !== "private") return null;+ const Icon = project.visibility === "private" ? Lock : Globe;+ return (+ <Dialog open={open} onOpenChange={(value) => { if (!changeAccess.isPending) setOpen(value); }}>+ <DialogTrigger render={<Button type="button" variant="ghost" size="sm" className="h-auto min-h-7 max-w-full justify-start px-0" aria-label={t(($) => $.access.label)}><Icon /><span className="truncate">{project.visibility === "private" ? t(($) => $.access.private) : t(($) => $.access.workspace)}</span></Button>} />+ <DialogContent className="flex max-h-[90dvh] flex-col sm:max-w-lg">+ <DialogHeader><DialogTitle>{t(($) => $.access.title, { title: project.title })}</DialogTitle><DialogDescription>{t(($) => $.access.description)}</DialogDescription></DialogHeader>+ {open ? <ProjectAccessEditor project={project} onClose={() => setOpen(false)} enabled={enabled} changeAccess={changeAccess} /> : null}+ </DialogContent>+ </Dialog>+ );+}++function ProjectAccessEditor({ project, enabled, onClose, changeAccess }: { project: Project; enabled: boolean; onClose: () => void; changeAccess: ReturnType<typeof useProjectAccessMutation> }) {+ const { t } = useT("projects");+ const { t: tc } = useT("common");+ const wsId = useWorkspaceId();+ const userId = useAuthStore((s) => s.user?.id);+ const workspaceMembers = useQuery(memberListOptions(wsId));+ const projectMembers = useQuery(projectMembersOptions(wsId, project.id));+ const [visibility, setVisibility] = useState<ProjectVisibility>(project.visibility ?? "workspace");+ const [draftIds, setDraftIds] = useState<string[] | null>(null);+ const [error, setError] = useState("");+ const [confirmPublic, setConfirmPublic] = useState(false);+ const members = workspaceMembers.data ?? [];+ const role = members.find((member) => member.user_id === userId)?.role;+ const leadId = project.lead_type === "member" ? project.lead_id : null;+ const canManage = canManageProjectAccess(project, userId, role);+ const currentIds = projectMembers.data?.members.map((member) => member.user_id) ?? EMPTY_IDS;+ const selected = project.visibility === "private" ? currentIds : (draftIds ?? Array.from(new Set([...currentIds, ...(userId ? [userId] : []), ...(leadId ? [leadId] : [])])));+ const loading = workspaceMembers.isPending || projectMembers.isPending;+ const loadFailed = workspaceMembers.isError || projectMembers.isError;+ const dirty = visibility !== (project.visibility ?? "workspace");+ const pending = changeAccess.isPending;+ const run = async (change: Parameters<typeof changeAccess.mutateAsync>[0]) => {+ setError("");+ try { await changeAccess.mutateAsync(change); return true; }+ catch (err) { setError(err instanceof Error ? err.message : t(($) => $.access.failed)); return false; }+ };+ const saveScope = async () => {+ if (await run({ type: "visibility", visibility, memberIds: selected })) { setConfirmPublic(false); onClose(); }+ };+ return (+ <>+ <div className="min-h-0 flex-1 overflow-y-auto">+ {loading ? <div role="status" className="flex justify-center py-8"><Spinner /></div> : loadFailed ? (+ <div role="alert" className="space-y-2 text-body"><p>{t(($) => $.access.load_failed)}</p><Button variant="outline" size="sm" onClick={() => { void workspaceMembers.refetch(); void projectMembers.refetch(); }}>{t(($) => $.access.retry)}</Button></div>+ ) : (+ <AccessFields visibility={visibility} onVisibilityChange={setVisibility} members={members} selected={selected} userId={userId} leadId={leadId}+ disabled={pending} canChangeScope={canManage} canUsePrivate={enabled || project.visibility === "private"}+ canAdd={canManage}+ canRemove={(id) => canManage && id !== leadId}+ onAdd={async (id) => { if (project.visibility === "private") return run({ type: "add", userId: id }); setDraftIds([...selected, id]); return true; }}+ onRemove={async (id) => {+ if (project.visibility !== "private") { setDraftIds(selected.filter((value) => value !== id)); return; }+ await run({ type: "remove", userId: id });+ }} />+ )}+ {error ? <p role="alert" className="mt-3 text-body text-destructive">{error}</p> : null}+ </div>+ <DialogFooter>+ <Button type="button" disabled={pending || (dirty && (loading || loadFailed))} aria-busy={pending} onClick={() => {+ if (!dirty) onClose();+ else if (visibility === "workspace") setConfirmPublic(true);+ else void saveScope();+ }}>{pending ? <Spinner /> : null}{dirty ? tc(($) => $.save) : t(($) => $.access.done)}</Button>+ </DialogFooter>+ <AlertDialog open={confirmPublic} onOpenChange={setConfirmPublic}>+ <AlertDialogContent>+ <AlertDialogHeader><AlertDialogTitle>{t(($) => $.access.publish_title)}</AlertDialogTitle><AlertDialogDescription>{t(($) => $.access.publish_description)}</AlertDialogDescription></AlertDialogHeader>+ {error ? <p role="alert" className="text-body text-destructive">{error}</p> : null}+ <AlertDialogFooter><AlertDialogCancel disabled={pending}>{tc(($) => $.cancel)}</AlertDialogCancel><AlertDialogAction disabled={pending} aria-busy={pending} onClick={async (event) => { event.preventDefault(); await saveScope(); }}>{tc(($) => $.confirm)}</AlertDialogAction></AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}++export function ProjectAccessDraftPicker({ visibility, memberIds, leadId, members, onChange }: {+ visibility: ProjectVisibility;+ memberIds: string[];+ leadId?: string;+ members: MemberWithUser[];+ onChange: (visibility: ProjectVisibility, ids: string[]) => void;+}) {+ const { t } = useT("projects");+ const enabled = useConfigStore((s) => s.featureFlags.private_projects_v1 === true);+ const userId = useAuthStore((s) => s.user?.id);+ if (!enabled && visibility !== "private") return null;+ const fixed = [userId, leadId].filter((id): id is string => !!id);+ const selected = Array.from(new Set([...memberIds, ...fixed]));+ const Icon = visibility === "private" ? Lock : Globe;+ return (+ <Popover>+ <PopoverTrigger render={<Button type="button" variant="outline" size="sm" aria-label={t(($) => $.access.label)}><Icon />{visibility === "private" ? t(($) => $.access.private) : t(($) => $.access.workspace)}</Button>} />+ <PopoverContent side="top" align="end" className="max-h-[70dvh] w-96 max-w-[calc(100vw-2rem)] overflow-y-auto">+ <AccessFields visibility={visibility} onVisibilityChange={(value) => onChange(value, selected)} members={members} selected={selected} leadId={leadId} userId={userId}+ disabled={false} canChangeScope canUsePrivate={enabled} canAdd+ canRemove={(id) => !fixed.includes(id)}+ onAdd={(id) => onChange(visibility, [...selected, id])}+ onRemove={(id) => onChange(visibility, selected.filter((value) => value !== id))} />+ </PopoverContent>+ </Popover>+ );+}diff --git a/packages/views/projects/components/project-detail.test.tsx b/packages/views/projects/components/project-detail.test.tsxindex 7720f28fd9..6fe7b3213b 100644--- a/packages/views/projects/components/project-detail.test.tsx+++ b/packages/views/projects/components/project-detail.test.tsx@@ -130,14 +130,6 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({DropdownMenuSeparator: () => <hr />,}));-vi.mock("@multica/ui/components/ui/popover", () => ({- Popover: ({ children }: { children: React.ReactNode }) => <>{children}</>,- PopoverTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,- PopoverContent: ({ children }: { children: React.ReactNode }) => (- <div>{children}</div>- ),-}));-vi.mock("@multica/ui/components/ui/tooltip", () => ({Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,@@ -307,6 +299,25 @@ describe("ProjectDetail rename", () => {});});+describe("ProjectDetail lead permissions", () => {+ it("does not let ordinary members change the lead of a private project", async () => {+ mocks.role = "member";+ qc.setQueryData(projectKeys.detail("workspace-1", PROJECT.id), { ...PROJECT, visibility: "private" });+ renderProjectDetail();+ expect(screen.getByRole("button", { name: "No lead" })).toBeDisabled();+ await userEvent.click(screen.getByRole("button", { name: "No lead" }));+ expect(screen.queryByPlaceholderText("Assign lead...")).not.toBeInTheDocument();+ });++ it("keeps the lead of a workspace project editable for ordinary members", async () => {+ mocks.role = "member";+ renderProjectDetail();+ expect(screen.getByRole("button", { name: "No lead" })).toBeEnabled();+ await userEvent.click(screen.getByRole("button", { name: "No lead" }));+ expect(screen.getByPlaceholderText("Assign lead...")).toBeInTheDocument();+ });+});+describe("ProjectDetail sharing", () => {it("copies the platform shareable URL instead of the renderer URL", async () => {const user = userEvent.setup();diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsxindex 35f2c3f14b..c16b9a4d3a 100644--- a/packages/views/projects/components/project-detail.tsx+++ b/packages/views/projects/components/project-detail.tsx@@ -10,7 +10,9 @@ import { copyText } from "@multica/ui/lib/clipboard";import { toast } from "sonner";import type { Project, ProjectStatus, ProjectPriority } from "@multica/core/types";import { useAuthStore } from "@multica/core/auth";+import { useConfigStore } from "@multica/core/config";import { canDeleteProject } from "@multica/core/projects/deletion-permissions";+import { canChangeProjectLead } from "@multica/core/projects/access";import { projectDetailOptions } from "@multica/core/projects/queries";import { Spinner } from "@multica/ui/components/ui/spinner";import { useUpdateProject, useDeleteProject, ProjectDeletionOfflineError } from "@multica/core/projects/mutations";@@ -32,6 +34,7 @@ import { PriorityIcon } from "../../issues/components/priority-icon";import { ProjectResourcesSection } from "./project-resources-section";import { ProjectStartDatePicker } from "./project-start-date-picker";import { ProjectDueDatePicker } from "./project-due-date-picker";+import { ProjectAccessControl } from "./project-access";import { ProjectWorkflowControl } from "../../workflows/project-workflow-row";import { ProjectWorkflowMenuHost } from "../../workflows/project-workflow-menu";import { IssueSurface } from "../../issues/surface/issue-surface";@@ -121,6 +124,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {const wsPaths = useWorkspacePaths();const router = useNavigation();const userId = useAuthStore((s) => s.user?.id);+ const privateProjectsEnabled = useConfigStore((s) => s.featureFlags.private_projects_v1 === true);const deleteProject = useDeleteProject();const deleted = deleteProject.isSuccess && deleteProject.variables === projectId;const { data: project, isLoading } = useQuery({@@ -159,6 +163,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {});const isPinned = pinnedItems.some((p) => p.item_type === "project" && p.item_id === projectId);const role = members.find((m) => m.user_id === userId)?.role ?? null;+ const canManageAccess = !!project && canChangeProjectLead(project, userId, role);const canDelete = !!project && canDeleteProject(project, userId ?? null, role, agents);const createPin = useCreatePin();const deletePinMut = useDeletePin();@@ -376,9 +381,13 @@ export function ProjectDetail({ projectId }: { projectId: string }) {</DropdownMenuContent></DropdownMenu></PropRow>+ {(privateProjectsEnabled || project.visibility === "private") && <PropRow label={t(($) => $.access.label)}>+ <ProjectAccessControl project={project} />+ </PropRow>}<PropRow label={t(($) => $.table.lead)}>- <Popover open={leadOpen} onOpenChange={(v) => { setLeadOpen(v); if (!v) setLeadFilter(""); }}>+ <Popover open={leadOpen && canManageAccess} onOpenChange={(v) => { setLeadOpen(v); if (!v) setLeadFilter(""); }}><PopoverTrigger+ disabled={!canManageAccess}render={<button type="button" className="inline-flex items-center gap-1.5 text-caption hover:text-foreground transition-colors">{project.lead_type && project.lead_id ? (diff --git a/packages/views/projects/components/project-lead-picker.tsx b/packages/views/projects/components/project-lead-picker.tsxindex 78076ec8f5..8b435547f2 100644--- a/packages/views/projects/components/project-lead-picker.tsx+++ b/packages/views/projects/components/project-lead-picker.tsx@@ -5,6 +5,8 @@ import { UserMinus } from "@multica/ui/icons";import { useQuery } from "@tanstack/react-query";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";import { useWorkspaceId } from "@multica/core/hooks";+import { useAuthStore } from "@multica/core/auth";+import { canChangeProjectLead } from "@multica/core/projects/access";import { useActorName } from "@multica/core/workspace/hooks";import { Popover, PopoverContent, PopoverTrigger } from "@multica/ui/components/ui/popover";import type { Project, UpdateProjectRequest } from "@multica/core/types";@@ -23,6 +25,8 @@ export function ProjectLeadPicker({ project, handleUpdate, renderTrigger, alignconst { getActorName } = useActorName();const { data: members = [] } = useQuery(memberListOptions(wsId));const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const userId = useAuthStore((s) => s.user?.id);+ const canManage = canChangeProjectLead(project, userId, members.find((m) => m.user_id === userId)?.role);const [leadOpen, setLeadOpen] = useState(false);const [leadFilter, setLeadFilter] = useState("");@@ -36,8 +40,8 @@ export function ProjectLeadPicker({ project, handleUpdate, renderTrigger, alignconst leadName = leadId && leadType ? getActorName(leadType, leadId) : null;return (- <Popover open={leadOpen} onOpenChange={(v) => { setLeadOpen(v); if (!v) setLeadFilter(""); }}>- <PopoverTrigger render={renderTrigger(leadName)} />+ <Popover open={leadOpen && canManage} onOpenChange={(v) => { setLeadOpen(v); if (!v) setLeadFilter(""); }}>+ <PopoverTrigger disabled={!canManage} render={renderTrigger(leadName)} /><PopoverContent align={align} className="w-52 p-0"><div className="px-2 py-1.5 border-b"><inputdiff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 83b62187bc..14710c9254 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "632_project_member_user_idx": "idx_project_member_workspace_user","628_app_action_request_chat_idx": "idx_app_action_request_chat","627_app_tool_call_issue_idx": "idx_app_tool_call_issue","626_app_action_request_task_idx": "idx_app_action_request_task",diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.goindex 50036d1208..0f9332ecf3 100644--- a/server/cmd/multica/cmd_project.go+++ b/server/cmd/multica/cmd_project.go@@ -8,6 +8,7 @@ import ("os""strings"+ "github.com/google/uuid""github.com/spf13/cobra""github.com/multica-ai/multica/server/internal/cli"@@ -91,6 +92,43 @@ var projectResourceRemoveCmd = &cobra.Command{RunE: runProjectResourceRemove,}+var projectMemberCmd = &cobra.Command{+ Use: "member",+ Short: "Manage the members of a private project",+}++var projectMemberListCmd = &cobra.Command{+ Use: "list <project-id>",+ Short: "List a project's members",+ Args: exactArgs(1),+ RunE: runProjectMemberList,+}++var projectMemberAddCmd = &cobra.Command{+ Use: "add <project-id> <member>...",+ Short: "Add workspace members to a project (name, email or user id)",+ Args: cobra.MinimumNArgs(2),+ RunE: runProjectMemberAdd,+}++var projectMemberRemoveCmd = &cobra.Command{+ Use: "remove <project-id> <member>",+ Short: "Remove a member from a project (name, email or user id)",+ Args: exactArgs(2),+ RunE: runProjectMemberRemove,+}++var validProjectVisibilities = []string{"workspace", "private"}++func validateProjectVisibility(v string) error {+ for _, allowed := range validProjectVisibilities {+ if v == allowed {+ return nil+ }+ }+ return fmt.Errorf("invalid visibility %q; valid values: %s", v, strings.Join(validProjectVisibilities, ", "))+}+var validProjectStatuses = []string{"planned", "in_progress", "paused", "completed", "cancelled",}@@ -121,6 +159,13 @@ func init() {projectResourceCmd.AddCommand(projectResourceUpdateCmd)projectResourceCmd.AddCommand(projectResourceRemoveCmd)+ projectCmd.AddCommand(projectMemberCmd)+ projectMemberCmd.AddCommand(projectMemberListCmd)+ projectMemberCmd.AddCommand(projectMemberAddCmd)+ projectMemberCmd.AddCommand(projectMemberRemoveCmd)+ projectMemberListCmd.Flags().String("output", "table", "Output format: table or json")+ projectMemberAddCmd.Flags().String("output", "table", "Output format: table or json")+// project listprojectListCmd.Flags().String("output", "table", "Output format: table or json")projectListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")@@ -138,6 +183,8 @@ func init() {projectCreateCmd.Flags().String("start-date", "", "Start date (calendar day, YYYY-MM-DD)")projectCreateCmd.Flags().String("due-date", "", "Due date (calendar day, YYYY-MM-DD)")projectCreateCmd.Flags().StringArray("repo", nil, "Attach a github_repo resource by URL (may be repeated)")+ projectCreateCmd.Flags().String("visibility", "", "Who can see the project: workspace (default) or private")+ projectCreateCmd.Flags().StringArray("member", nil, "Member of a private project (name, email or user id; may be repeated). You are always added")projectCreateCmd.Flags().String("output", "json", "Output format: table or json")// project resource list@@ -184,6 +231,8 @@ func init() {projectUpdateCmd.Flags().String("lead", "", "New lead name (member or agent)")projectUpdateCmd.Flags().String("start-date", "", "New start date (calendar day, YYYY-MM-DD; pass empty string to clear)")projectUpdateCmd.Flags().String("due-date", "", "New due date (calendar day, YYYY-MM-DD; pass empty string to clear)")+ projectUpdateCmd.Flags().String("visibility", "", "Switch visibility: workspace or private")+ projectUpdateCmd.Flags().StringArray("member", nil, "Members to add when switching to private (name, email or user id; may be repeated)")projectUpdateCmd.Flags().String("output", "json", "Output format: table or json")// project delete@@ -342,6 +391,9 @@ func runProjectCreate(cmd *cobra.Command, _ []string) error {if v, _ := cmd.Flags().GetString("due-date"); v != "" {body["due_date"] = v}+ if err := applyProjectVisibilityFlags(ctx, cmd, client, body); err != nil {+ return err+ }// Bundle resources into the create payload so the server attaches them in// the same transaction; this avoids leaving a half-attached project on@@ -437,9 +489,12 @@ func runProjectUpdate(cmd *cobra.Command, args []string) error {v, _ := cmd.Flags().GetString("due-date")body["due_date"] = v}+ if err := applyProjectVisibilityFlags(ctx, cmd, client, body); err != nil {+ return err+ }if len(body) == 0 {- return fmt.Errorf("no fields to update; use flags like --title, --status, --description, --icon, --lead, --start-date, --due-date")+ return fmt.Errorf("no fields to update; use flags like --title, --status, --description, --icon, --lead, --start-date, --due-date, --visibility")}var result map[string]any@@ -979,3 +1034,135 @@ func formatLead(project map[string]any, actors actorDisplayLookup) string {}return actors.actor(lType, lID)}++// applyProjectVisibilityFlags maps --visibility / --member onto a project+// create or update body.+func applyProjectVisibilityFlags(ctx context.Context, cmd *cobra.Command, client *cli.APIClient, body map[string]any) error {+ visibility, _ := cmd.Flags().GetString("visibility")+ members, _ := cmd.Flags().GetStringArray("member")+ if visibility == "" {+ if len(members) > 0 {+ return fmt.Errorf("--member requires --visibility private")+ }+ return nil+ }+ if err := validateProjectVisibility(visibility); err != nil {+ return err+ }+ body["visibility"] = visibility+ if len(members) == 0 {+ return nil+ }+ if visibility != "private" {+ return fmt.Errorf("--member requires --visibility private")+ }+ ids, err := resolveProjectMemberUserIDs(ctx, client, members)+ if err != nil {+ return err+ }+ body["member_ids"] = ids+ return nil+}++// resolveProjectMemberUserIDs turns member names, emails or user ids into+// user ids. Only workspace members qualify.+func resolveProjectMemberUserIDs(ctx context.Context, client *cli.APIClient, refs []string) ([]string, error) {+ ids := make([]string, 0, len(refs))+ for _, ref := range refs {+ ref = strings.TrimSpace(ref)+ if ref == "" {+ continue+ }+ if _, err := uuid.Parse(ref); err == nil {+ ids = append(ids, ref)+ continue+ }+ _, id, err := resolveAssignee(ctx, client, ref, memberOnlyKinds)+ if err != nil {+ return nil, fmt.Errorf("resolve member %q: %w", ref, err)+ }+ ids = append(ids, id)+ }+ return ids, nil+}++func printProjectMembers(cmd *cobra.Command, result map[string]any) error {+ output, _ := cmd.Flags().GetString("output")+ if output != "table" {+ return cli.PrintJSON(os.Stdout, result)+ }+ members, _ := result["members"].([]any)+ headers := []string{"USER ID", "NAME", "EMAIL"}+ rows := make([][]string, 0, len(members))+ for _, raw := range members {+ m, _ := raw.(map[string]any)+ rows = append(rows, []string{strVal(m, "user_id"), strVal(m, "name"), strVal(m, "email")})+ }+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}++func runProjectMemberList(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ var result map[string]any+ if err := client.GetJSON(ctx, "/api/projects/"+projectRef.ID+"/members", &result); err != nil {+ return fmt.Errorf("list project members: %w", err)+ }+ return printProjectMembers(cmd, result)+}++func runProjectMemberAdd(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ ids, err := resolveProjectMemberUserIDs(ctx, client, args[1:])+ if err != nil {+ return err+ }+ var result map[string]any+ if err := client.PostJSON(ctx, "/api/projects/"+projectRef.ID+"/members", map[string]any{"user_ids": ids}, &result); err != nil {+ return fmt.Errorf("add project members: %w", err)+ }+ return printProjectMembers(cmd, result)+}++func runProjectMemberRemove(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()+ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ ids, err := resolveProjectMemberUserIDs(ctx, client, args[1:2])+ if err != nil {+ return err+ }+ if len(ids) == 0 {+ return fmt.Errorf("member is required")+ }+ if err := client.DeleteJSON(ctx, "/api/projects/"+projectRef.ID+"/members/"+ids[0]); err != nil {+ return fmt.Errorf("remove project member: %w", err)+ }+ fmt.Fprintf(os.Stderr, "Removed %s from project %s.\n", args[1], projectRef.ID)+ return nil+}diff --git a/server/cmd/multica/cmd_project_member_test.go b/server/cmd/multica/cmd_project_member_test.gonew file mode 100644index 0000000000..ff3b9b97b0--- /dev/null+++ b/server/cmd/multica/cmd_project_member_test.go@@ -0,0 +1,80 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++func newProjectCreateVisibilityTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "create"}+ for _, name := range []string{"title", "description", "status", "icon", "lead", "start-date", "due-date", "visibility"} {+ cmd.Flags().String(name, "", "")+ }+ cmd.Flags().StringArray("repo", nil, "")+ cmd.Flags().StringArray("member", nil, "")+ cmd.Flags().String("output", "json", "")+ return cmd+}++func TestRunProjectCreateSendsVisibilityAndMembers(t *testing.T) {+ const memberID = "33333333-3333-3333-3333-333333333333"+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/projects" || r.Method != http.MethodPost {+ http.NotFound(w, r)+ return+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode body: %v", err)+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "p-1", "title": body["title"], "visibility": body["visibility"]})+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ cmd := newProjectCreateVisibilityTestCmd()+ _ = cmd.Flags().Set("title", "Client A")+ _ = cmd.Flags().Set("visibility", "private")+ _ = cmd.Flags().Set("member", memberID)+ if err := runProjectCreate(cmd, nil); err != nil {+ t.Fatalf("runProjectCreate: %v", err)+ }+ if body["visibility"] != "private" {+ t.Fatalf("visibility = %#v", body["visibility"])+ }+ ids, _ := body["member_ids"].([]any)+ if len(ids) != 1 || ids[0] != memberID {+ t.Fatalf("member_ids = %#v", body["member_ids"])+ }+}++func TestProjectVisibilityFlagValidation(t *testing.T) {+ for _, tc := range []struct {+ visibility string+ member string+ wantErr string+ }{+ {"secret", "", "invalid visibility"},+ {"", "33333333-3333-3333-3333-333333333333", "--member requires --visibility private"},+ {"workspace", "33333333-3333-3333-3333-333333333333", "--member requires --visibility private"},+ } {+ cmd := newProjectCreateVisibilityTestCmd()+ if tc.visibility != "" {+ _ = cmd.Flags().Set("visibility", tc.visibility)+ }+ if tc.member != "" {+ _ = cmd.Flags().Set("member", tc.member)+ }+ err := applyProjectVisibilityFlags(t.Context(), cmd, nil, map[string]any{})+ if err == nil || !strings.Contains(err.Error(), tc.wantErr) {+ t.Errorf("visibility=%q member=%q: err = %v, want %q", tc.visibility, tc.member, err, tc.wantErr)+ }+ }+}diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 48ce90cd57..3c61af80fc 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -1,6 +1,7 @@package mainimport (+ "context""encoding/json""fmt""log/slog"@@ -98,7 +99,15 @@ var memberPrivateEvents = map[string]bool{// for a Redis-backed relay or a feature-flagged dual-write implementation// without touching any of the event listeners below. This is Phase 0 of the// horizontal-scaling plan tracked in MUL-1138.-func registerListeners(bus *events.Bus, b realtime.Broadcaster) {+//+// audience, when given, narrows events about private projects (MUL-8472) to+// their members and workspace owners/admins; see privateProjectAudience.+func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...privateProjectAudience) {+ var projectAudience privateProjectAudience+ if len(audience) > 0 {+ projectAudience = audience[0]+ }+// Personal events should NOT be broadcast to the whole workspace.personalEvents := map[string]bool{protocol.EventInboxNew: true,@@ -305,6 +314,23 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {return}+ if projectAudience != nil && e.WorkspaceID != "" {+ ctx, cancel := context.WithTimeout(context.Background(), audienceResolveTimeout)+ recipients, private, err := projectAudience.Audience(ctx, e)+ cancel()+ if err != nil {+ logAudienceFailure(e, err)+ return+ }+ if private {+ realtime.M.RecordEvent(e.Type)+ for _, userID := range recipients {+ b.BroadcastToScope(realtime.ScopeWorkspaceMember, realtime.WorkspaceMemberScopeID(e.WorkspaceID, userID), data)+ }+ return+ }+ }+// Phase 1 (MUL-1138): the per-resource scope routing for high-frequency// task/chat events is intentionally NOT enabled yet. The server-side// pieces — Hub.subscribe/unsubscribe protocol, ScopeAuthorizer, Redisdiff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 781635ca5b..403c6ebf24 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -602,7 +602,7 @@ func main() {channelLeaseRedis = newNamedRedisClient(opts, "channel-lease")}}- registerListeners(bus, broadcaster)+ registerListeners(bus, broadcaster, newPrivateProjectAudience(db.New(pool)))analyticsClient := analytics.NewFromEnv()defer analyticsClient.Close()diff --git a/server/cmd/server/private_project_realtime.go b/server/cmd/server/private_project_realtime.gonew file mode 100644index 0000000000..9559408cd6--- /dev/null+++ b/server/cmd/server/private_project_realtime.go@@ -0,0 +1,306 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "strings"+ "sync"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// privateProjectAudience narrows realtime fanout for events about a private+// project (MUL-8472): the project itself, its resources, its issues, their+// comments and their runs reach only project members and workspace+// owners/admins. Every other event keeps workspace fanout, and so does an+// event whose project cannot be resolved (a deleted issue's id, a+// workspace-level object): narrowing anything wider is how #9133 silenced+// realtime for whole workspaces.+type privateProjectAudience interface {+ // Audience reports whether e belongs to a private project and, if so, the+ // user ids that may receive it. err means the decision could not be made;+ // the caller drops the event rather than widen it.+ Audience(ctx context.Context, e events.Event) (userIDs []string, private bool, err error)+}++type audienceQuerier interface {+ ListPrivateProjectAudience(ctx context.Context, workspaceID pgtype.UUID) ([]db.ListPrivateProjectAudienceRow, error)+ ListWorkspaceManagerUserIDs(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error)+ GetIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)+ GetCommentIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)+ GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)+}++// dbPrivateProjectAudience caches each workspace's private projects and their+// audience for audienceTTL. Producers run on the replica that handles the+// write, which invalidates its own cache on project and member events; other+// replicas converge within the TTL.+type dbPrivateProjectAudience struct {+ q audienceQuerier+ ttl time.Duration+ now func() time.Time++ mu sync.Mutex+ workspaces map[string]workspaceAudience+}++type workspaceAudience struct {+ loadedAt time.Time+ // projects maps a private project id to its member user ids.+ projects map[string][]string+ managers []string+}++const (+ audienceTTL = 2 * time.Second+ audienceResolveTimeout = 2 * time.Second+)++func newPrivateProjectAudience(q audienceQuerier) *dbPrivateProjectAudience {+ return &dbPrivateProjectAudience{q: q, ttl: audienceTTL, now: time.Now, workspaces: map[string]workspaceAudience{}}+}++// audienceInvalidatingEvents change who may see a private project.+func audienceInvalidatingEvent(eventType string) bool {+ return strings.HasPrefix(eventType, "project:") || strings.HasPrefix(eventType, "member:")+}++// workspaceVisibleTaskEvents carry only ids and status (task:failed has its+// error stripped by projectOutbound), and every member's agent presence,+// workload and run-history views refresh on them, so they keep workspace+// fanout for runs on private issues too. task:message and task:progress+// carry run content and stay narrowed.+var workspaceVisibleTaskEvents = map[string]bool{+ protocol.EventTaskQueued: true,+ protocol.EventTaskCoalesced: true,+ protocol.EventTaskDispatch: true,+ protocol.EventTaskRunning: true,+ protocol.EventTaskWaitingLocalDirectory: true,+ protocol.EventTaskUsage: true,+ protocol.EventTaskCompleted: true,+ protocol.EventTaskFailed: true,+ protocol.EventTaskCancelled: true,+}++func (a *dbPrivateProjectAudience) Audience(ctx context.Context, e events.Event) ([]string, bool, error) {+ if e.WorkspaceID == "" || workspaceVisibleTaskEvents[e.Type] {+ return nil, false, nil+ }+ if audienceInvalidatingEvent(e.Type) {+ a.mu.Lock()+ delete(a.workspaces, e.WorkspaceID)+ a.mu.Unlock()+ }+ ws, err := a.workspace(ctx, e.WorkspaceID)+ if err != nil {+ return nil, false, err+ }+ if len(ws.projects) == 0 {+ return nil, false, nil+ }+ projectID, err := a.eventProjectID(ctx, e)+ if err != nil {+ return nil, false, err+ }+ members, private := ws.projects[projectID]+ if !private {+ return nil, false, nil+ }+ seen := make(map[string]struct{}, len(members)+len(ws.managers))+ out := make([]string, 0, len(members)+len(ws.managers))+ for _, ids := range [][]string{ws.managers, members} {+ for _, id := range ids {+ if _, dup := seen[id]; dup {+ continue+ }+ seen[id] = struct{}{}+ out = append(out, id)+ }+ }+ return out, true, nil+}++func (a *dbPrivateProjectAudience) workspace(ctx context.Context, workspaceID string) (workspaceAudience, error) {+ a.mu.Lock()+ cached, ok := a.workspaces[workspaceID]+ a.mu.Unlock()+ if ok && a.now().Sub(cached.loadedAt) < a.ttl {+ return cached, nil+ }+ wsUUID, err := util.ParseUUID(workspaceID)+ if err != nil {+ return workspaceAudience{}, nil+ }+ rows, err := a.q.ListPrivateProjectAudience(ctx, wsUUID)+ if err != nil {+ return workspaceAudience{}, err+ }+ loaded := workspaceAudience{loadedAt: a.now(), projects: map[string][]string{}}+ for _, row := range rows {+ pid := util.UUIDToString(row.ProjectID)+ members := loaded.projects[pid]+ if row.UserID.Valid {+ members = append(members, util.UUIDToString(row.UserID))+ }+ loaded.projects[pid] = members+ }+ if len(loaded.projects) > 0 {+ managers, err := a.q.ListWorkspaceManagerUserIDs(ctx, wsUUID)+ if err != nil {+ return workspaceAudience{}, err+ }+ for _, id := range managers {+ loaded.managers = append(loaded.managers, util.UUIDToString(id))+ }+ }+ a.mu.Lock()+ a.workspaces[workspaceID] = loaded+ a.mu.Unlock()+ return loaded, nil+}++// eventProjectID resolves the project an event is about, or "" when it is+// about none. It reads the payload's own references first and only falls back+// to the database for a bare issue, comment or task id.+func (a *dbPrivateProjectAudience) eventProjectID(ctx context.Context, e events.Event) (string, error) {+ refs := extractEventRefs(e.Type, e.Payload)+ if refs.projectKnown {+ return refs.projectID, nil+ }+ lookup := func(id string, get func(context.Context, pgtype.UUID) (pgtype.UUID, error)) (string, error) {+ uid, err := util.ParseUUID(id)+ if err != nil {+ return "", nil+ }+ projectID, err := get(ctx, uid)+ if errors.Is(err, pgx.ErrNoRows) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ return util.UUIDToString(projectID), nil+ }+ if refs.issueID != "" {+ return lookup(refs.issueID, a.q.GetIssueProjectID)+ }+ if refs.commentID != "" {+ return lookup(refs.commentID, a.q.GetCommentIssueProjectID)+ }+ if e.TaskID != "" && e.ChatSessionID == "" {+ taskUUID, err := util.ParseUUID(e.TaskID)+ if err != nil {+ return "", nil+ }+ task, err := a.q.GetAgentTask(ctx, taskUUID)+ if errors.Is(err, pgx.ErrNoRows) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ if !task.IssueID.Valid {+ return "", nil+ }+ return lookup(util.UUIDToString(task.IssueID), a.q.GetIssueProjectID)+ }+ return "", nil+}++type eventRefs struct {+ // projectKnown is set when the payload states the project outright,+ // including an issue that states it has none.+ projectKnown bool+ projectID string+ issueID string+ commentID string+}++// extractEventRefs reads project / issue / comment references from an event+// payload. Payloads are maps of handler response structs, so this goes+// through their JSON form, the shape clients receive.+func extractEventRefs(eventType string, payload any) eventRefs {+ var refs eventRefs+ raw, err := json.Marshal(payload)+ if err != nil {+ return refs+ }+ var top map[string]json.RawMessage+ if json.Unmarshal(raw, &top) != nil {+ return refs+ }+ str := func(m map[string]json.RawMessage, key string) (string, bool) {+ v, ok := m[key]+ if !ok {+ return "", false+ }+ var s *string+ if json.Unmarshal(v, &s) != nil {+ return "", false+ }+ if s == nil {+ return "", true+ }+ return *s, true+ }+ object := func(key string) map[string]json.RawMessage {+ var m map[string]json.RawMessage+ if v, ok := top[key]; ok {+ _ = json.Unmarshal(v, &m)+ }+ return m+ }+ isProjectEvent := strings.HasPrefix(eventType, "project:") || strings.HasPrefix(eventType, "project_resource:")+ if isProjectEvent {+ if p := object("project"); p != nil {+ if id, ok := str(p, "id"); ok && id != "" {+ return eventRefs{projectKnown: true, projectID: id}+ }+ }+ }+ if id, ok := str(top, "project_id"); ok && id != "" && (isProjectEvent || eventType == protocol.EventProjectMembersChanged) {+ return eventRefs{projectKnown: true, projectID: id}+ }+ if issue := object("issue"); issue != nil {+ if pid, ok := str(issue, "project_id"); ok {+ return eventRefs{projectKnown: true, projectID: pid}+ }+ if id, ok := str(issue, "id"); ok {+ refs.issueID = id+ }+ }+ if refs.issueID == "" {+ if id, ok := str(top, "issue_id"); ok {+ refs.issueID = id+ }+ }+ if refs.issueID == "" {+ if c := object("comment"); c != nil {+ if id, ok := str(c, "issue_id"); ok && id != "" {+ refs.issueID = id+ } else if id, ok := str(c, "id"); ok {+ refs.commentID = id+ }+ }+ }+ if refs.issueID == "" && refs.commentID == "" {+ if id, ok := str(top, "comment_id"); ok {+ refs.commentID = id+ }+ }+ return refs+}++func logAudienceFailure(e events.Event, err error) {+ slog.Warn("realtime: dropping event, private project audience unresolved",+ "event_type", e.Type, "workspace_id", e.WorkspaceID, "task_id", e.TaskID, "error", err)+}diff --git a/server/cmd/server/private_project_realtime_test.go b/server/cmd/server/private_project_realtime_test.gonew file mode 100644index 0000000000..24a8319cdf--- /dev/null+++ b/server/cmd/server/private_project_realtime_test.go@@ -0,0 +1,171 @@+package main++import (+ "context"+ "errors"+ "sort"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++const (+ ppWorkspace = "00000000-0000-0000-0000-0000000000a1"+ ppPrivate = "00000000-0000-0000-0000-0000000000b1"+ ppPublic = "00000000-0000-0000-0000-0000000000b2"+ ppMember = "00000000-0000-0000-0000-0000000000c1"+ ppAdmin = "00000000-0000-0000-0000-0000000000c2"+ ppSecretIssue = "00000000-0000-0000-0000-0000000000d1"+ ppPublicIssue = "00000000-0000-0000-0000-0000000000d2"+ ppSecretTask = "00000000-0000-0000-0000-0000000000e1"+ ppSecretComment = "00000000-0000-0000-0000-0000000000f1"+)++type fakeAudienceQuerier struct {+ fail bool+}++func ppUUID(s string) pgtype.UUID {+ id, err := util.ParseUUID(s)+ if err != nil {+ panic(err)+ }+ return id+}++func (f fakeAudienceQuerier) ListPrivateProjectAudience(context.Context, pgtype.UUID) ([]db.ListPrivateProjectAudienceRow, error) {+ if f.fail {+ return nil, errors.New("db down")+ }+ return []db.ListPrivateProjectAudienceRow{{ProjectID: ppUUID(ppPrivate), UserID: ppUUID(ppMember)}}, nil+}++func (fakeAudienceQuerier) ListWorkspaceManagerUserIDs(context.Context, pgtype.UUID) ([]pgtype.UUID, error) {+ return []pgtype.UUID{ppUUID(ppAdmin)}, nil+}++func (fakeAudienceQuerier) GetIssueProjectID(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ switch util.UUIDToString(id) {+ case ppSecretIssue:+ return ppUUID(ppPrivate), nil+ case ppPublicIssue:+ return ppUUID(ppPublic), nil+ }+ return pgtype.UUID{}, pgx.ErrNoRows+}++func (fakeAudienceQuerier) GetCommentIssueProjectID(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ if util.UUIDToString(id) == ppSecretComment {+ return ppUUID(ppPrivate), nil+ }+ return pgtype.UUID{}, pgx.ErrNoRows+}++func (fakeAudienceQuerier) GetAgentTask(_ context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {+ if util.UUIDToString(id) == ppSecretTask {+ return db.AgentTaskQueue{ID: id, IssueID: ppUUID(ppSecretIssue)}, nil+ }+ return db.AgentTaskQueue{}, pgx.ErrNoRows+}++func privateAudienceScopes(fb *fakeBroadcaster) []string {+ fb.mu.Lock()+ defer fb.mu.Unlock()+ var out []string+ for _, c := range fb.scopeCalls {+ if c.scopeType == realtime.ScopeWorkspaceMember {+ out = append(out, c.scopeID)+ }+ }+ sort.Strings(out)+ return out+}++func TestRegisterListeners_PrivateProjectEventsReachOnlyItsAudience(t *testing.T) {+ want := []string{+ realtime.WorkspaceMemberScopeID(ppWorkspace, ppMember),+ realtime.WorkspaceMemberScopeID(ppWorkspace, ppAdmin),+ }+ sort.Strings(want)+ private := []events.Event{+ {Type: protocol.EventIssueUpdated, Payload: map[string]any{"issue": map[string]any{"id": ppSecretIssue, "project_id": ppPrivate}}},+ {Type: protocol.EventIssueUpdated, Payload: map[string]any{"issue_id": ppSecretIssue}},+ {Type: protocol.EventCommentCreated, Payload: map[string]any{"comment": map[string]any{"id": ppSecretComment, "issue_id": ppSecretIssue}}},+ {Type: protocol.EventProjectUpdated, Payload: map[string]any{"project": map[string]any{"id": ppPrivate}}},+ {Type: protocol.EventProjectMembersChanged, Payload: map[string]any{"project_id": ppPrivate}},+ {Type: protocol.EventTaskMessage, TaskID: ppSecretTask, Payload: map[string]any{"task_id": ppSecretTask}},+ }+ for _, e := range private {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))+ e.WorkspaceID = ppWorkspace+ bus.Publish(e)+ if len(fb.workspaceCalls) != 0 {+ t.Errorf("%s %v: broadcast to the whole workspace", e.Type, e.Payload)+ }+ if got := privateAudienceScopes(fb); len(got) != 2 || got[0] != want[0] || got[1] != want[1] {+ t.Errorf("%s %v: delivered to %v, want %v", e.Type, e.Payload, got, want)+ }+ }++ public := []events.Event{+ {Type: protocol.EventIssueUpdated, Payload: map[string]any{"issue": map[string]any{"id": ppPublicIssue, "project_id": nil}}},+ {Type: protocol.EventIssueUpdated, Payload: map[string]any{"issue_id": ppPublicIssue}},+ // A deleted issue cannot be resolved: keep fanout, never go silent.+ {Type: protocol.EventIssueDeleted, Payload: map[string]any{"issue_id": "00000000-0000-0000-0000-00000000dead"}},+ {Type: protocol.EventAgentStatus, Payload: map[string]any{"agent_id": "a"}},+ }+ for _, e := range public {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))+ e.WorkspaceID = ppWorkspace+ bus.Publish(e)+ if len(fb.workspaceCalls) != 1 {+ t.Errorf("%s %v: workspace broadcasts = %d, want 1", e.Type, e.Payload, len(fb.workspaceCalls))+ }+ }+}++func TestRegisterListeners_PrivateProjectAudienceFailureDropsEvent(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{fail: true}))+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: ppWorkspace, Payload: map[string]any{"issue_id": ppSecretIssue}})+ if len(fb.workspaceCalls) != 0 || len(privateAudienceScopes(fb)) != 0 {+ t.Fatalf("an unresolved audience must drop the event, got workspace=%d scoped=%v", len(fb.workspaceCalls), privateAudienceScopes(fb))+ }+}++func TestRegisterListeners_PrivateTaskLifecycleKeepsWorkspaceFanout(t *testing.T) {+ for _, eventType := range []string{+ protocol.EventTaskQueued, protocol.EventTaskDispatch, protocol.EventTaskRunning,+ protocol.EventTaskCompleted, protocol.EventTaskFailed, protocol.EventTaskCancelled,+ } {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))+ bus.Publish(events.Event{Type: eventType, WorkspaceID: ppWorkspace, TaskID: ppSecretTask,+ Payload: map[string]any{"task_id": ppSecretTask, "issue_id": ppSecretIssue, "agent_id": "agent", "status": "x"}})+ if len(fb.workspaceCalls) != 1 || len(privateAudienceScopes(fb)) != 0 {+ t.Errorf("%s: workspace=%d scoped=%v; lifecycle events must reach every member", eventType, len(fb.workspaceCalls), privateAudienceScopes(fb))+ }+ }+ // Run content stays with the project audience.+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))+ bus.Publish(events.Event{Type: protocol.EventTaskProgress, WorkspaceID: ppWorkspace, TaskID: ppSecretTask,+ Payload: protocol.TaskProgressPayload{TaskID: ppSecretTask, Summary: "secret step"}})+ if len(fb.workspaceCalls) != 0 || len(privateAudienceScopes(fb)) != 2 {+ t.Errorf("task:progress: workspace=%d scoped=%v; want only the project audience", len(fb.workspaceCalls), privateAudienceScopes(fb))+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 816786c76d..36cb356aa7 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2256,6 +2256,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/", h.UpdateProject)r.Delete("/", h.DeleteProject)r.Post("/workflow", h.SetProjectWorkflow)+ r.Get("/members", h.ListProjectMembers)+ r.Post("/members", h.AddProjectMembers)+ r.Delete("/members/{userId}", h.RemoveProjectMember)r.Get("/resources", h.ListProjectResources)r.Post("/resources", h.CreateProjectResource)r.Put("/resources/{resourceId}", h.UpdateProjectResource)diff --git a/server/cmd/server/task_dispatch_test.go b/server/cmd/server/task_dispatch_test.gonew file mode 100644index 0000000000..d48a5cf008--- /dev/null+++ b/server/cmd/server/task_dispatch_test.go@@ -0,0 +1,106 @@+package main++import (+ "context"+ "encoding/json"+ "reflect"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/service"+ "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"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func requireWorkspaceDispatchPayload(t *testing.T, fb *fakeBroadcaster, want map[string]string) {+ t.Helper()+ found := 0+ for _, call := range fb.workspaceCalls {+ var frame struct {+ Type string `json:"type"`+ Payload map[string]any `json:"payload"`+ }+ if err := json.Unmarshal(call.msg, &frame); err != nil {+ t.Fatal(err)+ }+ if frame.Type != protocol.EventTaskDispatch {+ continue+ }+ found+++ expected := make(map[string]any, len(want))+ for key, value := range want {+ expected[key] = value+ }+ if !reflect.DeepEqual(frame.Payload, expected) {+ t.Errorf("workspace dispatch payload = %v, want only routing ids %v", frame.Payload, expected)+ }+ }+ if found != 1 {+ t.Fatalf("workspace dispatch events = %d, want 1", found)+ }+}++func TestPrivateProjectQuickCreateDispatchOmitsPrompt(t *testing.T) {+ ctx := context.Background()+ fx := testutil.New(testPool, testWorkspaceID, testUserID)+ project := fx.Project(t, "Private client project", testutil.Cols{"visibility": "private"})+ runtime := fx.Runtime(t, "Dispatch runtime")+ agent := fx.Agent(t, "Dispatch agent", runtime)+ q := db.New(testPool)+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(q))+ tasks := service.NewTaskService(q, testPool, nil, bus)+ const prompt = "Confidential client acquisition terms"+ task, err := tasks.EnqueueQuickCreateTask(ctx, ppUUID(testWorkspaceID), ppUUID(testUserID), ppUUID(agent), pgtype.UUID{}, prompt, "", "", ppUUID(project), pgtype.UUID{}, nil)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id=$1`, task.ID)+ })+ claimed, err := tasks.ClaimTask(ctx, ppUUID(agent))+ if err != nil || claimed == nil {+ t.Fatalf("claim: task=%v error=%v", claimed, err)+ }+ var taskContext service.QuickCreateContext+ if err := json.Unmarshal(claimed.Context, &taskContext); err != nil || taskContext.Prompt != prompt {+ t.Fatalf("claimed task must retain its prompt for the daemon: context=%s error=%v", claimed.Context, err)+ }+ requireWorkspaceDispatchPayload(t, fb, map[string]string{+ "task_id": util.UUIDToString(claimed.ID), "agent_id": agent, "runtime_id": runtime, "issue_id": "",+ })+}++func TestTaskDispatchKeepsIssueAndChatRoutingWithoutContext(t *testing.T) {+ for _, kind := range []string{"issue", "chat"} {+ t.Run(kind, func(t *testing.T) {+ ctx := context.Background()+ fx := testutil.New(testPool, testWorkspaceID, testUserID)+ runtime := fx.Runtime(t, "Dispatch runtime")+ agent := fx.Agent(t, "Dispatch agent", runtime)+ cols := testutil.Cols{"runtime_id": runtime, "context": `{"prompt":"private context","future_field":"private data"}`}+ want := map[string]string{"agent_id": agent, "runtime_id": runtime, "issue_id": ""}+ if kind == "issue" {+ issue := fx.Issue(t, "Dispatch issue")+ cols["issue_id"], want["issue_id"] = issue, issue+ } else {+ chat := fx.ChatSession(t, agent)+ cols["chat_session_id"], want["chat_session_id"] = chat, chat+ }+ want["task_id"] = fx.Task(t, agent, cols)+ q := db.New(testPool)+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, newPrivateProjectAudience(q))+ tasks := service.NewTaskService(q, testPool, nil, bus)+ if claimed, err := tasks.ClaimTask(ctx, ppUUID(agent)); err != nil || claimed == nil {+ t.Fatalf("claim: task=%v error=%v", claimed, err)+ }+ requireWorkspaceDispatchPayload(t, fb, want)+ })+ }+}diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex d02911b3cc..e8a3d54099 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -89,6 +89,10 @@ const (// nothing is pending — the trigger is answered by accepting the issue out of// Triage, not by waiting.ReasonIssueInTriage ReasonCode = "issue_in_triage"+ // ReasonProjectAccessBlocked: the issue is in a private project that the+ // run's member or the agent's owner cannot access (MUL-8472). The caller+ // already sees the issue, so the code reveals nothing new about it.+ ReasonProjectAccessBlocked ReasonCode = "project_access_blocked"// ReasonQuotaExceeded is a policy-neutral refusal for an exhausted// Cloud-provided autopilot interval.ReasonQuotaExceeded ReasonCode = "quota_exceeded"diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.goindex bd24aa2122..de8bd8f4dd 100644--- a/server/internal/featureflags/keys.go+++ b/server/internal/featureflags/keys.go@@ -35,6 +35,11 @@ const (// makes those endpoints answer 404, so clients stop syncing and search// through the server again without a client release.LocalSearchIndex = "local_search_index"+ // PrivateProjectsV1 gates CREATING private projects (MUL-8472): a new+ // private project, or switching a project to private. It does not gate+ // enforcement: a project that is already private stays private when the+ // flag is off, and its members stay manageable. Off by default.+ PrivateProjectsV1 = "private_projects_v1"// agentBuilderCompat is no longer a release flag. Keep publishing the key// as enabled so installed desktop clients that still gate the AI creation// entry on this config decision receive the permanently enabled behavior.@@ -59,6 +64,7 @@ var frontendPublicFlags = []string{BillingWorkspaceSubscriptions,ComposioMCPApps,PluginsV1,+ PrivateProjectsV1,}func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {@@ -77,6 +83,10 @@ func TriageV1Enabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, TriageV1, false)}+func PrivateProjectsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {+ return flags.IsEnabled(ctx, PrivateProjectsV1, false)+}+func LocalSearchIndexEnabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, LocalSearchIndex, true)}diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.goindex 9d8ae503f5..a998a0fc1d 100644--- a/server/internal/handler/admission.go+++ b/server/internal/handler/admission.go@@ -68,6 +68,7 @@ const (ReasonAlreadyActive = dispatch.ReasonAlreadyActiveReasonSelfTriggerSuppressed = dispatch.ReasonSelfTriggerSuppressedReasonIssueInTriage = dispatch.ReasonIssueInTriage+ ReasonProjectAccessBlocked = dispatch.ReasonProjectAccessBlockedReasonInternalError = dispatch.ReasonInternalError)@@ -138,6 +139,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {return "a run is already active for this target"case ReasonIssueInTriage:return "the issue is in Triage and has no owner to run yet; accept it out of Triage first"+ case ReasonProjectAccessBlocked:+ return "the agent's owner is not a member of this private project"default:return "the run was blocked"}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex b65479bfd5..a2038a575b 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -397,6 +397,10 @@ type TaskCancellationActor struct {}type AgentTaskResponse struct {+ // Restricted marks a run on an issue in a private project the caller+ // cannot see (MUL-8472): only identity, status, timing and usage remain.+ Restricted bool `json:"restricted,omitempty"`+StartClaimSupported bool `json:"start_claim_supported,omitempty"`CancelledByCommentChange bool `json:"cancelled_by_comment_change,omitempty"`CancelledBy *TaskCancellationActor `json:"cancelled_by,omitempty"`@@ -3042,6 +3046,11 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {return}h.hydrateTaskSupplementMetadata(r.Context(), r, agent.WorkspaceID, tasks, resp)+ if err := h.redactHiddenProjectTasks(r, workspaceID, tasks, resp); err != nil {+ slog.Warn("list agent tasks: resolve project access failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to list agent tasks")+ return+ }h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))if includeUsage {if err := h.hydrateAgentTaskUsage(r.Context(), agent.ID, taskIDs, resp); err != nil {@@ -3343,6 +3352,11 @@ func (h *Handler) ListWorkspaceAgentTaskSnapshot(w http.ResponseWriter, r *http.writeError(w, http.StatusInternalServerError, "failed to list agent task snapshot")return}+ if err := h.redactHiddenProjectTasks(r, workspaceID, kept, resp); err != nil {+ slog.Warn("agent task snapshot: resolve project access failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to list agent task snapshot")+ return+ }h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))writeJSON(w, http.StatusOK, resp)diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 62374028df..59107f7d1e 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -1333,6 +1333,11 @@ func (h *Handler) parseAutopilotProjectID(writeError(w, http.StatusBadRequest, "project_id must reference a project in this workspace")return pgtype.UUID{}, false}+ // MUL-8472: an autopilot can only file into a private project its author+ // can see; its runs are then bounded by the rule owner's access.+ if !h.requireProjectVisible(w, r, uuidToString(workspaceID), projectID, http.StatusBadRequest, "project_id must reference a project in this workspace") {+ return pgtype.UUID{}, false+ }return projectID, true}diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex e3e0eff1f5..e5675cf07b 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -90,6 +90,9 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, "you do not have access to this agent")return}+ if !h.requireChatProjectVisible(w, r, workspaceID, projectID, agent.ID) {+ return+ }// Create inside a tx that first takes a FOR KEY SHARE lock on the workspace// row: it conflicts with DeleteWorkspace's FOR UPDATE, so a session cannot be@@ -413,6 +416,9 @@ func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireChatProjectVisible(w, r, workspaceID, projectID, session.AgentID) {+ return+ }}tx, txErr := h.TxStarter.Begin(r.Context())diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex a600a019c7..cb283de526 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -2307,6 +2307,9 @@ func commentEnqueueFailureReason(err error) DispatchReasonCode {if errors.Is(err, service.ErrAttributionFailClosed) {return ReasonAttributionBlocked}+ if errors.Is(err, service.ErrProjectAccessDenied) {+ return ReasonProjectAccessBlocked+ }return ReasonInternalError}@@ -3354,6 +3357,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}+ if !h.requireIssueIDVisible(w, r, workspaceID, existing.IssueID, http.StatusNotFound, "comment not found") {+ return+ }if bound, err := h.Queries.CommentHasTaskSupplement(r.Context(), db.CommentHasTaskSupplementParams{CommentID: existing.ID, WorkspaceID: wsUUID,}); err != nil {@@ -3634,6 +3640,9 @@ func (h *Handler) DeleteComment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}+ if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusNotFound, "comment not found") {+ return+ }member, ok := h.workspaceMember(w, r, workspaceID)if !ok {@@ -4054,6 +4063,9 @@ func (h *Handler) loadCommentForActor(w http.ResponseWriter, r *http.Request) (dwriteError(w, http.StatusNotFound, "comment not found")return db.Comment{}, "", "", "", false}+ if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusNotFound, "comment not found") {+ return db.Comment{}, "", "", "", false+ }actorType, actorID := h.resolveActor(r, userID, workspaceID)return comment, workspaceID, actorType, actorID, true}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 2a4f034ab9..c90161d461 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -6441,6 +6441,13 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {}}+ if scope == "subtree" {+ if err := h.redactHiddenProjectTasks(r, workspaceID, tasks, resp); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check project access")+ return+ }+ }+writeJSON(w, http.StatusOK, resp)}@@ -6609,6 +6616,12 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusNotFound, "task not found")return}+ // An issue run's transcript is visible exactly where its issue is+ // (MUL-8472). Task ids reach every member through task lifecycle events,+ // so this cannot rely on the issue page being unreachable.+ if !h.requireIssueIDVisible(w, r, wsID, task.IssueID, http.StatusNotFound, "task not found") {+ return+ }var (messages []db.TaskMessagediff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex cda64e73bc..f3e1eb2580 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -477,6 +477,9 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, "invalid issue_id")return}+ if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusForbidden, "invalid issue_id") {+ return+ }params.IssueID = issue.ID}if commentID := r.FormValue("comment_id"); commentID != "" {@@ -789,6 +792,9 @@ func (h *Handler) loadAttachmentForRequest(w http.ResponseWriter, r *http.RequeswriteError(w, http.StatusNotFound, "attachment not found")return db.Attachment{}, false}+ if !h.requireAttachmentVisible(w, r, workspaceID, att) {+ return db.Attachment{}, false+ }return att, true}@@ -833,6 +839,9 @@ func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Requereturn db.Attachment{}, false}if h.MembershipCache.Get(r.Context(), userID, workspaceID) {+ if !h.requireAttachmentVisible(w, r, workspaceID, att) {+ return db.Attachment{}, false+ }return att, true}if _, err := h.getWorkspaceMember(r.Context(), userID, workspaceID); err != nil {@@ -840,6 +849,9 @@ func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Requereturn db.Attachment{}, false}h.MembershipCache.Set(r.Context(), userID, workspaceID)+ if !h.requireAttachmentVisible(w, r, workspaceID, att) {+ return db.Attachment{}, false+ }return att, true}@@ -1377,6 +1389,9 @@ func (h *Handler) DeleteAttachment(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "attachment not found")return}+ if !h.requireAttachmentVisible(w, r, workspaceID, att) {+ return+ }// Captured-context attachments are immutable historical copies. They are// deleted only with their target issue, workspace, or abandoned context.if att.SourceContextID.Valid {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex d25850a77a..39c8350fac 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -1097,6 +1097,9 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issue// silently returns false for non-identifier strings, falling through to// the UUID path below.if issue, ok := h.resolveIssueByIdentifier(r.Context(), issueID, workspaceID); ok {+ if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusNotFound, "issue not found") {+ return db.Issue{}, false+ }return issue, true}@@ -1120,6 +1123,11 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issuewriteError(w, http.StatusNotFound, "issue not found")return db.Issue{}, false}+ // MUL-8472: an issue in a private project the caller cannot see does not+ // exist for them, on every route that loads it through here.+ if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusNotFound, "issue not found") {+ return db.Issue{}, false+ }return issue, true}diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 8afc44feb4..3867b10dad 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -195,10 +195,18 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {return}+ // Notifications about private-project issues are not written for+ // outsiders (CreateInboxItem); this read filter also drops older rows once+ // the reader loses access.+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }items, err := h.Queries.ListInboxItems(r.Context(), db.ListInboxItemsParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list inbox")@@ -233,10 +241,15 @@ func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {return}+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }items, err := h.Queries.ListArchivedInboxItems(r.Context(), db.ListArchivedInboxItemsParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list archived inbox")@@ -394,10 +407,15 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {return}+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }count, err := h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to count unread inbox")diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.goindex 3800cfc750..db6a6bcf63 100644--- a/server/internal/handler/inbox_archive.go+++ b/server/internal/handler/inbox_archive.go@@ -185,6 +185,14 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)p.BeforeTime = pgtype.Timestamptz{Time: before, Valid: true}}p.PageLimit = int32(limit + 1)+ // Filtered inside the query, before grouping and paging, so a hidden+ // notification neither shows up nor shortens a page. Not part of the+ // cursor scope: access can change between pages.+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(filters.WorkspaceID))+ if !ok {+ return+ }+ p.HiddenProjectIds = hidden.Param()rows, err := h.Queries.ListArchivedInboxPage(r.Context(), p)if err != nil {writeError(w, http.StatusInternalServerError, "failed to load archived inbox page")@@ -228,6 +236,11 @@ func (h *Handler) GetArchivedInboxFacets(w http.ResponseWriter, r *http.Request)if !ok {return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(p.WorkspaceID))+ if !ok {+ return+ }+ p.HiddenProjectIds = hidden.Param()rows, err := h.Queries.ArchivedInboxFacets(r.Context(), p)if err != nil {writeError(w, http.StatusInternalServerError, "failed to load archived inbox filters")diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 0c4fad7df3..a96dbc84f5 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -800,7 +800,7 @@ type searchResult struct {// case-insensitive LIKE semantics as the legacy query. The pipeline deliberately// trades the title, description, and comment content GIN fast paths for one// predictable pass over each relation within the selected workspace.-func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string, projectID pgtype.UUID) (string, []any) {+func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string, projectID pgtype.UUID, hiddenProjectIDs ...pgtype.UUID) (string, []any) {// Lowercase in Go so SQL only needs LOWER() on the column side.phrase = strings.ToLower(phrase)for i, term := range terms {@@ -838,6 +838,11 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,terminalStatusesParam = nextArg(terminalStatusKeys)}+ hiddenProjectsParam := ""+ if len(hiddenProjectIDs) > 0 {+ hiddenProjectsParam = nextArg(hiddenProjectIDs)+ }+// Bound before limit/offset so the handler's args[len-2]/args[len-1] fill// keeps landing on the pagination placeholders.projectParam := ""@@ -893,6 +898,11 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,if terminalStatusesParam != "" {issueWhere += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)}+ // Comment matches only reach the result through issue_matches, so this+ // one predicate also drops comments on hidden issues.+ if hiddenProjectsParam != "" {+ issueWhere += " AND " + hiddenProjectPredicate("i.project_id", hiddenProjectsParam)+ }// PostgreSQL otherwise inlines scalar LATERAL subqueries and recomputes the// LOWER expressions for every flag. The OFFSET 0 fences cache the normalized// title and description per issue row without materializing the whole CTE.@@ -1191,7 +1201,11 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {terminalStatusKeys = resolvedKeys}- sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, terminalStatusKeys, projectFilter)+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, terminalStatusKeys, projectFilter, hidden.Param()...)// Fill placeholder args: $4 = workspace_id, last two = limit, offsetargs[3] = wsUUIDargs[len(args)-2] = limit@@ -1416,6 +1430,10 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to resolve status categories")return}+ openHidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }issues, err := h.Queries.ListOpenIssues(ctx, db.ListOpenIssuesParams{WorkspaceID: wsUUID,TerminalStatusKeys: terminalStatusKeys,@@ -1427,6 +1445,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {InvolvesUserID: involvesUserFilter,MetadataFilter: metadataFilter,PropertiesFilter: openPropertiesFilter,+ HiddenProjectIds: openHidden.Param(),})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list issues")@@ -1584,6 +1603,13 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {args = append(args, v)return "$" + strconv.Itoa(len(args))}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ if ids := hidden.Param(); ids != nil {+ where = append(where, hiddenProjectPredicate("i.project_id", addArg(ids)))+ }if len(statusCategoriesFilter) > 0 {// Expanded to concrete status keys rather than filtered through// issue_effective_status(): wrapping the column in a function makes the@@ -2075,6 +2101,13 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {args = append(args, v)return "$" + strconv.Itoa(len(args))}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ if ids := hidden.Param(); ids != nil {+ where = append(where, hiddenProjectPredicate("i.project_id", addArg(ids)))+ }statuses := splitCommaParam(r.URL.Query().Get("statuses"))if len(statuses) == 0 {@@ -2568,6 +2601,11 @@ func (h *Handler) ListChildIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list child issues")return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(issue.WorkspaceID))+ if !ok {+ return+ }+ children = filterVisibleIssues(hidden, children)prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)ids := make([]pgtype.UUID, len(children))for i, child := range children {@@ -2654,6 +2692,11 @@ func (h *Handler) ListChildrenByParents(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to list child issues")return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ children = filterVisibleIssues(hidden, children)prefix := h.getIssuePrefix(r.Context(), wsUUID)ids := make([]pgtype.UUID, len(children))for i, child := range children {@@ -2930,6 +2973,9 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "project not found")return}+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), pid, http.StatusBadRequest, "project not found") {+ return+ }projectUUID = pid}@@ -2951,6 +2997,9 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")return}+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), parent.ProjectID, http.StatusBadRequest, "parent issue not found in this workspace") {+ return+ }parentIssueUUID = pid}@@ -2959,6 +3008,10 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {if writeIssueLimitReached(w, err) {return}+ if errors.Is(err, service.ErrProjectAccessDenied) {+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonProjectAccessBlocked)+ return+ }slog.Warn("quick-create enqueue failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to enqueue quick-create task")return@@ -3341,6 +3394,14 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {}projectID = id}+ // MUL-8472: an issue can only be filed into, or under a parent in, a+ // project the caller can see.+ if !h.requireProjectVisible(w, r, workspaceID, projectID, http.StatusBadRequest, "project not found in this workspace") {+ return+ }+ if !h.requireIssueIDVisible(w, r, workspaceID, parentIssueID, http.StatusBadRequest, "parent issue not found in this workspace") {+ return+ }// Project workflow (MUL-7420). A new issue in a project on a named// workflow must start on a status the workflow lists, and a column the@@ -3355,6 +3416,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {workflowProjectID = parent.ProjectID}}+ if !h.requireAssigneeCanAccessProject(w, r, wsUUID, assigneeType, assigneeID, workflowProjectID) {+ return+ }createWorkflow, createWorkflowProject, err := issueworkflow.ForProject(r.Context(), h.Queries, wsUUID, workflowProjectID)if err != nil {slog.Error("create issue: resolve project workflow", append(logger.RequestAttrs(r), "error", err)...)@@ -4016,13 +4080,17 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {return}// Validate parent exists in the same workspace.- if _, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ newParent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: newParentID,WorkspaceID: prevIssue.WorkspaceID,- }); err != nil {+ })+ if err != nil {writeError(w, http.StatusBadRequest, "parent issue not found in this workspace")return}+ if !h.requireProjectVisible(w, r, uuidToString(prevIssue.WorkspaceID), newParent.ProjectID, http.StatusBadRequest, "parent issue not found in this workspace") {+ return+ }// Cycle detection: walk up from the new parent to ensure we don't reach this issue.cursor := newParentIDfor depth := 0; depth < 10; depth++ {@@ -4060,6 +4128,9 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "project not found in this workspace")return}+ if !h.requireProjectVisible(w, r, uuidToString(prevIssue.WorkspaceID), projectUUID, http.StatusBadRequest, "project not found in this workspace") {+ return+ }params.ProjectID = projectUUID} else {params.ProjectID = pgtype.UUID{Valid: false}@@ -4114,6 +4185,11 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {return}}+ if _, projectTouched := rawFields["project_id"]; touchedType || touchedID || handoff != nil || projectTouched {+ if !h.requireAssigneeCanAccessProject(w, r, prevIssue.WorkspaceID, params.AssigneeType, params.AssigneeID, params.ProjectID) {+ return+ }+ }attachmentIDs, ok := parseUUIDSliceOrBadRequest(w, req.AttachmentIDs, "attachment_ids")if !ok {@@ -4776,6 +4852,9 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "project not found in this workspace")return}+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), projectUUID, http.StatusBadRequest, "project not found in this workspace") {+ return+ }batchProjectID = projectUUID}@@ -4787,6 +4866,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {// once after the loop against the final state (MUL-4155), not per child// against a mid-batch snapshot.var changedParents []pgtype.UUID+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }for _, issueID := range req.IssueIDs {issueUUID, err := util.ParseUUID(issueID)if err != nil {@@ -4796,7 +4879,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {ID: issueUUID,WorkspaceID: wsUUID,})- if err != nil {+ if err != nil || !hidden.CanSeeProject(prevIssue.ProjectID) {continue}@@ -4879,10 +4962,11 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {continue}// Validate parent exists in the same workspace.- if _, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ newParent, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: newParentID,WorkspaceID: prevIssue.WorkspaceID,- }); err != nil {+ })+ if err != nil || !hidden.CanSeeProject(newParent.ProjectID) {continue}// Cycle detection: walk up from the new parent to ensure we don't reach this issue.@@ -5083,6 +5167,10 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {}issues := make([]db.Issue, 0, len(req.IssueIDs))excludedIDs := make([]pgtype.UUID, 0, len(req.IssueIDs))+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }seenIssueIDs := make(map[pgtype.UUID]struct{}, len(req.IssueIDs))for _, issueID := range req.IssueIDs {issueUUID, err := util.ParseUUID(issueID)@@ -5096,7 +5184,7 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {ID: issueUUID,WorkspaceID: wsUUID,})- if err != nil {+ if err != nil || !hidden.CanSeeProject(issue.ProjectID) {continue}diff --git a/server/internal/handler/issue_duplicate.go b/server/internal/handler/issue_duplicate.goindex d5de58d8ba..1b1561a97d 100644--- a/server/internal/handler/issue_duplicate.go+++ b/server/internal/handler/issue_duplicate.go@@ -142,6 +142,10 @@ func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {if !ok {return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(issue.WorkspaceID))+ if !ok {+ return+ }prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)fill := h.newStatusCategoryFiller(r.Context(), issue.WorkspaceID)@@ -152,6 +156,7 @@ func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {WorkspaceID: issue.WorkspaceID,})switch {+ case err == nil && !hidden.CanSeeProject(original.ProjectID):case err == nil:resp := issueToResponse(original, prefix)fill(&resp)@@ -172,6 +177,7 @@ func (h *Handler) ListIssueDuplicates(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list duplicates")return}+ rows = filterVisibleIssues(hidden, rows)duplicates := make([]IssueResponse, 0, len(rows))for _, row := range rows {resp := issueToResponse(row, prefix)diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 072cae2efb..9e104e4b81 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -507,6 +507,13 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,args = append(args, value)return "$" + strconv.Itoa(len(args))}+ hidden, ok := h.requestHiddenProjects(w, r, util.UUIDToString(workspaceUUID))+ if !ok {+ return issueTableSQL{}, false+ }+ if ids := hidden.Param(); ids != nil {+ where = append(where, hiddenProjectPredicate("i.project_id", addArg(ids)))+ }negated := make(map[string]bool, len(spec.Filters.Negate))for _, field := range spec.Filters.Negate {diff --git a/server/internal/handler/issue_unread.go b/server/internal/handler/issue_unread.goindex 920c2c51f7..f8c3f0f7cd 100644--- a/server/internal/handler/issue_unread.go+++ b/server/internal/handler/issue_unread.go@@ -35,10 +35,15 @@ func (h *Handler) ListIssueUnread(w http.ResponseWriter, r *http.Request) {if !ok {return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }params := db.ListIssueUnreadParams{- WorkspaceID: wsUUID,- UserID: parseUUID(userID),- PageLimit: int32(issueUnreadPageSize + 1),+ WorkspaceID: wsUUID,+ UserID: parseUUID(userID),+ PageLimit: int32(issueUnreadPageSize + 1),+ HiddenProjectIds: hidden.Param(),}if cursor := r.URL.Query().Get("cursor"); cursor != "" {params.BeforeCreatedAt, params.BeforeIssueID = parseTranscriptCursor(cursor)diff --git a/server/internal/handler/issue_view.go b/server/internal/handler/issue_view.goindex a6e95cf561..33c1056503 100644--- a/server/internal/handler/issue_view.go+++ b/server/internal/handler/issue_view.go@@ -223,6 +223,9 @@ func (h *Handler) CreateIssueView(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), projUUID, http.StatusNotFound, "project not found") {+ return+ }scopeID = projUUIDcase "my":// My Issues is a per-user perspective; sharing it is meaningless.@@ -269,6 +272,10 @@ func (h *Handler) ListIssueViews(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list views")return}+ views, ok := h.visibleIssueViews(w, r, wsUUID, views)+ if !ok {+ return+ }resp := make([]IssueViewResponse, len(views))for i, v := range views {resp[i] = issueViewToResponse(v)@@ -299,6 +306,10 @@ func (h *Handler) ListIssueViews(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list views")return}+ views, ok = h.visibleIssueViews(w, r, wsUUID, views)+ if !ok {+ return+ }resp := make([]IssueViewResponse, len(views))for i, v := range views {resp[i] = issueViewToResponse(v)@@ -325,6 +336,9 @@ func (h *Handler) loadIssueViewForUser(w http.ResponseWriter, r *http.Request, uwriteError(w, http.StatusNotFound, "view not found")return db.IssueView{}, pgtype.UUID{}, false}+ if view.ScopeType == "project" && !h.requireProjectVisible(w, r, uuidToString(wsUUID), view.ScopeID, http.StatusNotFound, "view not found") {+ return db.IssueView{}, pgtype.UUID{}, false+ }return view, wsUUID, true}@@ -487,3 +501,23 @@ func (h *Handler) DeleteIssueView(w http.ResponseWriter, r *http.Request) {h.publishIssueViewChanged(view, false, userID, "deleted")w.WriteHeader(http.StatusNoContent)}++// visibleIssueViews drops project-scoped views on private projects the caller+// cannot see (MUL-8472); a workspace-shared view would otherwise name one.+func (h *Handler) visibleIssueViews(w http.ResponseWriter, r *http.Request, wsUUID pgtype.UUID, views []db.IssueView) ([]db.IssueView, bool) {+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return nil, false+ }+ if hidden.Empty() {+ return views, true+ }+ out := views[:0:0]+ for _, v := range views {+ if v.ScopeType == "project" && !hidden.CanSeeProject(v.ScopeID) {+ continue+ }+ out = append(out, v)+ }+ return out, true+}diff --git a/server/internal/handler/issue_workflow.go b/server/internal/handler/issue_workflow.goindex 1a9f9ebfc7..561e4a0604 100644--- a/server/internal/handler/issue_workflow.go+++ b/server/internal/handler/issue_workflow.go@@ -914,6 +914,9 @@ func (h *Handler) loadProjectForWorkflowWrite(w http.ResponseWriter, r *http.ReqwriteError(w, http.StatusNotFound, "project not found")return db.Project{}, db.Member{}, "", false}+ if !h.requireProjectVisible(w, r, workspaceID, project.ID, http.StatusNotFound, "project not found") {+ return db.Project{}, db.Member{}, "", false+ }if !canManageProjectWorkflow(member, project) {writeError(w, http.StatusForbidden, "only workspace admins and the project lead can change this project's workflow")return db.Project{}, db.Member{}, "", false@@ -1399,6 +1402,9 @@ func (h *Handler) PreviewWorkflowHandoff(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, uuidToString(issue.WorkspaceID), projectID, http.StatusNotFound, "project not found") {+ return+ }params.ProjectID = projectIDenterOnMove = true}diff --git a/server/internal/handler/pin.go b/server/internal/handler/pin.goindex 578efab375..3c5cc5b9e8 100644--- a/server/internal/handler/pin.go+++ b/server/internal/handler/pin.go@@ -2,10 +2,14 @@ package handlerimport ("encoding/json"+ "errors""net/http""strings""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"++ "github.com/multica-ai/multica/server/internal/projectaccess"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -74,11 +78,21 @@ func (h *Handler) ListPins(w http.ResponseWriter, r *http.Request) {// they understand them (?include=view).includeViews := strings.Contains(r.URL.Query().Get("include"), "view")+ // Pins on private projects (or their issues) the caller cannot see are+ // left out rather than deleted, so they come back if access does.+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }+resp := make([]PinnedItemResponse, 0, len(pins))for _, p := range pins {if p.ItemType == "view" && !includeViews {continue}+ if !hidden.Empty() && !h.pinVisible(r, hidden, p) {+ continue+ }resp = append(resp, pinnedItemToResponse(p))}writeJSON(w, http.StatusOK, resp)@@ -117,12 +131,16 @@ func (h *Handler) CreatePin(w http.ResponseWriter, r *http.Request) {// Verify the item exists in this workspaceswitch req.ItemType {case "issue":- if _, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{+ issue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{ID: itemUUID, WorkspaceID: wsUUID,- }); err != nil {+ })+ if err != nil {writeError(w, http.StatusNotFound, "issue not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, issue.ProjectID, http.StatusNotFound, "issue not found") {+ return+ }case "project":if _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{ID: itemUUID, WorkspaceID: wsUUID,@@ -130,6 +148,9 @@ func (h *Handler) CreatePin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, itemUUID, http.StatusNotFound, "project not found") {+ return+ }case "view":// Same read rule as the view endpoints: your own views, or views// shared to the workspace. Foreign private views 404 — a pin must@@ -251,3 +272,20 @@ func (h *Handler) ReorderPins(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusNoContent)}++func (h *Handler) pinVisible(r *http.Request, hidden projectaccess.Hidden, pin db.PinnedItem) bool {+ switch pin.ItemType {+ case "project":+ return hidden.CanSeeProject(pin.ItemID)+ case "issue":+ projectID, err := h.Queries.GetIssueProjectID(r.Context(), pin.ItemID)+ if err != nil {+ // A missing issue keeps today's behavior (the client prunes it);+ // a read failure hides the pin rather than risk showing it.+ return errors.Is(err, pgx.ErrNoRows)+ }+ return hidden.CanSeeProject(projectID)+ default:+ return true+ }+}diff --git a/server/internal/handler/private_project_test.go b/server/internal/handler/private_project_test.gonew file mode 100644index 0000000000..aaef2f92df--- /dev/null+++ b/server/internal/handler/private_project_test.go@@ -0,0 +1,756 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/projectaccess"+ "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"+)++// privateProjectFixture: a private project with one regular member (insider),+// a regular workspace member outside it (outsider), the workspace owner+// (testUserID, not a project member), an issue and a comment inside it, and a+// public issue outside any project.+type privateProjectFixture struct {+ projectID string+ insider string+ outsider string+ secretIssue string+ secretComment string+ publicIssue string+ marker string+}++func newPrivateProjectFixture(t *testing.T) privateProjectFixture {+ t.Helper()+ marker := fmt.Sprintf("pp%d", time.Now().UnixNano())+ f := privateProjectFixture{marker: marker}+ f.insider = createPlainMember(t, marker+"[email protected]")+ f.outsider = createPlainMember(t, marker+"[email protected]")+ f.projectID = dbfx.Project(t, marker+" secret project", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})+ addProjectMemberRow(t, f.projectID, f.insider)+ // Explicit numbers far above the workspace counter keep these rows clear+ // of the numbers CreateIssue allocates in the same test.+ base := 800000 + int(time.Now().UnixNano()%100000)*2+ f.secretIssue = dbfx.Issue(t, marker+" secret issue", testutil.Cols{"project_id": f.projectID, "number": base})+ f.secretComment = dbfx.Comment(t, f.secretIssue, marker+" secret comment")+ f.publicIssue = dbfx.Issue(t, marker+" public issue", testutil.Cols{"number": base + 1})+ return f+}++func addProjectMemberRow(t *testing.T, projectID, userID string) {+ t.Helper()+ dbfx.InsertNoID(t, "project_member", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "project_id": projectID,+ "user_id": userID,+ }, "project_id = $1 AND user_id = $2", projectID, userID)+}++func asUser(req *http.Request, userID string) *http.Request {+ req.Header.Set("X-User-ID", userID)+ return req+}++func TestPrivateProjectIssueDetailMatrix(t *testing.T) {+ f := newPrivateProjectFixture(t)+ get := func(userID, issueID string) int {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+issueID, nil), userID), "id", issueID)+ rec := httptest.NewRecorder()+ testHandler.GetIssue(rec, req)+ return rec.Code+ }+ for _, tc := range []struct {+ name string+ userID string+ want int+ }{+ {"project member", f.insider, http.StatusOK},+ {"workspace owner outside the member list", testUserID, http.StatusOK},+ {"workspace member outside the project", f.outsider, http.StatusNotFound},+ } {+ if got := get(tc.userID, f.secretIssue); got != tc.want {+ t.Errorf("%s: GET secret issue = %d, want %d", tc.name, got, tc.want)+ }+ }+ if got := get(f.outsider, f.publicIssue); got != http.StatusOK {+ t.Errorf("outsider GET public issue = %d, want 200", got)+ }++ // Sub-resources go through the same loader.+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.secretIssue+"/comments", nil), f.outsider), "id", f.secretIssue)+ testutil.Call(t, testHandler.ListComments, req).Want(http.StatusNotFound)+}++func TestPrivateProjectHiddenFromLists(t *testing.T) {+ f := newPrivateProjectFixture(t)++ listIssueIDs := func(userID, query string) map[string]bool {+ req := asUser(newRequest(http.MethodGet, "/api/issues?"+query, nil), userID)+ var resp struct {+ Issues []IssueResponse `json:"issues"`+ }+ testutil.Call(t, testHandler.ListIssues, req).Want(http.StatusOK).JSON(&resp)+ ids := map[string]bool{}+ for _, is := range resp.Issues {+ ids[is.ID] = true+ }+ return ids+ }+ for _, query := range []string{"limit=100", "open_only=true"} {+ outsider := listIssueIDs(f.outsider, query)+ if outsider[f.secretIssue] || !outsider[f.publicIssue] {+ t.Errorf("%s: outsider sees secret=%v public=%v", query, outsider[f.secretIssue], outsider[f.publicIssue])+ }+ if insider := listIssueIDs(f.insider, query); !insider[f.secretIssue] {+ t.Errorf("%s: insider does not see the secret issue", query)+ }+ }++ listProjectIDs := func(userID string) map[string]bool {+ var resp struct {+ Projects []ProjectResponse `json:"projects"`+ }+ testutil.Call(t, testHandler.ListProjects, asUser(newRequest(http.MethodGet, "/api/projects", nil), userID)).+ Want(http.StatusOK).JSON(&resp)+ ids := map[string]bool{}+ for _, p := range resp.Projects {+ ids[p.ID] = true+ if p.ID == f.projectID && p.Visibility != projectaccess.VisibilityPrivate {+ t.Errorf("project visibility = %q, want private", p.Visibility)+ }+ }+ return ids+ }+ if listProjectIDs(f.outsider)[f.projectID] {+ t.Error("outsider sees the private project in the project list")+ }+ if !listProjectIDs(testUserID)[f.projectID] {+ t.Error("workspace owner does not see the private project in the project list")+ }++ search := func(userID string) map[string]bool {+ req := asUser(newRequest(http.MethodGet, "/api/issues/search?q="+f.marker, nil), userID)+ var resp struct {+ Issues []struct {+ ID string `json:"id"`+ } `json:"issues"`+ }+ testutil.Call(t, testHandler.SearchIssues, req).Want(http.StatusOK).JSON(&resp)+ ids := map[string]bool{}+ for _, is := range resp.Issues {+ ids[is.ID] = true+ }+ return ids+ }+ if got := search(f.outsider); got[f.secretIssue] || !got[f.publicIssue] {+ t.Errorf("outsider search: secret=%v public=%v", got[f.secretIssue], got[f.publicIssue])+ }+ if !search(f.insider)[f.secretIssue] {+ t.Error("insider search misses the secret issue")+ }++ projectReq := withURLParam(asUser(newRequest(http.MethodGet, "/api/projects/"+f.projectID, nil), f.outsider), "id", f.projectID)+ testutil.Call(t, testHandler.GetProject, projectReq).Want(http.StatusNotFound)+}++func TestPrivateProjectSearchProjectFilter(t *testing.T) {+ f := newPrivateProjectFixture(t)+ commentIssue := dbfx.Issue(t, "comment-only search hit", testutil.Cols{"project_id": f.projectID})+ dbfx.Comment(t, commentIssue, f.marker+" matching comment")+ for _, includeClosed := range []string{"false", "true"} {+ for _, userID := range []string{f.insider, f.outsider, testUserID} {+ req := asUser(newRequest(http.MethodGet, "/api/issues/search?q="+f.marker+"&project_id="+f.projectID+"&include_closed="+includeClosed, nil), userID)+ var resp struct {+ Issues []SearchIssueResponse `json:"issues"`+ }+ testutil.Call(t, testHandler.SearchIssues, req).Want(http.StatusOK).JSON(&resp)+ if userID == f.outsider {+ if len(resp.Issues) != 0 {+ t.Fatalf("outsider project search (include_closed=%s) exposed %+v", includeClosed, resp.Issues)+ }+ continue+ }+ if len(resp.Issues) != 2 {+ t.Fatalf("authorized project search (include_closed=%s) = %+v, want title and comment hits", includeClosed, resp.Issues)+ }+ for _, issue := range resp.Issues {+ if issue.ID != f.secretIssue && issue.ID != commentIssue {+ t.Fatalf("project search returned an issue outside the selected project: %+v", issue)+ }+ }+ }+ }+}++func TestPrivateProjectSubtreeRunsAreRedacted(t *testing.T) {+ f := newPrivateProjectFixture(t)+ dbfx.Exec(t, "UPDATE issue SET parent_issue_id=$1 WHERE id=$2", f.publicIssue, f.secretIssue)+ agentID := dbfx.Agent(t, f.marker+" subtree agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "completed",+ "result": testutil.Raw(`'{"output":"private subtree result"}'::jsonb`),+ })+ for _, userID := range []string{f.outsider, f.insider, testUserID} {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.publicIssue+"/task-runs?scope=subtree", nil), userID), "id", f.publicIssue)+ var runs []AgentTaskResponse+ testutil.Call(t, testHandler.ListTasksByIssue, req).Want(http.StatusOK).JSON(&runs)+ if len(runs) != 1 || runs[0].ID != taskID {+ t.Fatalf("subtree runs = %+v, want descendant run %s", runs, taskID)+ }+ run := runs[0]+ if userID == f.outsider {+ if !run.Restricted || run.IssueID != "" || run.IssueTitle != "" || run.IssueIdentifier != "" || run.Result != nil {+ t.Fatalf("private descendant run exposed to outsider: %+v", run)+ }+ } else if run.Restricted || run.IssueID != f.secretIssue || run.IssueTitle == "" || run.Result == nil {+ t.Fatalf("authorized viewer lost descendant run content: %+v", run)+ }+ }+}++func TestPrivateProjectCommentAndAttachmentByID(t *testing.T) {+ f := newPrivateProjectFixture(t)+ react := func(userID string) int {+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/comments/"+f.secretComment+"/reactions", map[string]any{"emoji": "👍"}), userID), "commentId", f.secretComment)+ rec := httptest.NewRecorder()+ testHandler.AddReaction(rec, req)+ return rec.Code+ }+ if got := react(f.outsider); got != http.StatusNotFound {+ t.Errorf("outsider reaction on secret comment = %d, want 404", got)+ }+ if got := react(f.insider); got >= 400 {+ t.Errorf("insider reaction on secret comment = %d, want success", got)+ }+ testPool.Exec(context.Background(), `DELETE FROM comment_reaction WHERE comment_id = $1`, f.secretComment)++ attachmentID := dbfx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "issue_id": f.secretIssue,+ "uploader_type": "member",+ "uploader_id": testUserID,+ "filename": "secret.txt",+ "url": "https://example.invalid/secret.txt",+ "content_type": "text/plain",+ "size_bytes": 1,+ })+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/attachments/"+attachmentID, nil), f.outsider), "id", attachmentID)+ testutil.Call(t, testHandler.GetAttachmentByID, req).Want(http.StatusNotFound)+}++func TestPrivateProjectWritesNeedVisibility(t *testing.T) {+ f := newPrivateProjectFixture(t)+ create := func(userID string, body map[string]any) *testutil.Response {+ return testutil.Call(t, testHandler.CreateIssue, asUser(newRequest(http.MethodPost, "/api/issues", body), userID))+ }+ create(f.outsider, map[string]any{"title": f.marker + " smuggled", "project_id": f.projectID}).Want(http.StatusBadRequest)+ create(f.outsider, map[string]any{"title": f.marker + " child", "parent_issue_id": f.secretIssue}).Want(http.StatusBadRequest)++ var created IssueResponse+ create(f.insider, map[string]any{"title": f.marker + " insider issue", "project_id": f.projectID}).Want(http.StatusCreated).JSON(&created)+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, created.ID) })++ // Moving a public issue into the private project needs the same access.+ move := withURLParam(asUser(newRequest(http.MethodPut, "/api/issues/"+f.publicIssue, map[string]any{"project_id": f.projectID}), f.outsider), "id", f.publicIssue)+ testutil.Call(t, testHandler.UpdateIssue, move).Want(http.StatusBadRequest)+}++func TestPrivateProjectVisibilityAndMembersAPI(t *testing.T) {+ f := newPrivateProjectFixture(t)+ createPrivate := func() *testutil.Response {+ return testutil.Call(t, testHandler.CreateProject, asUser(newRequest(http.MethodPost, "/api/projects", map[string]any{+ "title": f.marker + " new private",+ "visibility": "private",+ "member_ids": []string{f.insider},+ }), f.insider))+ }++ withFeatureFlag(t, testHandler, featureflags.PrivateProjectsV1, false)+ if got := createPrivate().Want(http.StatusForbidden).Map()["code"]; got != "private_projects_disabled" {+ t.Fatalf("flag off: code = %v", got)+ }++ withFeatureFlag(t, testHandler, featureflags.PrivateProjectsV1, true)+ var project ProjectResponse+ createPrivate().Want(http.StatusCreated).JSON(&project)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_member WHERE project_id = $1`, project.ID)+ testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, project.ID)+ })+ if project.Visibility != projectaccess.VisibilityPrivate {+ t.Fatalf("visibility = %q", project.Visibility)+ }++ members := func(userID string) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/projects/"+project.ID+"/members", nil), userID), "id", project.ID)+ return testutil.Call(t, testHandler.ListProjectMembers, req)+ }+ members(f.outsider).Want(http.StatusNotFound)+ var list struct {+ Members []ProjectMemberResponse `json:"members"`+ }+ members(f.insider).Want(http.StatusOK).JSON(&list)+ if len(list.Members) != 1 || list.Members[0].UserID != f.insider {+ t.Fatalf("members = %+v, want only the creator", list.Members)+ }++ // Only an access manager may add; unknown workspace users are rejected.+ add := func(userID string, ids ...string) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+project.ID+"/members", map[string]any{"user_ids": ids}), userID), "id", project.ID)+ return testutil.Call(t, testHandler.AddProjectMembers, req)+ }+ add(f.insider, f.outsider).Want(http.StatusForbidden)+ members(testUserID).Want(http.StatusOK).JSON(&list)+ if len(list.Members) != 1 || list.Members[0].UserID != f.insider {+ t.Fatal("refused add changed project membership")+ }+ add(testUserID, "00000000-0000-0000-0000-00000000beef").Want(http.StatusBadRequest)+ add(testUserID, f.outsider).Want(http.StatusOK)++ remove := func(actor, target string) *testutil.Response {+ req := testutil.WithURLParams(asUser(newRequest(http.MethodDelete, "/api/projects/"+project.ID+"/members/"+target, nil), actor), "id", project.ID, "userId", target)+ return testutil.Call(t, testHandler.RemoveProjectMember, req)+ }+ // Every removal takes an admin or the lead, including self-removal.+ remove(f.outsider, f.insider).Want(http.StatusForbidden)+ remove(f.outsider, f.outsider).Want(http.StatusForbidden)+ members(f.outsider).Want(http.StatusOK)+ withFeatureFlag(t, testHandler, featureflags.PrivateProjectsV1, false)+ remove(f.outsider, f.outsider).Want(http.StatusForbidden)+ members(f.outsider).Want(http.StatusOK)+ remove(testUserID, f.outsider).Want(http.StatusNoContent)+ members(f.outsider).Want(http.StatusNotFound)++ // Only an admin or the lead switches visibility; the owner can.+ update := func(userID string, body map[string]any) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+project.ID, body), userID), "id", project.ID)+ return testutil.Call(t, testHandler.UpdateProject, req)+ }+ update(f.insider, map[string]any{"visibility": "workspace"}).Want(http.StatusForbidden)+ var updated ProjectResponse+ update(testUserID, map[string]any{"visibility": "workspace"}).Want(http.StatusOK).JSON(&updated)+ if updated.Visibility != projectaccess.VisibilityWorkspace {+ t.Fatalf("visibility after switch = %q", updated.Visibility)+ }+ members(f.outsider).Want(http.StatusOK)+}++func TestPrivateProjectTaskTranscriptAndRunHistory(t *testing.T) {+ f := newPrivateProjectFixture(t)+ var agentID string+ if err := testPool.QueryRow(context.Background(),+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = 'Handler Test Agent'`, testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load seeded agent: %v", err)+ }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": f.secretIssue,+ "runtime_id": testRuntimeID,+ "status": "completed",+ "result": testutil.Raw(`'{"output":"secret result"}'::jsonb`),+ })++ transcript := func(userID string) int {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/tasks/"+taskID+"/messages", nil), userID), "taskId", taskID)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ rec := httptest.NewRecorder()+ testHandler.ListTaskMessagesByUser(rec, req)+ return rec.Code+ }+ if got := transcript(f.outsider); got != http.StatusNotFound {+ t.Errorf("outsider transcript = %d, want 404", got)+ }+ if got := transcript(f.insider); got != http.StatusOK {+ t.Errorf("insider transcript = %d, want 200", got)+ }++ history := func(userID string) AgentTaskResponse {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks", nil), userID), "id", agentID)+ var tasks []AgentTaskResponse+ testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)+ for _, task := range tasks {+ if task.ID == taskID {+ return task+ }+ }+ t.Fatalf("run %s missing from %s's history", taskID, userID)+ return AgentTaskResponse{}+ }+ hidden := history(f.outsider)+ if !hidden.Restricted || hidden.IssueID != "" || hidden.Result != nil || hidden.Status != "completed" {+ t.Errorf("outsider run = restricted %v issue %q result %v status %q; want a redacted completed run",+ hidden.Restricted, hidden.IssueID, hidden.Result, hidden.Status)+ }+ visible := history(f.insider)+ if visible.Restricted || visible.IssueID != f.secretIssue {+ t.Errorf("insider run = restricted %v issue %q", visible.Restricted, visible.IssueID)+ }+}++func TestPrivateProjectEnqueueNeedsAgentOwnerAccess(t *testing.T) {+ f := newPrivateProjectFixture(t)+ ctx := context.Background()+ outsiderAgent := dbfx.Agent(t, f.marker+" outsider agent", testRuntimeID, testutil.Cols{"owner_id": f.outsider})+ insiderAgent := dbfx.Agent(t, f.marker+" insider agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, f.secretIssue)+ })++ issue := func(agentID string) db.Issue {+ testPool.Exec(ctx, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, f.secretIssue, agentID)+ row, err := testHandler.Queries.GetIssue(ctx, parseUUID(f.secretIssue))+ if err != nil {+ t.Fatalf("load issue: %v", err)+ }+ return row+ }+ _, err := testHandler.TaskService.EnqueueTaskForIssueByActor(ctx, issue(outsiderAgent), parseUUID(f.insider))+ if !errors.Is(err, service.ErrProjectAccessDenied) {+ t.Fatalf("outsider-owned agent: err = %v, want ErrProjectAccessDenied", err)+ }+ _, err = testHandler.TaskService.EnqueueTaskForIssueByActor(ctx, issue(insiderAgent), parseUUID(f.insider))+ if errors.Is(err, service.ErrProjectAccessDenied) {+ t.Fatalf("insider-owned agent refused for project access")+ }++ // Assignment surfaces the same rule as an explicit 403.+ rec := httptest.NewRecorder()+ req := asUser(newRequest(http.MethodPut, "/api/issues/"+f.secretIssue, nil), f.insider)+ ok := testHandler.requireAssigneeCanAccessProject(rec, req, parseUUID(testWorkspaceID),+ pgtype.Text{String: "agent", Valid: true}, parseUUID(outsiderAgent), parseUUID(f.projectID))+ if ok || rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), string(ReasonProjectAccessBlocked)) {+ t.Fatalf("assignment pre-check = %v %d %s", ok, rec.Code, rec.Body.String())+ }+}++func TestPrivateProjectInboxSkipsOutsiders(t *testing.T) {+ f := newPrivateProjectFixture(t)+ ctx := context.Background()+ write := func(recipient string) error {+ _, err := testHandler.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ RecipientType: "member",+ RecipientID: parseUUID(recipient),+ Type: "mentioned",+ Severity: "info",+ IssueID: parseUUID(f.secretIssue),+ Title: f.marker + " secret notification",+ })+ return err+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM inbox_item WHERE issue_id = $1`, f.secretIssue)+ })+ if err := write(f.outsider); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("outsider notification: err = %v, want skipped", err)+ }+ if err := write(f.insider); err != nil {+ t.Fatalf("insider notification: %v", err)+ }+ if err := write(testUserID); err != nil {+ t.Fatalf("owner notification: %v", err)+ }+}++func removeProjectMemberAsOwner(t *testing.T, f privateProjectFixture, userID string) {+ t.Helper()+ req := testutil.WithURLParams(newRequest(http.MethodDelete, "/api/projects/"+f.projectID+"/members/"+userID, nil), "id", f.projectID, "userId", userID)+ testutil.Call(t, testHandler.RemoveProjectMember, req).Want(http.StatusNoContent)+}++func TestPrivateProjectIssueUnreadRunReferencesAfterRevocation(t *testing.T) {+ f := newPrivateProjectFixture(t)+ agentID := dbfx.Agent(t, f.marker+" unread agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})+ secretTask := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.secretIssue, "runtime_id": testRuntimeID, "status": "completed"})+ publicTask := dbfx.Task(t, agentID, testutil.Cols{"issue_id": f.publicIssue, "runtime_id": testRuntimeID, "status": "completed"})+ secretResult := dbfx.Comment(t, f.secretIssue, "private run result", testutil.Cols{"source_task_id": secretTask})+ publicResult := dbfx.Comment(t, f.publicIssue, "public run result", testutil.Cols{"source_task_id": publicTask})+ dbfx.Cleanup(t, `DELETE FROM issue_unread WHERE user_id = $1`, f.insider)+ dbfx.Exec(t, `+INSERT INTO issue_unread (workspace_id, user_id, issue_id, outcome, agent_id, task_id)+VALUES ($1, $2, $3, 'completed', $4, $5), ($1, $2, $6, 'completed', $4, $7)`,+ testWorkspaceID, f.insider, f.secretIssue, agentID, secretTask, f.publicIssue, publicTask)++ before := listIssueUnreadAs(t, f.insider)+ if len(before) != 2 {+ t.Fatalf("member should see both unread issues, got %+v", before)+ }+ for _, item := range before {+ wantTask, wantComment := publicTask, publicResult+ if item.IssueID == f.secretIssue {+ wantTask, wantComment = secretTask, secretResult+ } else if item.IssueID != f.publicIssue {+ t.Fatalf("unexpected unread issue: %+v", item)+ }+ if item.TaskID == nil || *item.TaskID != wantTask || item.CommentID == nil || *item.CommentID != wantComment {+ t.Fatalf("unread issue should link to task %s and comment %s, got %+v", wantTask, wantComment, item)+ }+ }++ removeProjectMemberAsOwner(t, f, f.insider)++ after := listIssueUnreadAs(t, f.insider)+ if len(after) != 1 || after[0].IssueID != f.publicIssue {+ t.Fatalf("revoked member should only see the public unread issue, got %+v", after)+ }+ if after[0].TaskID == nil || *after[0].TaskID != publicTask || after[0].CommentID == nil || *after[0].CommentID != publicResult {+ t.Fatalf("public unread issue should retain its run references after revocation, got %+v", after[0])+ }+}++func TestPrivateProjectArchivedInboxAndUnreadAfterRevocation(t *testing.T) {+ f := newPrivateProjectFixture(t)+ dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,+ "type": "mentioned", "severity": "info", "title": f.marker + " archived secret", "issue_id": f.secretIssue,+ "archived": true,+ })+ unreadID := dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,+ "type": "mentioned", "severity": "info", "title": f.marker + " unread secret", "issue_id": f.secretIssue,+ })+ countUnread := func() int64 {+ req := asUser(newRequest(http.MethodGet, "/api/inbox/unread-count", nil), f.insider)+ var resp struct {+ Count int64 `json:"count"`+ }+ testutil.Call(t, inboxWorkspaceHandler(testHandler.CountUnreadInbox), req).Want(http.StatusOK).JSON(&resp)+ return resp.Count+ }+ if got := countUnread(); got < 1 {+ t.Fatalf("member unread count before removal = %d, want the private notification counted", got)+ }+ before := countUnread()++ removeProjectMemberAsOwner(t, f, f.insider)++ for _, tc := range []struct {+ name string+ handler http.HandlerFunc+ }{+ {"archived list", testHandler.ListArchivedInbox},+ {"archived page", testHandler.ListArchivedInboxPage},+ {"archived facets", testHandler.GetArchivedInboxFacets},+ } {+ req := asUser(newRequest(http.MethodGet, "/api/inbox/archived", nil), f.insider)+ body := testutil.Call(t, inboxWorkspaceHandler(tc.handler), req).Want(http.StatusOK).Text()+ if strings.Contains(body, f.secretIssue) || strings.Contains(body, f.marker) {+ t.Errorf("%s still returns the private notification after removal: %s", tc.name, body)+ }+ }+ if got := countUnread(); got != before-1 {+ t.Errorf("unread count after removal = %d, want %d (notification %s no longer counted)", got, before-1, unreadID)+ }+}++func TestPrivateProjectLeadChangeCannotGrantAccess(t *testing.T) {+ f := newPrivateProjectFixture(t)+ isMember := func(userID string) bool {+ var ok bool+ if err := testPool.QueryRow(context.Background(),+ `SELECT EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2)`, f.projectID, userID,+ ).Scan(&ok); err != nil {+ t.Fatal(err)+ }+ return ok+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_member WHERE project_id = $1 AND user_id = $2`, f.projectID, f.outsider)+ })+ setLead := func(req *http.Request) *testutil.Response {+ return testutil.Call(t, testHandler.UpdateProject, withURLParam(req, "id", f.projectID))+ }+ body := map[string]any{"lead_type": "member", "lead_id": f.outsider}++ // An agent run of a project member cannot hand the project to an outsider.+ agent := dbfx.Agent(t, f.marker+" insider agent", testRuntimeID, testutil.Cols{"owner_id": f.insider})+ task := dbfx.Task(t, agent, testutil.Cols{"runtime_id": testRuntimeID, "issue_id": f.secretIssue, "status": "running",+ "originator_user_id": f.insider, "accountable_user_id": f.insider})+ req := asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.insider)+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Set("X-Agent-ID", agent)+ req.Header.Set("X-Task-ID", task)+ setLead(req).Want(http.StatusForbidden)+ if isMember(f.outsider) {+ t.Fatal("agent lead change granted the outsider project membership")+ }+ var lead *string+ testPool.QueryRow(context.Background(), `SELECT lead_id::text FROM project WHERE id = $1`, f.projectID).Scan(&lead)+ if lead != nil {+ t.Fatalf("refused update still wrote lead_id = %s", *lead)+ }++ // A human workspace owner may, and the new lead becomes a member.+ setLead(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), testUserID)).Want(http.StatusOK)+ if !isMember(f.outsider) {+ t.Fatal("a member lead of a private project must be a project member")+ }+}++func TestPrivateProjectLeadChangeRequiresAccessManager(t *testing.T) {+ for _, change := range []string{"self", "outsider", "clear", "id_only", "type_only"} {+ t.Run(change, func(t *testing.T) {+ f := newPrivateProjectFixture(t)+ lead := createPlainMember(t, f.marker+"[email protected]")+ addProjectMemberRow(t, f.projectID, lead)+ dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, lead, f.projectID)+ body := map[string]any{"lead_type": "member", "lead_id": f.insider, "title": "must not change"}+ switch change {+ case "outsider":+ body["lead_id"] = f.outsider+ case "clear":+ body["lead_type"], body["lead_id"] = nil, nil+ case "id_only":+ delete(body, "lead_type")+ case "type_only":+ body["lead_type"] = nil+ delete(body, "lead_id")+ }+ req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.insider), "id", f.projectID)+ testutil.Call(t, testHandler.UpdateProject, req).Want(http.StatusForbidden)+ var title, storedLead string+ if err := testPool.QueryRow(context.Background(), `SELECT title, lead_id::text FROM project WHERE id = $1`, f.projectID).Scan(&title, &storedLead); err != nil {+ t.Fatal(err)+ }+ if storedLead != lead || title == "must not change" {+ t.Fatal("refused lead change still changed the project")+ }+ })+ }+}++// On a workspace-visible project the lead stays an ordinary field: any member+// (or agent) may set it, as before private projects. Leading one therefore+// grants nothing; in particular it does not let a member make it private.+func TestWorkspaceProjectLeadStaysOpenButGrantsNoAccess(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.PrivateProjectsV1, true)+ f := newPrivateProjectFixture(t)+ dbfx.Exec(t, `UPDATE project SET visibility = 'workspace' WHERE id = $1`, f.projectID)+ update := func(body map[string]any) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, body), f.outsider), "id", f.projectID)+ return testutil.Call(t, testHandler.UpdateProject, req)+ }+ update(map[string]any{"lead_type": "member", "lead_id": f.outsider}).Want(http.StatusOK)+ update(map[string]any{"visibility": "private"}).Want(http.StatusForbidden)+ addReq := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+f.projectID+"/members", map[string]any{"user_ids": []string{f.outsider}}), f.outsider), "id", f.projectID)+ testutil.Call(t, testHandler.AddProjectMembers, addReq).Want(http.StatusForbidden)+ var visibility string+ if err := testPool.QueryRow(context.Background(), `SELECT visibility FROM project WHERE id = $1`, f.projectID).Scan(&visibility); err != nil {+ t.Fatal(err)+ }+ if visibility != projectaccess.VisibilityWorkspace {+ t.Fatalf("visibility = %q after a self-appointed lead tried to make it private", visibility)+ }+}++func TestPrivateProjectAccessManagersCanAddAndTransferLead(t *testing.T) {+ for _, actor := range []string{"owner", "admin", "lead"} {+ t.Run(actor, func(t *testing.T) {+ f := newPrivateProjectFixture(t)+ dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, f.insider, f.projectID)+ userID := testUserID+ if actor == "lead" {+ userID = f.insider+ } else if actor == "admin" {+ userID = createPlainMember(t, f.marker+"[email protected]")+ dbfx.Exec(t, `UPDATE member SET role = 'admin' WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)+ }+ added := createPlainMember(t, f.marker+"[email protected]")+ req := withURLParam(asUser(newRequest(http.MethodPost, "/api/projects/"+f.projectID+"/members", map[string]any{"user_ids": []string{added}}), userID), "id", f.projectID)+ testutil.Call(t, testHandler.AddProjectMembers, req).Want(http.StatusOK)+ req = withURLParam(asUser(newRequest(http.MethodPut, "/api/projects/"+f.projectID, map[string]any{"lead_type": "member", "lead_id": f.outsider}), userID), "id", f.projectID)+ testutil.Call(t, testHandler.UpdateProject, req).Want(http.StatusOK)+ var newLeadIsMember, oldLeadIsMember bool+ if err := testPool.QueryRow(context.Background(), `SELECT+ EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2),+ EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $3)`, f.projectID, f.outsider, f.insider).Scan(&newLeadIsMember, &oldLeadIsMember); err != nil {+ t.Fatal(err)+ }+ if !newLeadIsMember || !oldLeadIsMember {+ t.Fatal("lead transfer must add the new lead and retain the old lead's membership")+ }+ })+ }+}++func TestPrivateProjectCurrentLeadCannotBeRemoved(t *testing.T) {+ f := newPrivateProjectFixture(t)+ dbfx.Exec(t, `UPDATE project SET lead_type = 'member', lead_id = $1 WHERE id = $2`, f.insider, f.projectID)+ for _, actor := range []string{testUserID, f.insider} {+ req := testutil.WithURLParams(asUser(newRequest(http.MethodDelete, "/api/projects/"+f.projectID+"/members/"+f.insider, nil), actor), "id", f.projectID, "userId", f.insider)+ testutil.Call(t, testHandler.RemoveProjectMember, req).Want(http.StatusConflict)+ }+ var exists bool+ if err := testPool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM project_member WHERE project_id = $1 AND user_id = $2)`, f.projectID, f.insider).Scan(&exists); err != nil {+ t.Fatal(err)+ }+ if !exists {+ t.Fatal("current lead lost project membership")+ }+}++func TestPrivateProjectRevocationDeletesProjectFromSearchIndex(t *testing.T) {+ f := newPrivateProjectFixture(t)+ cursor := searchIndexManifest(t, testWorkspaceID).Cursor+ removeProjectMemberAsOwner(t, f, f.insider)+ req := asUser(searchIndexRequest(http.MethodPost, "/api/search-index/changes", testWorkspaceID, map[string]any{"cursor": cursor, "limit": 1000}), f.insider)+ var changes SearchIndexChangesResponse+ testutil.Call(t, testHandler.ListSearchIndexChanges, req).Want(http.StatusOK).JSON(&changes)+ for _, id := range changes.Deleted.Projects {+ if id == f.projectID {+ return+ }+ }+ t.Errorf("revoked project missing from search deletions; projects=%v issues=%v comments=%v",+ changes.Deleted.Projects, changes.Deleted.Issues, changes.Deleted.Comments)+}++func TestPrivateProjectQuickCreateNeedsAgentOwnerAccess(t *testing.T) {+ f := newPrivateProjectFixture(t)+ runtime := dbfx.Runtime(t, f.marker+" runtime", testutil.Cols{"owner_id": f.outsider, "metadata": testutil.Raw(`'{"cli_version":"99.0.0"}'::jsonb`)})+ agent := dbfx.Agent(t, f.marker+" outsider agent", runtime, testutil.Cols{"owner_id": f.outsider, "permission_mode": "public_to", "visibility": "workspace"})+ dbfx.Insert(t, "agent_invocation_target", testutil.Cols{"agent_id": agent, "target_type": "workspace", "target_id": testWorkspaceID})+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE agent_id = $1`, agent) })+ for _, body := range []map[string]any{+ {"prompt": "Create a task in this project", "agent_id": agent, "project_id": f.projectID},+ {"prompt": "Create a sub-issue", "agent_id": agent, "parent_issue_id": f.secretIssue},+ } {+ rec := httptest.NewRecorder()+ testHandler.QuickCreateIssue(rec, newRequest(http.MethodPost, "/api/issues/quick-create", body))+ if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), string(ReasonProjectAccessBlocked)) {+ t.Errorf("quick-create %v = %d %s, want 403 %s", body, rec.Code, rec.Body.String(), ReasonProjectAccessBlocked)+ }+ }+ var queued int+ testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, agent).Scan(&queued)+ if queued != 0 {+ t.Fatalf("refused quick-create queued %d task(s)", queued)+ }+}++func TestPrivateProjectCommentSubIssuePreviewHidden(t *testing.T) {+ f := newPrivateProjectFixture(t)+ preview := func(userID string) *testutil.Response {+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/comments/"+f.secretComment+"/sub-issue/preview", nil), userID), "commentId", f.secretComment)+ return testutil.Call(t, testHandler.PreviewCommentSubIssue, req)+ }+ if body := preview(f.outsider).Text(); strings.Contains(body, f.marker) {+ t.Fatalf("outsider preview leaks the private thread: %s", body)+ }+ preview(f.insider).Want(http.StatusOK)+}diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex be386747ac..9be2917a53 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -14,8 +14,10 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -49,6 +51,9 @@ type ProjectResponse struct {// WorkflowID is the workflow this project uses; null means the workspace// Default workflow. (MUL-7420)WorkflowID *string `json:"workflow_id"`+ // Visibility is "workspace" (every member) or "private" (project members+ // plus workspace owners/admins). (MUL-8472)+ Visibility string `json:"visibility"`}func projectToResponse(p db.Project) ProjectResponse {@@ -69,9 +74,19 @@ func projectToResponse(p db.Project) ProjectResponse {CreatedAt: timestampToString(p.CreatedAt),UpdatedAt: timestampToString(p.UpdatedAt),WorkflowID: uuidToPtr(p.WorkflowID),+ Visibility: projectVisibilityOrDefault(p.Visibility),}}+// projectVisibilityOrDefault keeps responses on the documented enum for a+// db.Project built outside sqlc that left Visibility empty.+func projectVisibilityOrDefault(v string) string {+ if v == "" {+ return projectaccess.VisibilityWorkspace+ }+ return v+}+func (h *Handler) loadProjectIssueStats(ctx context.Context, workspaceID, projectID pgtype.UUID) (int64, int64) {terminalStatusKeys := h.projectTerminalIssueStatusKeys(ctx, workspaceID)stats, err := h.Queries.GetProjectIssueStats(ctx, db.GetProjectIssueStatsParams{@@ -117,6 +132,11 @@ type CreateProjectRequest struct {StartDate *string `json:"start_date"`DueDate *string `json:"due_date"`Resources []CreateProjectResourceRequestPayload `json:"resources,omitempty"`+ // Visibility "private" creates a private project (MUL-8472, behind+ // private_projects_v1). MemberIDs seeds its member list; the creator is+ // always added.+ Visibility *string `json:"visibility,omitempty"`+ MemberIDs []string `json:"member_ids,omitempty"`// WorkflowID picks the project's workflow at creation; omitted or null// uses the workspace Default workflow. A new project has no issues, so no// status mapping is involved. (MUL-7420)@@ -143,6 +163,10 @@ type UpdateProjectRequest struct {LeadID *string `json:"lead_id"`StartDate *string `json:"start_date"`DueDate *string `json:"due_date"`+ // Visibility switches between "workspace" and "private" (MUL-8472).+ // MemberIDs is only read together with a switch to "private".+ Visibility *string `json:"visibility"`+ MemberIDs []string `json:"member_ids,omitempty"`}func (h *Handler) ListProjects(w http.ResponseWriter, r *http.Request) {@@ -168,6 +192,19 @@ func (h *Handler) ListProjects(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list projects")return}+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }+ if !hidden.Empty() {+ visible := projects[:0:0]+ for _, p := range projects {+ if hidden.CanSeeProject(p.ID) {+ visible = append(visible, p)+ }+ }+ projects = visible+ }// Batch-fetch issue stats and resource counts for all projectsstatsMap := make(map[string]db.GetProjectIssueStatsRow)@@ -226,6 +263,9 @@ func (h *Handler) GetProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, project.ID, http.StatusNotFound, "project not found") {+ return+ }resp := projectToResponse(project)resp.IssueCount, resp.DoneCount = h.loadProjectIssueStats(r.Context(), wsUUID, project.ID)resp.ResourceCount = h.loadProjectResourceCount(r.Context(), project.ID)@@ -394,6 +434,38 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {}}+ // MUL-8472: a private project is created with its member list in the same+ // transaction, so it is never briefly visible to the whole workspace.+ private := false+ var privateMemberIDs []pgtype.UUID+ if req.Visibility != nil && *req.Visibility != "" && *req.Visibility != projectaccess.VisibilityWorkspace {+ if *req.Visibility != projectaccess.VisibilityPrivate {+ writeError(w, http.StatusBadRequest, "invalid visibility: must be one of workspace, private")+ return+ }+ if !h.requireHumanProjectAccessActor(w, r, workspaceID) {+ return+ }+ if !featureflags.PrivateProjectsV1Enabled(r.Context(), h.FeatureFlags) {+ writeFeatureDisabled(w, "private_projects_disabled", "private projects are not enabled")+ return+ }+ ids, ok := parseProjectMemberIDs(w, req.MemberIDs, "member_ids")+ if !ok {+ return+ }+ creator, ok := parseUUIDOrBadRequest(w, userID, "user id")+ if !ok {+ return+ }+ ids = append(ids, creator)+ if leadType.Valid && leadType.String == "member" && leadID.Valid {+ ids = append(ids, leadID)+ }+ private = true+ privateMemberIDs = ids+ }+actorType, actorID := h.resolveActor(r, userID, workspaceID)creatorID, ok := parseUUIDOrBadRequest(w, actorID, "creator_id")if !ok {@@ -416,7 +488,7 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {}// Without resources, keep the simple non-tx path.- if len(req.Resources) == 0 {+ if len(req.Resources) == 0 && !private {project, err := h.Queries.CreateProject(r.Context(), createParams)if err != nil {h.writeProjectWriteError(w, r, err, "create")@@ -442,6 +514,30 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {h.writeProjectWriteError(w, r, err, "create")return}+ if private {+ inserted, err := qtx.AddProjectMembers(r.Context(), db.AddProjectMembersParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserIds: privateMemberIDs,+ AddedBy: parseUUIDOrInvalid(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to add project members")+ return+ }+ if !h.allProjectMembersExist(w, r, qtx, project, privateMemberIDs, inserted) {+ return+ }+ project, err = qtx.UpdateProjectVisibility(r.Context(), db.UpdateProjectVisibilityParams{+ ID: project.ID,+ WorkspaceID: project.WorkspaceID,+ Visibility: projectaccess.VisibilityPrivate,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to set project visibility")+ return+ }+ }creator, _ := h.parseUserUUIDOrZero(userID)resourceRows := make([]db.ProjectResource, 0, len(req.Resources))@@ -521,6 +617,9 @@ func (h *Handler) UpdateProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, prevProject.ID, http.StatusNotFound, "project not found") {+ return+ }userID, ok := requireUserID(w, r)if !ok {return@@ -618,9 +717,20 @@ func (h *Handler) UpdateProject(w http.ResponseWriter, r *http.Request) {params.DueDate = pgtype.Date{Valid: false} // explicit null = clear date}}- project, err := h.Queries.UpdateProject(r.Context(), params)- if err != nil {- h.writeProjectWriteError(w, r, err, "update")+ newLeadType, newLeadID := prevProject.LeadType, prevProject.LeadID+ if params.LeadTypeSet {+ newLeadType = params.LeadType+ }+ if params.LeadIDSet {+ newLeadID = params.LeadID+ }+ leadChanged := newLeadType != prevProject.LeadType || newLeadID != prevProject.LeadID+ access, ok := h.prepareProjectAccessUpdate(w, r, prevProject, req.Visibility, req.MemberIDs, newLeadType, newLeadID, leadChanged)+ if !ok {+ return+ }+ project, ok := h.writeProjectUpdate(w, r, params, access, userID)+ if !ok {return}resp := projectToResponse(project)@@ -648,6 +758,9 @@ func (h *Handler) DeleteProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, project.ID, http.StatusNotFound, "project not found") {+ return+ }if !h.requireProjectDeletion(w, r, project) {return}@@ -687,6 +800,13 @@ func (h *Handler) DeleteProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete project views")return}+ if err := qtx.DeleteProjectMembersByProject(r.Context(), db.DeleteProjectMembersByProjectParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete project members")+ return+ }if err := qtx.DeleteProject(r.Context(), db.DeleteProjectParams{ID: project.ID,WorkspaceID: project.WorkspaceID,@@ -710,7 +830,7 @@ type SearchProjectResponse struct {}// buildProjectSearchQuery builds a dynamic SQL query for project search.-func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool) (string, []any) {+func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool, hiddenProjectIDs ...pgtype.UUID) (string, []any) {phrase = strings.ToLower(phrase)for i, t := range terms {terms[i] = strings.ToLower(t)@@ -826,13 +946,17 @@ func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool))}+ if len(hiddenProjectIDs) > 0 {+ whereClause += fmt.Sprintf(" AND NOT (p.id = ANY(%s::uuid[]))", nextArg(hiddenProjectIDs))+ }+limitParam := nextArg(nil)offsetParam := nextArg(nil)query := fmt.Sprintf(`SELECT p.id, p.workspace_id, p.title, p.description, p.icon,p.status, p.priority, p.lead_type, p.lead_id,p.start_date, p.due_date,- p.created_at, p.updated_at, p.creator_type, p.creator_id,+ p.created_at, p.updated_at, p.visibility, p.creator_type, p.creator_id,%s AS match_sourceFROM project pWHERE p.workspace_id = %s AND %s@@ -884,7 +1008,11 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {}terms := splitSearchTerms(q)- sqlQuery, args := buildProjectSearchQuery(q, terms, includeClosed)+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }+ sqlQuery, args := buildProjectSearchQuery(q, terms, includeClosed, hidden.Param()...)args[1] = wsUUIDargs[len(args)-2] = limitargs[len(args)-1] = offset@@ -912,6 +1040,7 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {&row.project.DueDate,&row.project.CreatedAt,&row.project.UpdatedAt,+ &row.project.Visibility,&row.project.CreatorType,&row.project.CreatorID,&row.matchSource,diff --git a/server/internal/handler/project_access.go b/server/internal/handler/project_access.gonew file mode 100644index 0000000000..ab7812258b--- /dev/null+++ b/server/internal/handler/project_access.go@@ -0,0 +1,290 @@+package handler++import (+ "context"+ "errors"+ "log/slog"+ "net/http"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/projectaccess"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// hiddenProjects returns the private projects (MUL-8472) this request may not+// see. A member request is bounded by the member; an agent request by the+// run's originator and the agent's owner together (projectaccess.RunPrincipals).+//+// Enforcement does not read the private_projects_v1 flag: the flag gates+// creating private projects, and a project that is already private stays+// private whatever the flag says.+func (h *Handler) hiddenProjects(r *http.Request, workspaceID string) (projectaccess.Hidden, error) {+ ctx := r.Context()+ wsUUID, err := util.ParseUUID(workspaceID)+ if err != nil {+ return projectaccess.Hidden{}, err+ }+ userID := requestUserID(r)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ if actorType == "agent" {+ return h.hiddenProjectsForAgentRun(ctx, wsUUID, actorID, r.Header.Get("X-Task-ID"))+ }+ userUUID, err := util.ParseUUID(userID)+ if err != nil {+ return projectaccess.ForPrincipals(ctx, h.Queries, wsUUID)+ }+ if m, ok := ctxMember(ctx); ok && m.WorkspaceID == wsUUID && m.UserID == userUUID {+ return projectaccess.ForMember(ctx, h.Queries, wsUUID, userUUID, m.Role)+ }+ return projectaccess.ForPrincipals(ctx, h.Queries, wsUUID, userUUID)+}++func (h *Handler) hiddenProjectsForAgentRun(ctx context.Context, workspaceID pgtype.UUID, agentID, taskID string) (projectaccess.Hidden, error) {+ // Most workspaces have no private project; skip the run lookups there.+ if private, err := h.Queries.ListPrivateProjectIDs(ctx, workspaceID); err != nil || len(private) == 0 {+ return projectaccess.Hidden{}, err+ }+ agentUUID, agentErr := util.ParseUUID(agentID)+ taskUUID, taskErr := util.ParseUUID(taskID)+ if agentErr != nil || taskErr != nil {+ return projectaccess.ForPrincipals(ctx, h.Queries, workspaceID)+ }+ task, err := h.Queries.GetAgentTask(ctx, taskUUID)+ if errors.Is(err, pgx.ErrNoRows) {+ return projectaccess.ForPrincipals(ctx, h.Queries, workspaceID)+ }+ if err != nil {+ return projectaccess.Hidden{}, err+ }+ agent, err := h.Queries.GetAgent(ctx, agentUUID)+ if errors.Is(err, pgx.ErrNoRows) {+ return projectaccess.ForPrincipals(ctx, h.Queries, workspaceID)+ }+ if err != nil {+ return projectaccess.Hidden{}, err+ }+ return projectaccess.ForPrincipals(ctx, h.Queries, workspaceID, projectaccess.RunPrincipals(task, agent.OwnerID)...)+}++// requestHiddenProjects is hiddenProjects for handlers: it writes a 500 and+// returns ok=false when access cannot be resolved, so callers fail closed.+func (h *Handler) requestHiddenProjects(w http.ResponseWriter, r *http.Request, workspaceID string) (projectaccess.Hidden, bool) {+ hidden, err := h.hiddenProjects(r, workspaceID)+ if err != nil {+ if errors.Is(r.Context().Err(), context.Canceled) && errors.Is(err, context.Canceled) {+ w.WriteHeader(middleware.StatusClientClosedRequest)+ return projectaccess.Hidden{}, false+ }+ slog.Warn("resolve project access failed", append(logger.RequestAttrs(r), "workspace_id", workspaceID, "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")+ return projectaccess.Hidden{}, false+ }+ return hidden, true+}++// requireProjectVisible writes status with notFoundMsg when projectID is a+// private project the request may not see. Callers pass the status and+// message they already use for a missing object: a hidden object must be+// indistinguishable from one that does not exist, so this never answers 403.+func (h *Handler) requireProjectVisible(w http.ResponseWriter, r *http.Request, workspaceID string, projectID pgtype.UUID, status int, notFoundMsg string) bool {+ if !projectID.Valid {+ return true+ }+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return false+ }+ if !hidden.CanSeeProject(projectID) {+ writeError(w, status, notFoundMsg)+ return false+ }+ return true+}++// requireIssueIDVisible is requireProjectVisible for objects that carry only+// an issue id (comments, attachments, reactions).+func (h *Handler) requireIssueIDVisible(w http.ResponseWriter, r *http.Request, workspaceID string, issueID pgtype.UUID, status int, notFoundMsg string) bool {+ if !issueID.Valid {+ return true+ }+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return false+ }+ if hidden.Empty() {+ return true+ }+ projectID, err := h.Queries.GetIssueProjectID(r.Context(), issueID)+ if errors.Is(err, pgx.ErrNoRows) {+ return true+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")+ return false+ }+ if !hidden.CanSeeProject(projectID) {+ writeError(w, status, notFoundMsg)+ return false+ }+ return true+}++// commentInHiddenProject reports whether a comment sits on an issue in a+// private project the request cannot see. A missing comment is not hidden;+// the caller's own lookup answers for it.+func (h *Handler) commentInHiddenProject(r *http.Request, workspaceID string, commentID pgtype.UUID) (bool, error) {+ hidden, err := h.hiddenProjects(r, workspaceID)+ if err != nil || hidden.Empty() {+ return false, err+ }+ projectID, err := h.Queries.GetCommentIssueProjectID(r.Context(), commentID)+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ if err != nil {+ return false, err+ }+ return !hidden.CanSeeProject(projectID), nil+}++// sourceContextProjectVisible answers a hidden target project of a comment+// sub-issue exactly like a missing one.+func (h *Handler) sourceContextProjectVisible(r *http.Request, workspaceID, projectID pgtype.UUID) error {+ hidden, err := h.hiddenProjects(r, uuidToString(workspaceID))+ if err != nil {+ return err+ }+ if !hidden.CanSeeProject(projectID) {+ return sourceContextBadRequest("project not found")+ }+ return nil+}++// requireAssigneeCanAccessProject refuses handing an issue in a private+// project to an agent (or a squad, through its leader) whose owner cannot+// see that project (MUL-8472). Enqueue enforces the same rule+// (service.ErrProjectAccessDenied); checking at assignment turns what would be+// a run that never starts into an explicit 403 with a stable reason code.+func (h *Handler) requireAssigneeCanAccessProject(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, assigneeType pgtype.Text, assigneeID, projectID pgtype.UUID) bool {+ if !projectID.Valid || !assigneeType.Valid || !assigneeID.Valid {+ return true+ }+ ctx := r.Context()+ agentID := assigneeID+ switch assigneeType.String {+ case "agent":+ case "squad":+ squad, err := h.Queries.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: assigneeID, WorkspaceID: workspaceID})+ if err != nil {+ return true // validateAssigneePair owns the missing-squad answer+ }+ agentID = squad.LeaderID+ default:+ return true+ }+ project, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{ID: projectID, WorkspaceID: workspaceID})+ if err != nil || project.Visibility != projectaccess.VisibilityPrivate {+ return true+ }+ agent, err := h.Queries.GetAgent(ctx, agentID)+ if err != nil || !agent.OwnerID.Valid {+ return true+ }+ hidden, err := projectaccess.ForPrincipals(ctx, h.Queries, workspaceID, agent.OwnerID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")+ return false+ }+ if !hidden.CanSeeProject(projectID) {+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonProjectAccessBlocked)+ return false+ }+ return true+}++// requireAttachmentVisible 404s an attachment on an issue (or a comment on an+// issue) in a project the caller cannot see.+func (h *Handler) requireAttachmentVisible(w http.ResponseWriter, r *http.Request, workspaceID string, att db.Attachment) bool {+ if att.IssueID.Valid {+ return h.requireIssueIDVisible(w, r, workspaceID, att.IssueID, http.StatusNotFound, "attachment not found")+ }+ if !att.CommentID.Valid {+ return true+ }+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return false+ }+ if hidden.Empty() {+ return true+ }+ projectID, err := h.Queries.GetCommentIssueProjectID(r.Context(), att.CommentID)+ if errors.Is(err, pgx.ErrNoRows) {+ return true+ }+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")+ return false+ }+ if !hidden.CanSeeProject(projectID) {+ writeError(w, http.StatusNotFound, "attachment not found")+ return false+ }+ return true+}++// requireChatProjectVisible gates a chat session's project context+// (MUL-8472). The context is injected into the chat agent's runs, so both the+// caller and the agent's owner must see the project; otherwise it 404s like a+// missing project.+func (h *Handler) requireChatProjectVisible(w http.ResponseWriter, r *http.Request, workspaceID string, projectID, agentID pgtype.UUID) bool {+ if !projectID.Valid {+ return true+ }+ if !h.requireProjectVisible(w, r, workspaceID, projectID, http.StatusNotFound, "project not found") {+ return false+ }+ agent, err := h.Queries.GetAgent(r.Context(), agentID)+ if err != nil {+ writeError(w, http.StatusNotFound, "agent not found")+ return false+ }+ if !agent.OwnerID.Valid {+ return true+ }+ hidden, err := projectaccess.ForPrincipals(r.Context(), h.Queries, agent.WorkspaceID, agent.OwnerID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")+ return false+ }+ if !hidden.CanSeeProject(projectID) {+ writeError(w, http.StatusNotFound, "project not found")+ return false+ }+ return true+}++// hiddenProjectPredicate is the dynamic-SQL twin of the sqlc+// hidden_project_ids filter: rows outside any project always pass.+func hiddenProjectPredicate(column, param string) string {+ return "(" + column + " IS NULL OR NOT (" + column + " = ANY(" + param + "::uuid[])))"+}++// filterVisibleIssues drops issues in hidden projects from an unpaginated list.+func filterVisibleIssues(hidden projectaccess.Hidden, issues []db.Issue) []db.Issue {+ if hidden.Empty() {+ return issues+ }+ out := issues[:0:0]+ for _, issue := range issues {+ if hidden.CanSeeProject(issue.ProjectID) {+ out = append(out, issue)+ }+ }+ return out+}diff --git a/server/internal/handler/project_member.go b/server/internal/handler/project_member.gonew file mode 100644index 0000000000..ca1ca0f3de--- /dev/null+++ b/server/internal/handler/project_member.go@@ -0,0 +1,478 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/projectaccess"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Private projects (MUL-8472). Who may do what:+//+// - change visibility or lead, add/remove members: workspace+// owner/admin, or the project's member lead+// - ordinary project members: read-only membership, no self-removal+// - agents: none of these; an agent's access is derived from humans+//+// Only switching a project TO private is behind private_projects_v1. Making+// a private project public and managing members keep working with the flag+// off, so turning the flag off never strands an existing private project.++type ProjectMemberResponse struct {+ ProjectID string `json:"project_id"`+ UserID string `json:"user_id"`+ Name string `json:"name"`+ Email string `json:"email"`+ AvatarURL *string `json:"avatar_url"`+ AddedBy *string `json:"added_by"`+ CreatedAt string `json:"created_at"`+ WorkspaceRole string `json:"workspace_role,omitempty"`+}++type AddProjectMembersRequest struct {+ UserIDs []string `json:"user_ids"`+}++// projectAccessUpdate is the validated, not yet written, access side of a+// project update: a visibility switch and the member rows it needs.+type projectAccessUpdate struct {+ visibility string // target visibility; "" leaves it unchanged+ addIDs []pgtype.UUID+}++func (u projectAccessUpdate) empty() bool { return u.visibility == "" && len(u.addIDs) == 0 }++func (h *Handler) requireHumanProjectAccessActor(w http.ResponseWriter, r *http.Request, workspaceID string) bool {+ if actorType, _ := h.resolveActor(r, requestUserID(r), workspaceID); actorType == "agent" {+ writeError(w, http.StatusForbidden, "agents cannot change project access")+ return false+ }+ return true+}++// canManageProjectAccess: workspace owner/admin, or the member lead of a+// private project. Any member may set the lead of a workspace-visible project,+// so leading one grants nothing; making it private takes an owner/admin.+func canManageProjectAccess(member db.Member, project db.Project) bool {+ if projectaccess.IsManagerRole(member.Role) {+ return true+ }+ return projectVisibilityOrDefault(project.Visibility) == projectaccess.VisibilityPrivate &&+ project.LeadType.Valid && project.LeadType.String == "member" && project.LeadID == member.UserID+}++func parseProjectMemberIDs(w http.ResponseWriter, raw []string, field string) ([]pgtype.UUID, bool) {+ ids := make([]pgtype.UUID, 0, len(raw))+ seen := map[pgtype.UUID]struct{}{}+ for _, s := range raw {+ id, ok := parseUUIDOrBadRequest(w, s, field)+ if !ok {+ return nil, false+ }+ if _, dup := seen[id]; dup {+ continue+ }+ seen[id] = struct{}{}+ ids = append(ids, id)+ }+ return ids, true+}++// prepareProjectAccessUpdate validates the access side of a project update+// before anything is written. Two things change who can see a project:+//+// - a visibility switch (requested = nil leaves it alone), which takes a+// human workspace admin or the member lead;+// - on a private project, a new member lead who is not yet a project member.+// A member lead must be a project member, so the update adds them, which+// is granting access: it takes a human who could add members directly.+// Agents never grant access, here or anywhere else.+//+// newLeadType / newLeadID are the lead the project will have after the update.+func (h *Handler) prepareProjectAccessUpdate(w http.ResponseWriter, r *http.Request, project db.Project, requested *string, rawMemberIDs []string, newLeadType pgtype.Text, newLeadID pgtype.UUID, leadChanged bool) (projectAccessUpdate, bool) {+ workspaceID := uuidToString(project.WorkspaceID)+ current := projectVisibilityOrDefault(project.Visibility)+ memberLead := newLeadType.Valid && newLeadType.String == "member" && newLeadID.Valid++ // The lead of a private project manages its access, so changing it is an+ // access change. On a workspace-visible project the lead is an ordinary+ // field anyone can set, as it was before private projects existed.+ if leadChanged && current == projectaccess.VisibilityPrivate {+ if !h.requireHumanProjectAccessActor(w, r, workspaceID) {+ return projectAccessUpdate{}, false+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return projectAccessUpdate{}, false+ }+ if !canManageProjectAccess(member, project) {+ writeError(w, http.StatusForbidden, "only workspace admins and the project lead can change the project lead")+ return projectAccessUpdate{}, false+ }+ }++ if requested != nil && *requested != current {+ target := *requested+ if !projectaccess.ValidVisibility(target) {+ writeError(w, http.StatusBadRequest, "invalid visibility: must be one of workspace, private")+ return projectAccessUpdate{}, false+ }+ if !h.requireHumanProjectAccessActor(w, r, workspaceID) {+ return projectAccessUpdate{}, false+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return projectAccessUpdate{}, false+ }+ if !canManageProjectAccess(member, project) {+ writeError(w, http.StatusForbidden, "only workspace admins and the project lead can change project visibility")+ return projectAccessUpdate{}, false+ }+ if target == projectaccess.VisibilityPrivate && !featureflags.PrivateProjectsV1Enabled(r.Context(), h.FeatureFlags) {+ writeFeatureDisabled(w, "private_projects_disabled", "private projects are not enabled")+ return projectAccessUpdate{}, false+ }+ update := projectAccessUpdate{visibility: target}+ if target == projectaccess.VisibilityPrivate {+ ids, ok := parseProjectMemberIDs(w, rawMemberIDs, "member_ids")+ if !ok {+ return projectAccessUpdate{}, false+ }+ // The caller and a member lead always keep access to a project+ // they make private.+ ids = append(ids, member.UserID)+ if memberLead {+ ids = append(ids, newLeadID)+ }+ update.addIDs = ids+ }+ return update, true+ }++ if current != projectaccess.VisibilityPrivate || !leadChanged || !memberLead {+ return projectAccessUpdate{}, true+ }+ isMember, err := h.isProjectMember(r, project, newLeadID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check project membership")+ return projectAccessUpdate{}, false+ }+ if isMember {+ return projectAccessUpdate{}, true+ }+ return projectAccessUpdate{addIDs: []pgtype.UUID{newLeadID}}, true+}++// writeProjectUpdate stores params and, in the same transaction, a prepared+// access update, so a rejected member list leaves the project untouched.+func (h *Handler) writeProjectUpdate(w http.ResponseWriter, r *http.Request, params db.UpdateProjectParams, access projectAccessUpdate, actorUserID string) (db.Project, bool) {+ ctx := r.Context()+ if access.empty() {+ project, err := h.Queries.UpdateProject(ctx, params)+ if err != nil {+ h.writeProjectWriteError(w, r, err, "update")+ return db.Project{}, false+ }+ return project, true+ }+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start transaction")+ return db.Project{}, false+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ project, err := qtx.UpdateProject(ctx, params)+ if err != nil {+ h.writeProjectWriteError(w, r, err, "update")+ return db.Project{}, false+ }+ if len(access.addIDs) > 0 {+ inserted, err := qtx.AddProjectMembers(ctx, db.AddProjectMembersParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserIds: access.addIDs,+ AddedBy: parseUUIDOrInvalid(actorUserID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to add project members")+ return db.Project{}, false+ }+ if !h.allProjectMembersExist(w, r, qtx, project, access.addIDs, inserted) {+ return db.Project{}, false+ }+ }+ if access.visibility != "" {+ project, err = qtx.UpdateProjectVisibility(ctx, db.UpdateProjectVisibilityParams{+ ID: project.ID,+ WorkspaceID: project.WorkspaceID,+ Visibility: access.visibility,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update project visibility")+ return db.Project{}, false+ }+ }+ if err := touchProjectSearchIndex(r, qtx, project); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update search index")+ return db.Project{}, false+ }+ if err := tx.Commit(ctx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit project update")+ return db.Project{}, false+ }+ if access.visibility != "" {+ slog.Info("project visibility changed", append(logger.RequestAttrs(r),+ "project_id", uuidToString(project.ID), "visibility", project.Visibility)...)+ }+ if len(access.addIDs) > 0 {+ h.publishProjectMembersChanged(project, parseUUIDOrInvalid(actorUserID))+ }+ return project, true+}++// allProjectMembersExist rejects a member list naming users outside the+// workspace. AddProjectMembers skips them (and existing members) silently, so+// anything not inserted must already be a member to count as valid.+func (h *Handler) allProjectMembersExist(w http.ResponseWriter, r *http.Request, q *db.Queries, project db.Project, requested []pgtype.UUID, inserted []db.ProjectMember) bool {+ if len(inserted) == len(requested) {+ return true+ }+ existing, err := q.ListProjectMemberUserIDs(r.Context(), db.ListProjectMemberUserIDsParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list project members")+ return false+ }+ present := make(map[pgtype.UUID]struct{}, len(existing))+ for _, id := range existing {+ present[id] = struct{}{}+ }+ for _, id := range requested {+ if _, ok := present[id]; !ok {+ writeError(w, http.StatusBadRequest, "user "+uuidToString(id)+" is not a member of this workspace")+ return false+ }+ }+ return true+}++func parseUUIDOrInvalid(s string) pgtype.UUID {+ id, err := util.ParseUUID(s)+ if err != nil {+ return pgtype.UUID{}+ }+ return id+}++// loadVisibleProject loads {id} for a project sub-resource and 404s when the+// caller cannot see it.+func (h *Handler) loadVisibleProject(w http.ResponseWriter, r *http.Request) (db.Project, bool) {+ workspaceID := h.resolveWorkspaceID(r)+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "project id")+ if !ok {+ return db.Project{}, false+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return db.Project{}, false+ }+ project, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{ID: idUUID, WorkspaceID: wsUUID})+ if err != nil {+ writeError(w, http.StatusNotFound, "project not found")+ return db.Project{}, false+ }+ if !h.requireProjectVisible(w, r, workspaceID, project.ID, http.StatusNotFound, "project not found") {+ return db.Project{}, false+ }+ return project, true+}++func (h *Handler) listProjectMemberResponses(r *http.Request, project db.Project) ([]ProjectMemberResponse, error) {+ rows, err := h.Queries.ListProjectMembers(r.Context(), db.ListProjectMembersParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ })+ if err != nil {+ return nil, err+ }+ resp := make([]ProjectMemberResponse, len(rows))+ for i, row := range rows {+ resp[i] = ProjectMemberResponse{+ ProjectID: uuidToString(row.ProjectID),+ UserID: uuidToString(row.UserID),+ Name: row.UserName,+ Email: row.UserEmail,+ AvatarURL: textToPtr(row.UserAvatarUrl),+ AddedBy: uuidToPtr(row.AddedBy),+ CreatedAt: timestampToString(row.CreatedAt),+ }+ }+ return resp, nil+}++// ListProjectMembers — GET /api/projects/{id}/members+func (h *Handler) ListProjectMembers(w http.ResponseWriter, r *http.Request) {+ project, ok := h.loadVisibleProject(w, r)+ if !ok {+ return+ }+ resp, err := h.listProjectMemberResponses(r, project)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list project members")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{"members": resp, "total": len(resp)})+}++// AddProjectMembers — POST /api/projects/{id}/members {"user_ids": [...]}+func (h *Handler) AddProjectMembers(w http.ResponseWriter, r *http.Request) {+ project, ok := h.loadVisibleProject(w, r)+ if !ok {+ return+ }+ workspaceID := uuidToString(project.WorkspaceID)+ if !h.requireHumanProjectAccessActor(w, r, workspaceID) {+ return+ }+ var req AddProjectMembersRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ ids, ok := parseProjectMemberIDs(w, req.UserIDs, "user_ids")+ if !ok {+ return+ }+ if len(ids) == 0 {+ writeError(w, http.StatusBadRequest, "user_ids is required")+ return+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ if !canManageProjectAccess(member, project) {+ writeError(w, http.StatusForbidden, "only workspace admins and the project lead can add members")+ return+ }+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start transaction")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ inserted, err := qtx.AddProjectMembers(r.Context(), db.AddProjectMembersParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserIds: ids,+ AddedBy: member.UserID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to add project members")+ return+ }+ if !h.allProjectMembersExist(w, r, qtx, project, ids, inserted) {+ return+ }+ if err := touchProjectSearchIndex(r, qtx, project); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update search index")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit project members")+ return+ }+ h.publishProjectMembersChanged(project, member.UserID)+ h.ListProjectMembers(w, r)+}++// RemoveProjectMember — DELETE /api/projects/{id}/members/{userId}+func (h *Handler) RemoveProjectMember(w http.ResponseWriter, r *http.Request) {+ project, ok := h.loadVisibleProject(w, r)+ if !ok {+ return+ }+ workspaceID := uuidToString(project.WorkspaceID)+ if !h.requireHumanProjectAccessActor(w, r, workspaceID) {+ return+ }+ target, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "userId"), "user id")+ if !ok {+ return+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ if !canManageProjectAccess(member, project) {+ writeError(w, http.StatusForbidden, "only workspace admins and the project lead can remove project members")+ return+ }+ if project.LeadType.Valid && project.LeadType.String == "member" && project.LeadID == target {+ writeError(w, http.StatusConflict, "change the project lead before removing the current lead")+ return+ }+ removed, err := h.Queries.DeleteProjectMember(r.Context(), db.DeleteProjectMemberParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserID: target,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to remove project member")+ return+ }+ if removed == 0 {+ writeError(w, http.StatusNotFound, "project member not found")+ return+ }+ if err := touchProjectSearchIndex(r, h.Queries, project); err != nil {+ slog.Warn("touch project search index failed", append(logger.RequestAttrs(r), "project_id", uuidToString(project.ID), "error", err)...)+ }+ h.publishProjectMembersChanged(project, member.UserID)+ w.WriteHeader(http.StatusNoContent)+}++func (h *Handler) isProjectMember(r *http.Request, project db.Project, userID pgtype.UUID) (bool, error) {+ ids, err := h.Queries.ListProjectMemberUserIDs(r.Context(), db.ListProjectMemberUserIDsParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ })+ if err != nil {+ return false, err+ }+ for _, id := range ids {+ if id == userID {+ return true, nil+ }+ }+ return false, nil+}++func (h *Handler) publishProjectMembersChanged(project db.Project, actorUserID pgtype.UUID) {+ h.publish(protocol.EventProjectMembersChanged, uuidToString(project.WorkspaceID), "member", uuidToString(actorUserID), map[string]any{+ "project_id": uuidToString(project.ID),+ })+}++// touchProjectSearchIndex re-announces a project's issues and comments to+// local search sync, so every client re-pulls them under its current access:+// upserts where it can see them, deletions where it cannot.+func touchProjectSearchIndex(r *http.Request, q *db.Queries, project db.Project) error {+ return q.TouchProjectSearchIndexEntries(r.Context(), db.TouchProjectSearchIndexEntriesParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ })+}diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex 4cb5d6b643..e9d4e689c4 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -529,6 +529,9 @@ func (h *Handler) loadProjectForResource(w http.ResponseWriter, r *http.Request,writeError(w, http.StatusNotFound, "project not found")return db.Project{}, false}+ if !h.requireProjectVisible(w, r, uuidToString(wsUUID), project.ID, http.StatusNotFound, "project not found") {+ return db.Project{}, false+ }return project, true}diff --git a/server/internal/handler/reaction.go b/server/internal/handler/reaction.goindex 4266aab651..0df18302a9 100644--- a/server/internal/handler/reaction.go+++ b/server/internal/handler/reaction.go@@ -77,6 +77,9 @@ func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}+ if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusNotFound, "comment not found") {+ return+ }var req struct {Emoji string `json:"emoji"`@@ -167,6 +170,9 @@ func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "comment not found")return}+ if !h.requireIssueIDVisible(w, r, workspaceID, comment.IssueID, http.StatusNotFound, "comment not found") {+ return+ }var req struct {Emoji string `json:"emoji"`diff --git a/server/internal/handler/search_index.go b/server/internal/handler/search_index.goindex 913eea615e..3380a236e4 100644--- a/server/internal/handler/search_index.go+++ b/server/internal/handler/search_index.go@@ -14,11 +14,13 @@ import ("strings""time"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/projectaccess"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -377,20 +379,36 @@ func (h *Handler) GetSearchIndexSnapshot(w http.ResponseWriter, r *http.Request)h.writeSearchIndexError(w, r, "snapshot", err)return}+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ // Paging advances over the unfiltered page so a hidden issue cannot end+ // the snapshot early or stall it.+ pageLen := len(issues)+ nextAfterNumber := int32(afterNumber)+ if pageLen > 0 {+ nextAfterNumber = issues[pageLen-1].Number+ }+ visibleIssues := filterVisibleIssues(hidden, issues)+ visibleIssueIDs := make(map[pgtype.UUID]bool, len(visibleIssues))+ for _, is := range visibleIssues {+ visibleIssueIDs[is.ID] = true+ }resp := SearchIndexSnapshotResponse{- Issues: h.searchIndexIssues(ctx, wsUUID, issues),+ Issues: h.searchIndexIssues(ctx, wsUUID, visibleIssues),Comments: make([]SearchIndexComment, 0, len(comments)),- Projects: searchIndexProjects(projects),- NextAfterNumber: int32(afterNumber),- Done: len(issues) < limit,+ Projects: searchIndexProjects(visibleProjects(hidden, projects)),+ NextAfterNumber: nextAfterNumber,+ Done: pageLen < limit,}for _, c := range comments {+ if !visibleIssueIDs[c.IssueID] {+ continue+ }resp.Comments = append(resp.Comments, searchIndexComment(c.ID, c.IssueID, c.Content, c.CreatedAt))}- if n := len(issues); n > 0 {- resp.NextAfterNumber = issues[n-1].Number- }writeJSON(w, http.StatusOK, resp)}@@ -503,6 +521,33 @@ func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusGone, "search index cursor expired; rebuild the local index")return}+ // Entities in a project the caller cannot see are reported as deleted, so+ // a client that synced them before losing access drops its copy.+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))+ if !ok {+ return+ }+ if !hidden.Empty() {+ issues = filterVisibleIssues(hidden, issues)+ projects = visibleProjects(hidden, projects)+ visibleComments := comments[:0:0]+ issueProjects := map[pgtype.UUID]pgtype.UUID{}+ for _, c := range comments {+ projectID, seen := issueProjects[c.IssueID]+ if !seen {+ projectID, err = h.Queries.GetIssueProjectID(ctx, c.IssueID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ h.writeSearchIndexError(w, r, "changes", err)+ return+ }+ issueProjects[c.IssueID] = projectID+ }+ if hidden.CanSeeProject(projectID) {+ visibleComments = append(visibleComments, c)+ }+ }+ comments = visibleComments+ }resp := SearchIndexChangesResponse{Issues: h.searchIndexIssues(ctx, wsUUID, issues),@@ -606,3 +651,16 @@ func searchIndexComment(id, issueID pgtype.UUID, content string, createdAt pgtypCreatedAt: createdAt.Time.UTC().Format(time.RFC3339Nano),}}++func visibleProjects(hidden projectaccess.Hidden, projects []db.Project) []db.Project {+ if hidden.Empty() {+ return projects+ }+ out := projects[:0:0]+ for _, p := range projects {+ if hidden.CanSeeProject(p.ID) {+ out = append(out, p)+ }+ }+ return out+}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex c94834034f..f0a940a02b 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -416,6 +416,15 @@ func (h *Handler) PreviewCommentSubIssue(w http.ResponseWriter, r *http.Request)if !ok {return}+ // MUL-8472: a comment in a private project the caller cannot see reads as+ // a missing one, here as on every other comment route.+ if hiddenComment, err := h.commentInHiddenProject(r, workspaceID, anchorCommentID); err != nil || hiddenComment {+ if err == nil {+ err = service.ErrAnchorCommentDeleted+ }+ h.writeSourceContextError(w, err, service.SourceContextLimitUsage{})+ return+ }build, err := service.BuildSourceContext(r.Context(), h.Queries, wsUUID, anchorCommentID)if err != nil {h.writeSourceContextError(w, err, build.Limits)@@ -460,6 +469,15 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)if !ok {return}+ // MUL-8472: a comment in a private project the caller cannot see reads as+ // a missing one, here as on every other comment route.+ if hiddenComment, err := h.commentInHiddenProject(r, workspaceID, anchorCommentID); err != nil || hiddenComment {+ if err == nil {+ err = service.ErrAnchorCommentDeleted+ }+ h.writeSourceContextError(w, err, service.SourceContextLimitUsage{})+ return+ }wantDigest, tokenIssueID, validToken := service.ParseSourceContextToken(strings.TrimSpace(req.CaptureToken))if !validToken {writeJSON(w, http.StatusConflict, map[string]any{"code": "source_context_changed", "error": "source context preview is invalid; refresh and try again"})@@ -680,6 +698,9 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Reqif err != nil {return sourceContextBadRequest("invalid project_id")}+ if err := h.sourceContextProjectVisible(r, workspaceID, parsed); err != nil {+ return err+ }projectID = parsed}attachmentIDs, ok := parseUUIDSliceOrBadRequest(w, input.AttachmentIDs, "attachment_ids")@@ -843,6 +864,9 @@ func (h *Handler) prepareAgentCommentSubIssue(w http.ResponseWriter, r *http.Reqif _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{ID: parsed, WorkspaceID: workspaceID}); err != nil {return nil, sourceContextBadRequest("project not found")}+ if err := h.sourceContextProjectVisible(r, workspaceID, parsed); err != nil {+ return nil, err+ }projectID = parsed}return &preparedAgentCommentSubIssue{@@ -911,6 +935,9 @@ func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limicase errors.Is(err, errSourceContextBadRequest):status, code = http.StatusBadRequest, "invalid_request"message = err.Error()+ case errors.Is(err, service.ErrProjectAccessDenied):+ status, code = http.StatusForbidden, string(ReasonProjectAccessBlocked)+ message = dispatchBlockedFallbackMessage(ReasonProjectAccessBlocked)case err == nil:return}diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.goindex 2049a7b20d..0e80d31aec 100644--- a/server/internal/handler/task_lifecycle.go+++ b/server/internal/handler/task_lifecycle.go@@ -253,6 +253,10 @@ func (h *Handler) rerunIssue(w http.ResponseWriter, r *http.Request, issue db.Ish.writeDispatchBlocked(w, http.StatusForbidden, ReasonIssueInTriage)return}+ if errors.Is(err, service.ErrProjectAccessDenied) {+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonProjectAccessBlocked)+ return+ }// Not a dispatch refusal: the issue may well be runnable, and only the named// source is ineligible. It falls through to the 400 below with the// sentinel's own sentence, like the sibling "does not belong to this issue".diff --git a/server/internal/handler/task_project_privacy.go b/server/internal/handler/task_project_privacy.gonew file mode 100644index 0000000000..c332fe25ce--- /dev/null+++ b/server/internal/handler/task_project_privacy.go@@ -0,0 +1,87 @@+package handler++import (+ "net/http"++ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// redactHiddenProjectTasks replaces every run on an issue in a private project+// the caller cannot see (MUL-8472) with restrictedTaskResponse. The runs stay+// in the list so an agent's working state and workload counts read the same+// for everyone; only what they were about is removed. tasks and resp are+// parallel slices.+func (h *Handler) redactHiddenProjectTasks(r *http.Request, workspaceID string, tasks []db.AgentTaskQueue, resp []AgentTaskResponse) error {+ hidden, err := h.hiddenProjects(r, workspaceID)+ if err != nil {+ return err+ }+ if hidden.Empty() {+ return nil+ }+ seen := map[pgtype.UUID]struct{}{}+ var issueIDs []pgtype.UUID+ for _, t := range tasks {+ if !t.IssueID.Valid {+ continue+ }+ if _, ok := seen[t.IssueID]; ok {+ continue+ }+ seen[t.IssueID] = struct{}{}+ issueIDs = append(issueIDs, t.IssueID)+ }+ if len(issueIDs) == 0 {+ return nil+ }+ rows, err := h.Queries.ListIssueProjectIDs(r.Context(), issueIDs)+ if err != nil {+ return err+ }+ projectOf := make(map[pgtype.UUID]pgtype.UUID, len(rows))+ for _, row := range rows {+ projectOf[row.ID] = row.ProjectID+ }+ for i, t := range tasks {+ if !t.IssueID.Valid {+ continue+ }+ if hidden.CanSeeProject(projectOf[t.IssueID]) {+ continue+ }+ resp[i] = restrictedTaskResponse(resp[i])+ }+ return nil+}++// restrictedTaskResponse keeps only what agent presence, workload and the+// run-history row shape need. It copies an allowlist instead of clearing a+// denylist so a field added to AgentTaskResponse later is withheld by+// default.+func restrictedTaskResponse(full AgentTaskResponse) AgentTaskResponse {+ return AgentTaskResponse{+ Restricted: true,+ ID: full.ID,+ AgentID: full.AgentID,+ RuntimeID: full.RuntimeID,+ WorkspaceID: full.WorkspaceID,+ WorkspaceSlug: full.WorkspaceSlug,+ Status: full.Status,+ Priority: full.Priority,+ DispatchedAt: full.DispatchedAt,+ StartedAt: full.StartedAt,+ CompletedAt: full.CompletedAt,+ FailureReason: full.FailureReason,+ Attempt: full.Attempt,+ MaxAttempts: full.MaxAttempts,+ ParentTaskID: full.ParentTaskID,+ IsLeaderTask: full.IsLeaderTask,+ CreatedAt: full.CreatedAt,+ Kind: full.Kind,+ Usage: full.Usage,+ // Always present on the wire (see the field's comment); empty here.+ DeliveredCommentIDs: []string{},+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 4751d98890..e16f493dd9 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -117,6 +117,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"plugin_package_version": workspaceDelete,"plugin_package_file": workspaceDelete,"project": workspaceDelete,+ "project_member": workspaceDelete,"project_resource": workspaceDelete,"quick_action": workspaceDelete,"runtime_profile": workspaceDelete,diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 2593c74a98..206b15027d 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -265,6 +265,13 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDresult.ReadyChats = append(result.ReadyChats, readyChats...)}+ // No FK cascade (repo rule): a departing member leaves every private+ // project in the workspace.+ if err := qtx.DeleteProjectMembersByUser(ctx, db.DeleteProjectMembersByUserParams{+ WorkspaceID: workspaceID, UserID: userID,+ }); err != nil {+ return empty, err+ }if err := qtx.DeleteMember(ctx, memberID); err != nil {return empty, err}diff --git a/server/internal/projectaccess/projectaccess.go b/server/internal/projectaccess/projectaccess.gonew file mode 100644index 0000000000..0035a1328c--- /dev/null+++ b/server/internal/projectaccess/projectaccess.go@@ -0,0 +1,177 @@+// Package projectaccess decides which private projects (MUL-8472) a viewer may+// see. It is the single source of the rule; handlers, the task service and the+// realtime fanout all call into it instead of re-deriving visibility.+//+// The rule: a project with visibility "private" is visible to its+// project_member rows and to workspace owners/admins. Every other project is+// visible to every workspace member. An issue's visibility is its project's.+//+// A viewer is a set of principals (human user ids). A member request has one+// principal: the member. An agent run has two: the human who triggered it and+// the agent's owner, and sees a private project only when both can. A viewer+// with no principal sees no private project.+package projectaccess++import (+ "context"+ "errors"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ VisibilityWorkspace = "workspace"+ VisibilityPrivate = "private"+)++// ValidVisibility reports whether v is a storable project visibility.+func ValidVisibility(v string) bool {+ return v == VisibilityWorkspace || v == VisibilityPrivate+}++// IsManagerRole reports whether a workspace role sees every private project.+func IsManagerRole(role string) bool {+ return role == "owner" || role == "admin"+}++// Querier is the subset of *db.Queries this package reads.+type Querier interface {+ GetMemberByUserAndWorkspace(ctx context.Context, arg db.GetMemberByUserAndWorkspaceParams) (db.Member, error)+ ListHiddenProjectIDsForUser(ctx context.Context, arg db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error)+ ListPrivateProjectIDs(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error)+}++// Hidden is the set of private projects a viewer may not see. The zero value+// hides nothing.+type Hidden struct {+ ids []pgtype.UUID+ set map[[16]byte]struct{}+}++func newHidden() Hidden { return Hidden{set: map[[16]byte]struct{}{}} }++func (h *Hidden) add(ids []pgtype.UUID) {+ for _, id := range ids {+ if !id.Valid {+ continue+ }+ if _, ok := h.set[id.Bytes]; ok {+ continue+ }+ h.set[id.Bytes] = struct{}{}+ h.ids = append(h.ids, id)+ }+}++// Empty reports whether the viewer sees every project.+func (h Hidden) Empty() bool { return len(h.ids) == 0 }++// CanSeeProject reports whether an object in projectID is visible. Objects+// outside any project (invalid projectID) are always visible.+func (h Hidden) CanSeeProject(projectID pgtype.UUID) bool {+ if !projectID.Valid || len(h.set) == 0 {+ return true+ }+ _, hidden := h.set[projectID.Bytes]+ return !hidden+}++// Param is the value for a `hidden_project_ids` query argument: nil when+// nothing is hidden, so the SQL predicate short-circuits.+func (h Hidden) Param() []pgtype.UUID {+ if len(h.ids) == 0 {+ return nil+ }+ return h.ids+}++// IDs returns the hidden project ids (never nil, for dynamic SQL builders).+func (h Hidden) IDs() []pgtype.UUID {+ if h.ids == nil {+ return []pgtype.UUID{}+ }+ return h.ids+}++// ForMember computes the hidden set for one workspace member whose role the+// caller already knows (request middleware loaded it).+func ForMember(ctx context.Context, q Querier, workspaceID, userID pgtype.UUID, role string) (Hidden, error) {+ h := newHidden()+ if IsManagerRole(role) {+ return h, nil+ }+ ids, err := q.ListHiddenProjectIDsForUser(ctx, db.ListHiddenProjectIDsForUserParams{+ WorkspaceID: workspaceID,+ UserID: userID,+ })+ if err != nil {+ return Hidden{}, err+ }+ h.add(ids)+ return h, nil+}++// ForPrincipals computes the hidden set for a viewer whose access is bounded+// by every listed principal: a project is visible only when each of them can+// see it. Invalid ids are ignored; when none remain, every private project is+// hidden. A principal who is no longer a workspace member sees no private+// project.+func ForPrincipals(ctx context.Context, q Querier, workspaceID pgtype.UUID, principals ...pgtype.UUID) (Hidden, error) {+ h := newHidden()+ private, err := q.ListPrivateProjectIDs(ctx, workspaceID)+ if err != nil {+ return Hidden{}, err+ }+ if len(private) == 0 {+ return h, nil+ }+ all := newHidden()+ all.add(private)+ seen := map[[16]byte]struct{}{}+ var valid []pgtype.UUID+ for _, p := range principals {+ if !p.Valid {+ continue+ }+ if _, ok := seen[p.Bytes]; ok {+ continue+ }+ seen[p.Bytes] = struct{}{}+ valid = append(valid, p)+ }+ if len(valid) == 0 {+ return all, nil+ }+ for _, p := range valid {+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ UserID: p,+ WorkspaceID: workspaceID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return all, nil+ }+ if err != nil {+ return Hidden{}, err+ }+ one, err := ForMember(ctx, q, workspaceID, p, member.Role)+ if err != nil {+ return Hidden{}, err+ }+ h.add(one.ids)+ }+ return h, nil+}++// RunPrincipals returns the humans that bound an agent run's access: the+// run's originator (falling back to its accountable user, which is how+// owner_fallback and autopilot runs record their human) and the agent owner.+func RunPrincipals(task db.AgentTaskQueue, agentOwnerID pgtype.UUID) []pgtype.UUID {+ originator := task.OriginatorUserID+ if !originator.Valid {+ originator = task.AccountableUserID+ }+ return []pgtype.UUID{originator, agentOwnerID}+}diff --git a/server/internal/projectaccess/projectaccess_test.go b/server/internal/projectaccess/projectaccess_test.gonew file mode 100644index 0000000000..ed3e2565d3--- /dev/null+++ b/server/internal/projectaccess/projectaccess_test.go@@ -0,0 +1,106 @@+package projectaccess++import (+ "context"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func uid(b byte) pgtype.UUID {+ var id pgtype.UUID+ id.Bytes[15] = b+ id.Valid = true+ return id+}++// fakeQuerier: private projects p1 and p2; user 1 is an admin, user 2 is a+// member of p1 only, user 3 is a member of nothing, user 4 is not in the+// workspace.+type fakeQuerier struct{}++var (+ p1, p2 = uid(101), uid(102)+ admin, p1Member, nonMember, notInWork = uid(1), uid(2), uid(3), uid(4)+)++func (fakeQuerier) GetMemberByUserAndWorkspace(_ context.Context, arg db.GetMemberByUserAndWorkspaceParams) (db.Member, error) {+ switch arg.UserID {+ case admin:+ return db.Member{UserID: admin, Role: "admin"}, nil+ case p1Member, nonMember:+ return db.Member{UserID: arg.UserID, Role: "member"}, nil+ }+ return db.Member{}, pgx.ErrNoRows+}++func (fakeQuerier) ListHiddenProjectIDsForUser(_ context.Context, arg db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error) {+ if arg.UserID == p1Member {+ return []pgtype.UUID{p2}, nil+ }+ return []pgtype.UUID{p1, p2}, nil+}++func (fakeQuerier) ListPrivateProjectIDs(context.Context, pgtype.UUID) ([]pgtype.UUID, error) {+ return []pgtype.UUID{p1, p2}, nil+}++func TestForPrincipals(t *testing.T) {+ ws := uid(200)+ for _, tc := range []struct {+ name string+ principals []pgtype.UUID+ seeP1 bool+ seeP2 bool+ }{+ {"admin sees every project", []pgtype.UUID{admin}, true, true},+ {"member sees their project only", []pgtype.UUID{p1Member}, true, false},+ {"run needs both humans: admin and member", []pgtype.UUID{admin, p1Member}, true, false},+ {"run needs both humans: member and outsider", []pgtype.UUID{p1Member, nonMember}, false, false},+ {"principal outside the workspace sees nothing private", []pgtype.UUID{admin, notInWork}, false, false},+ {"no principal sees nothing private", nil, false, false},+ {"invalid principals are ignored", []pgtype.UUID{{}, p1Member}, true, false},+ } {+ hidden, err := ForPrincipals(context.Background(), fakeQuerier{}, ws, tc.principals...)+ if err != nil {+ t.Fatalf("%s: %v", tc.name, err)+ }+ if got := hidden.CanSeeProject(p1); got != tc.seeP1 {+ t.Errorf("%s: p1 visible = %v, want %v", tc.name, got, tc.seeP1)+ }+ if got := hidden.CanSeeProject(p2); got != tc.seeP2 {+ t.Errorf("%s: p2 visible = %v, want %v", tc.name, got, tc.seeP2)+ }+ if !hidden.CanSeeProject(pgtype.UUID{}) {+ t.Errorf("%s: an object outside any project must stay visible", tc.name)+ }+ }+}++func TestHiddenParamIsNilWhenNothingHidden(t *testing.T) {+ hidden, err := ForMember(context.Background(), fakeQuerier{}, uid(200), admin, "owner")+ if err != nil {+ t.Fatal(err)+ }+ if hidden.Param() != nil || !hidden.Empty() {+ t.Fatalf("owner hidden set = %v", hidden.Param())+ }+ if hidden.IDs() == nil {+ t.Fatal("IDs must never be nil")+ }+}++func TestRunPrincipalsFallsBackToAccountableUser(t *testing.T) {+ owner := uid(9)+ got := RunPrincipals(db.AgentTaskQueue{AccountableUserID: owner}, owner)+ if got[0] != owner || got[1] != owner {+ t.Fatalf("owner_fallback run principals = %v", got)+ }+ got = RunPrincipals(db.AgentTaskQueue{OriginatorUserID: p1Member, AccountableUserID: owner}, owner)+ if got[0] != p1Member {+ t.Fatalf("originator must win over accountable: %v", got)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 9942f670a5..cc7259e819 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1318,6 +1318,9 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issueslog.Warn("task enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(issue.AssigneeID))return db.AgentTaskQueue{}, err}+ if err := s.guardRunProjectAccess(ctx, issue, agent, attr.UserID, attr.AccountableUserID); err != nil {+ return db.AgentTaskQueue{}, err+ }originatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)@@ -1491,6 +1494,9 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issslog.Warn("mention task enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))return db.AgentTaskQueue{}, err}+ if err := s.guardRunProjectAccess(ctx, issue, agent, attr.UserID, attr.AccountableUserID); err != nil {+ return db.AgentTaskQueue{}, err+ }originatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)@@ -1693,6 +1699,11 @@ func (s *TaskService) enqueueQuickCreateTask(ctx context.Context, workspaceID, rif err != nil {return db.AgentTaskQueue{}, err}+ // The claim hands this run the project's description and resources (and+ // the parent issue for a sub-issue), so it is gated like an issue run.+ if err := s.guardQuickCreateProjectAccess(ctx, workspaceID, agent, requesterID, attr.AccountableUserID, projectID, parentIssueID); err != nil {+ return db.AgentTaskQueue{}, err+ }attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)taskID := dbid.NewV7()@@ -7539,17 +7550,14 @@ func (s *TaskService) notifyRuntimeMayHaveWork(runtimeID pgtype.UUID, taskID str}func (s *TaskService) broadcastTaskDispatch(ctx context.Context, task db.AgentTaskQueue) {- var payload map[string]any- if task.Context != nil {- json.Unmarshal(task.Context, &payload)- }- if payload == nil {- payload = map[string]any{}+ // Dispatch is a workspace-wide invalidation hint. Task context may contain+ // private prompts; the daemon receives it through the claim response.+ payload := map[string]any{+ "task_id": util.UUIDToString(task.ID),+ "runtime_id": util.UUIDToString(task.RuntimeID),+ "issue_id": util.UUIDToString(task.IssueID),+ "agent_id": util.UUIDToString(task.AgentID),}- payload["task_id"] = util.UUIDToString(task.ID)- payload["runtime_id"] = util.UUIDToString(task.RuntimeID)- payload["issue_id"] = util.UUIDToString(task.IssueID)- payload["agent_id"] = util.UUIDToString(task.AgentID)// chat_session_id is the routing key the chat window uses to writethrough// `chatKeys.pendingTask` to status="running" the moment the daemon claims// the task. Without it the pill stays stuck at "Queued" until completion.diff --git a/server/internal/service/task_project_access.go b/server/internal/service/task_project_access.gonew file mode 100644index 0000000000..65da1f6915--- /dev/null+++ b/server/internal/service/task_project_access.go@@ -0,0 +1,87 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "log/slog"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/projectaccess"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// ErrProjectAccessDenied refuses a run that would read a private project+// (MUL-8472) its human (originator, else accountable user) or its agent's+// owner cannot see. An agent has no project access of its own: a run reads a+// private project only when both of those people can.+var ErrProjectAccessDenied = errors.New("the run's member or the agent's owner cannot access this private project")++// guardRunProjectAccess is the enqueue-time check behind ErrProjectAccessDenied+// for a run on an existing issue.+func (s *TaskService) guardRunProjectAccess(ctx context.Context, issue db.Issue, agent db.Agent, originatorUserID, accountableUserID pgtype.UUID) error {+ return s.guardRunProjectsAccess(ctx, issue.WorkspaceID, agent, originatorUserID, accountableUserID, issue.ProjectID)+}++// guardQuickCreateProjectAccess covers a quick-create run, which has no issue+// yet but is handed the target project's context and, for a sub-issue, its+// parent. Both the chosen project and the parent's project are checked.+func (s *TaskService) guardQuickCreateProjectAccess(ctx context.Context, workspaceID pgtype.UUID, agent db.Agent, requesterID, accountableUserID, projectID, parentIssueID pgtype.UUID) error {+ projects := []pgtype.UUID{projectID}+ if parentIssueID.Valid {+ parentProject, err := s.Queries.GetIssueProjectID(ctx, parentIssueID)+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {+ return fmt.Errorf("load parent issue project: %w", err)+ }+ projects = append(projects, parentProject)+ }+ return s.guardRunProjectsAccess(ctx, workspaceID, agent, requesterID, accountableUserID, projects...)+}++// guardRunProjectsAccess refuses the run when any of projectIDs is a private+// project the run's human or the agent's owner cannot see. Projects that are+// not private pass after one read each.+func (s *TaskService) guardRunProjectsAccess(ctx context.Context, workspaceID pgtype.UUID, agent db.Agent, originatorUserID, accountableUserID pgtype.UUID, projectIDs ...pgtype.UUID) error {+ var private []pgtype.UUID+ for _, projectID := range projectIDs {+ if !projectID.Valid {+ continue+ }+ project, err := s.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{+ ID: projectID,+ WorkspaceID: workspaceID,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ continue+ }+ if err != nil {+ return fmt.Errorf("load project: %w", err)+ }+ if project.Visibility == projectaccess.VisibilityPrivate {+ private = append(private, projectID)+ }+ }+ if len(private) == 0 {+ return nil+ }+ human := originatorUserID+ if !human.Valid {+ human = accountableUserID+ }+ hidden, err := projectaccess.ForPrincipals(ctx, s.Queries, workspaceID, human, agent.OwnerID)+ if err != nil {+ return fmt.Errorf("resolve project access: %w", err)+ }+ for _, projectID := range private {+ if !hidden.CanSeeProject(projectID) {+ slog.Info("task enqueue refused: private project access",+ "agent_id", util.UUIDToString(agent.ID),+ "project_id", util.UUIDToString(projectID))+ return ErrProjectAccessDenied+ }+ }+ return nil+}diff --git a/server/migrations/630_project_visibility.down.sql b/server/migrations/630_project_visibility.down.sqlnew file mode 100644index 0000000000..92c0004580--- /dev/null+++ b/server/migrations/630_project_visibility.down.sql@@ -0,0 +1 @@+ALTER TABLE project DROP COLUMN IF EXISTS visibility;diff --git a/server/migrations/630_project_visibility.up.sql b/server/migrations/630_project_visibility.up.sqlnew file mode 100644index 0000000000..a552ad343c--- /dev/null+++ b/server/migrations/630_project_visibility.up.sql@@ -0,0 +1,8 @@+-- MUL-8472: private projects. 'workspace' keeps today's behavior (every+-- workspace member sees the project and its issues); 'private' limits it to+-- project_member rows plus workspace owners/admins.+--+-- The constant default makes this a catalog-only change. Values are validated+-- in code (handler.validProjectVisibilities); there is no CHECK constraint so+-- the ALTER does not scan the table, the same trade-off as inbox_item.section.+ALTER TABLE project ADD COLUMN IF NOT EXISTS visibility TEXT NOT NULL DEFAULT 'workspace';diff --git a/server/migrations/631_project_member.down.sql b/server/migrations/631_project_member.down.sqlnew file mode 100644index 0000000000..952693f1f7--- /dev/null+++ b/server/migrations/631_project_member.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS project_member;diff --git a/server/migrations/631_project_member.up.sql b/server/migrations/631_project_member.up.sqlnew file mode 100644index 0000000000..3c7cb99955--- /dev/null+++ b/server/migrations/631_project_member.up.sql@@ -0,0 +1,14 @@+-- MUL-8472: membership of a private project. Rows only matter while the+-- project is private; a workspace-visible project keeps its rows so flipping+-- it back to private restores the same list.+--+-- No foreign keys (repo rule): project deletion, member removal and workspace+-- teardown delete these rows in application code.+CREATE TABLE IF NOT EXISTS project_member (+ workspace_id UUID NOT NULL,+ project_id UUID NOT NULL,+ user_id UUID NOT NULL,+ added_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, user_id)+);diff --git a/server/migrations/632_project_member_user_idx.down.sql b/server/migrations/632_project_member_user_idx.down.sqlnew file mode 100644index 0000000000..af3b47b972--- /dev/null+++ b/server/migrations/632_project_member_user_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_project_member_workspace_user;diff --git a/server/migrations/632_project_member_user_idx.up.sql b/server/migrations/632_project_member_user_idx.up.sqlnew file mode 100644index 0000000000..125c6cb5cd--- /dev/null+++ b/server/migrations/632_project_member_user_idx.up.sql@@ -0,0 +1,4 @@+-- Serves the per-request "which private projects can this user see" lookup and+-- the member-removal cleanup, both keyed by (workspace, user).+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_project_member_workspace_user+ ON project_member (workspace_id, user_id);diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 7c6afedfdf..4a91c1b69b 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -189,18 +189,34 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt}const countUnreadInbox = `-- name: CountUnreadInbox :one-SELECT count(*) FROM inbox_item-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false+SELECT count(*) FROM inbox_item i+WHERE i.workspace_id = $1+ AND i.recipient_type = $2+ AND i.recipient_id = $3+ AND i.read = false+ AND i.archived = false+ -- MUL-8472: private projects the caller cannot see.+ AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY($4::uuid[])+ ))`type CountUnreadInboxParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientType string `json:"recipient_type"`- RecipientID pgtype.UUID `json:"recipient_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`}func (q *Queries) CountUnreadInbox(ctx context.Context, arg CountUnreadInboxParams) (int64, error) {- row := q.db.QueryRow(ctx, countUnreadInbox, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)+ row := q.db.QueryRow(ctx, countUnreadInbox,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.HiddenProjectIds,+ )var count int64err := row.Scan(&count)return count, err@@ -216,6 +232,18 @@ FROM (WHERE i.recipient_type = 'member'AND i.recipient_id = $1AND i.archived = false+ -- MUL-8472: issues in private projects the recipient is outside of+ -- (neither a project member nor a workspace owner/admin) do not count.+ AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = i.issue_id+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id+ )+ ))ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC) newestWHERE newest.read = false@@ -265,10 +293,25 @@ INSERT INTO inbox_item (actor_type, actor_id, details, id)SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid())-WHERE ($2::text = 'member' AND EXISTS (+WHERE (($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (SELECT 1 FROM agent WHERE workspace_id = $1 AND id = $3+)))+AND NOT ($2::text = 'member' AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = $6+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = $3+ )+ AND NOT EXISTS (+ SELECT 1 FROM member manager+ WHERE manager.workspace_id = $1 AND manager.user_id = $3+ AND manager.role IN ('owner', 'admin')+ )))RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`@@ -290,6 +333,8 @@ type CreateInboxItemParams struct {// A missing recipient is a quiet skip (pgx.ErrNoRows), not a delivery failure.// Check the insertion snapshot without adding recipient row locks.+// MUL-8472: a member outside a private project gets no notification about its+// issues. Owners/admins and project members do.func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams) (InboxItem, error) {row := q.db.QueryRow(ctx, createInboxItem,arg.WorkspaceID,@@ -401,6 +446,12 @@ WITH eligible_archived AS MATERIALIZED (AND i.recipient_type = $2AND i.recipient_id = $3AND i.archived = true+ -- MUL-8472: private projects the caller cannot see.+ AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY($4::uuid[])+ ))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1FROM inbox_item active@@ -452,9 +503,10 @@ ORDER BY i.created_at DESC, i.id DESC`type ListArchivedInboxItemsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientType string `json:"recipient_type"`- RecipientID pgtype.UUID `json:"recipient_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`}type ListArchivedInboxItemsRow struct {@@ -505,7 +557,12 @@ type ListArchivedInboxItemsRow struct {// Keep the materialized working set narrow: full row data is joined only for// the final selected ids, not copied for every archived notification scanned.func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedInboxItemsParams) ([]ListArchivedInboxItemsRow, error) {- rows, err := q.db.Query(ctx, listArchivedInboxItems, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)+ rows, err := q.db.Query(ctx, listArchivedInboxItems,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.HiddenProjectIds,+ )if err != nil {return nil, err}@@ -562,13 +619,15 @@ SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severitFROM inbox_item iLEFT JOIN issue iss ON iss.id = i.issue_idWHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = false+ AND ($4::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY($4::uuid[])))ORDER BY i.created_at DESC`type ListInboxItemsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientType string `json:"recipient_type"`- RecipientID pgtype.UUID `json:"recipient_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`}type ListInboxItemsRow struct {@@ -601,7 +660,12 @@ type ListInboxItemsRow struct {// identical to ListArchivedInboxItems: the handler converts one row type into// the other.func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams) ([]ListInboxItemsRow, error) {- rows, err := q.db.Query(ctx, listInboxItems, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)+ rows, err := q.db.Query(ctx, listInboxItems,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.HiddenProjectIds,+ )if err != nil {return nil, err}diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex d695168fd4..cb191aa94f 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -30,6 +30,12 @@ WITH base AS MATERIALIZED (AND i.recipient_type = 'member'AND i.recipient_id = $2::uuidAND i.archived = true+ -- MUL-8472: private projects the caller cannot see.+ AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY($3::uuid[])+ ))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item activeWHERE active.workspace_id = i.workspace_id@@ -39,11 +45,11 @@ WITH base AS MATERIALIZED ())), notification_match AS MATERIALIZED (SELECT base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type_group, base.actor,- (cardinality($3::text[]) = 0- OR (type_group = ANY($3::text[])) <> ('type' = ANY($4::text[]))) AS type_match,- (cardinality($5::text[]) = 0- OR COALESCE(actor = ANY($5::text[]), false) <> ('actor' = ANY($4::text[]))) AS actor_match,- ($6::timestamptz IS NULL OR created_at >= $6::timestamptz) AS received_match+ (cardinality($4::text[]) = 0+ OR (type_group = ANY($4::text[])) <> ('type' = ANY($5::text[]))) AS type_match,+ (cardinality($6::text[]) = 0+ OR COALESCE(actor = ANY($6::text[]), false) <> ('actor' = ANY($5::text[]))) AS actor_match,+ ($7::timestamptz IS NULL OR created_at >= $7::timestamptz) AS received_matchFROM base), groups AS (SELECT DISTINCT group_id, issue_id FROM base@@ -61,26 +67,26 @@ WITH base AS MATERIALIZED (AND iss.workspace_id = $1::uuid), issue_match AS MATERIALIZED (SELECT projected.group_id, projected.issue_ref, projected.issue_status, projected.issue_priority, projected.project_key, projected.assignee_key, projected.due_date, projected.label_ids,- (cardinality($7::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_status = ANY($7::text[])) <> ('status' = ANY($4::text[])))) AS status_match,(cardinality($8::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_priority = ANY($8::text[])) <> ('priority' = ANY($4::text[])))) AS priority_match,+ AND (issue_status = ANY($8::text[])) <> ('status' = ANY($5::text[])))) AS status_match,(cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL- AND (project_key = ANY($9::text[])) <> ('project' = ANY($4::text[])))) AS project_match,+ AND (issue_priority = ANY($9::text[])) <> ('priority' = ANY($5::text[])))) AS priority_match,(cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL- AND (assignee_key = ANY($10::text[])) <> ('assignee' = ANY($4::text[])))) AS assignee_match,+ AND (project_key = ANY($10::text[])) <> ('project' = ANY($5::text[])))) AS project_match,(cardinality($11::text[]) = 0 OR (issue_ref IS NOT NULL- AND (label_ids && $11::text[]) <> ('label' = ANY($4::text[])))) AS label_match,- (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(- ('overdue' = ANY($12::text[]) AND due_date < $13::date)- OR ('today' = ANY($12::text[]) AND due_date = $13::date)- OR ('this_week' = ANY($12::text[])- AND due_date >= $13::date - (EXTRACT(ISODOW FROM $13::date)::int - 1)- AND due_date < $13::date - (EXTRACT(ISODOW FROM $13::date)::int - 1) + 7)- OR ('next_7_days' = ANY($12::text[])- AND due_date >= $13::date AND due_date < $13::date + 7)- OR ('none' = ANY($12::text[]) AND due_date IS NULL), false)- <> ('dueDate' = ANY($4::text[])))) AS due_match+ AND (assignee_key = ANY($11::text[])) <> ('assignee' = ANY($5::text[])))) AS assignee_match,+ (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL+ AND (label_ids && $12::text[]) <> ('label' = ANY($5::text[])))) AS label_match,+ (cardinality($13::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(+ ('overdue' = ANY($13::text[]) AND due_date < $14::date)+ OR ('today' = ANY($13::text[]) AND due_date = $14::date)+ OR ('this_week' = ANY($13::text[])+ AND due_date >= $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1)+ AND due_date < $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1) + 7)+ OR ('next_7_days' = ANY($13::text[])+ AND due_date >= $14::date AND due_date < $14::date + 7)+ OR ('none' = ANY($13::text[]) AND due_date IS NULL), false)+ <> ('dueDate' = ANY($5::text[])))) AS due_matchFROM projected), reps AS (SELECT DISTINCT ON (group_id) group_id, read@@ -88,7 +94,7 @@ WITH base AS MATERIALIZED (WHERE type_match AND actor_match AND received_matchORDER BY group_id, created_at DESC, id DESC), matched AS (- SELECT issue_match.group_id, issue_match.issue_ref, issue_match.issue_status, issue_match.issue_priority, issue_match.project_key, issue_match.assignee_key, issue_match.due_date, issue_match.label_ids, issue_match.status_match, issue_match.priority_match, issue_match.project_match, issue_match.assignee_match, issue_match.label_match, issue_match.due_match, (NOT $14::boolean OR NOT reps.read) AS read_match, reps.read+ SELECT issue_match.group_id, issue_match.issue_ref, issue_match.issue_status, issue_match.issue_priority, issue_match.project_key, issue_match.assignee_key, issue_match.due_date, issue_match.label_ids, issue_match.status_match, issue_match.priority_match, issue_match.project_match, issue_match.assignee_match, issue_match.label_match, issue_match.due_match, (NOT $15::boolean OR NOT reps.read) AS read_match, reps.readFROM reps JOIN issue_match USING (group_id)), type_reps AS (SELECT DISTINCT ON (group_id, type_group) group_id, type_group, read@@ -123,12 +129,12 @@ FROM matched, unnest(label_ids) AS label GROUP BY labelUNION ALLSELECT 'types'::text, type_reps.type_group::text,count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match- AND (NOT $14::boolean OR NOT type_reps.read))::bigint+ AND (NOT $15::boolean OR NOT type_reps.read))::bigintFROM type_reps JOIN issue_match USING (group_id) GROUP BY type_reps.type_groupUNION ALLSELECT 'actors'::text, actor_reps.actor::text,count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match- AND (NOT $14::boolean OR NOT actor_reps.read))::bigint+ AND (NOT $15::boolean OR NOT actor_reps.read))::bigintFROM actor_reps JOIN issue_match USING (group_id) GROUP BY actor_reps.actorUNION ALLSELECT 'unread'::text, 'unread'::text,@@ -137,20 +143,21 @@ FROM matched`type ArchivedInboxFacetsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- Types []string `json:"types"`- Negated []string `json:"negated"`- Actors []string `json:"actors"`- ReceivedAfter pgtype.Timestamptz `json:"received_after"`- Statuses []string `json:"statuses"`- Priorities []string `json:"priorities"`- Projects []string `json:"projects"`- Assignees []string `json:"assignees"`- Labels []string `json:"labels"`- DueDates []string `json:"due_dates"`- Today pgtype.Date `json:"today"`- UnreadOnly bool `json:"unread_only"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ Types []string `json:"types"`+ Negated []string `json:"negated"`+ Actors []string `json:"actors"`+ ReceivedAfter pgtype.Timestamptz `json:"received_after"`+ Statuses []string `json:"statuses"`+ Priorities []string `json:"priorities"`+ Projects []string `json:"projects"`+ Assignees []string `json:"assignees"`+ Labels []string `json:"labels"`+ DueDates []string `json:"due_dates"`+ Today pgtype.Date `json:"today"`+ UnreadOnly bool `json:"unread_only"`}type ArchivedInboxFacetsRow struct {@@ -166,6 +173,7 @@ func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFacerows, err := q.db.Query(ctx, archivedInboxFacets,arg.WorkspaceID,arg.RecipientID,+ arg.HiddenProjectIds,arg.Types,arg.Negated,arg.Actors,@@ -217,8 +225,14 @@ WITH base AS MATERIALIZED (AND i.recipient_type = 'member'AND i.recipient_id = $2::uuidAND i.archived = true- AND ($3::uuid IS NULL OR i.issue_id = $3::uuid- OR (i.issue_id IS NULL AND i.id = $3::uuid))+ -- MUL-8472: private projects the caller cannot see.+ AND ($3::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY($3::uuid[])+ ))+ AND ($4::uuid IS NULL OR i.issue_id = $4::uuid+ OR (i.issue_id IS NULL AND i.id = $4::uuid))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item activeWHERE active.workspace_id = i.workspace_id@@ -229,11 +243,11 @@ WITH base AS MATERIALIZED (), newest AS (SELECT DISTINCT ON (group_id) base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type_group, base.actorFROM base- WHERE (cardinality($4::text[]) = 0- OR (type_group = ANY($4::text[])) <> ('type' = ANY($5::text[])))- AND (cardinality($6::text[]) = 0- OR COALESCE(actor = ANY($6::text[]), false) <> ('actor' = ANY($5::text[])))- AND ($7::timestamptz IS NULL OR created_at >= $7::timestamptz)+ WHERE (cardinality($5::text[]) = 0+ OR (type_group = ANY($5::text[])) <> ('type' = ANY($6::text[])))+ AND (cardinality($7::text[]) = 0+ OR COALESCE(actor = ANY($7::text[]), false) <> ('actor' = ANY($6::text[])))+ AND ($8::timestamptz IS NULL OR created_at >= $8::timestamptz)ORDER BY group_id, created_at DESC, id DESC), projected AS (SELECT newest.id, newest.created_at, newest.read,@@ -250,31 +264,31 @@ WITH base AS MATERIALIZED (), selected AS (SELECT projected.id, projected.created_at, projected.issue_status, projected.issue_priorityFROM projected- WHERE (cardinality($8::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_status = ANY($8::text[])) <> ('status' = ANY($5::text[]))))- AND (cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_priority = ANY($9::text[])) <> ('priority' = ANY($5::text[]))))+ WHERE (cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL+ AND (issue_status = ANY($9::text[])) <> ('status' = ANY($6::text[]))))AND (cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL- AND (project_key = ANY($10::text[])) <> ('project' = ANY($5::text[]))))+ AND (issue_priority = ANY($10::text[])) <> ('priority' = ANY($6::text[]))))AND (cardinality($11::text[]) = 0 OR (issue_ref IS NOT NULL- AND (assignee_key = ANY($11::text[])) <> ('assignee' = ANY($5::text[]))))+ AND (project_key = ANY($11::text[])) <> ('project' = ANY($6::text[]))))AND (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL- AND (label_ids && $12::text[]) <> ('label' = ANY($5::text[]))))- AND (cardinality($13::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(- ('overdue' = ANY($13::text[]) AND due_date < $14::date)- OR ('today' = ANY($13::text[]) AND due_date = $14::date)- OR ('this_week' = ANY($13::text[])- AND due_date >= $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1)- AND due_date < $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1) + 7)- OR ('next_7_days' = ANY($13::text[])- AND due_date >= $14::date AND due_date < $14::date + 7)- OR ('none' = ANY($13::text[]) AND due_date IS NULL), false)- <> ('dueDate' = ANY($5::text[]))))- AND (NOT $15::boolean OR NOT read)- AND ($16::timestamptz IS NULL OR- (created_at, id) < ($16::timestamptz, $17::uuid))+ AND (assignee_key = ANY($12::text[])) <> ('assignee' = ANY($6::text[]))))+ AND (cardinality($13::text[]) = 0 OR (issue_ref IS NOT NULL+ AND (label_ids && $13::text[]) <> ('label' = ANY($6::text[]))))+ AND (cardinality($14::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(+ ('overdue' = ANY($14::text[]) AND due_date < $15::date)+ OR ('today' = ANY($14::text[]) AND due_date = $15::date)+ OR ('this_week' = ANY($14::text[])+ AND due_date >= $15::date - (EXTRACT(ISODOW FROM $15::date)::int - 1)+ AND due_date < $15::date - (EXTRACT(ISODOW FROM $15::date)::int - 1) + 7)+ OR ('next_7_days' = ANY($14::text[])+ AND due_date >= $15::date AND due_date < $15::date + 7)+ OR ('none' = ANY($14::text[]) AND due_date IS NULL), false)+ <> ('dueDate' = ANY($6::text[]))))+ AND (NOT $16::boolean OR NOT read)+ AND ($17::timestamptz IS NULL OR+ (created_at, id) < ($17::timestamptz, $18::uuid))ORDER BY created_at DESC, id DESC- LIMIT $18::int+ LIMIT $19::int)SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, selected.issue_status, selected.issue_priority,iss.project_id AS issue_project_id,@@ -304,24 +318,25 @@ ORDER BY i.created_at DESC, i.id DESC`type ListArchivedInboxPageParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- GroupID pgtype.UUID `json:"group_id"`- Types []string `json:"types"`- Negated []string `json:"negated"`- Actors []string `json:"actors"`- ReceivedAfter pgtype.Timestamptz `json:"received_after"`- Statuses []string `json:"statuses"`- Priorities []string `json:"priorities"`- Projects []string `json:"projects"`- Assignees []string `json:"assignees"`- Labels []string `json:"labels"`- DueDates []string `json:"due_dates"`- Today pgtype.Date `json:"today"`- UnreadOnly bool `json:"unread_only"`- BeforeTime pgtype.Timestamptz `json:"before_time"`- BeforeID pgtype.UUID `json:"before_id"`- PageLimit int32 `json:"page_limit"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ GroupID pgtype.UUID `json:"group_id"`+ Types []string `json:"types"`+ Negated []string `json:"negated"`+ Actors []string `json:"actors"`+ ReceivedAfter pgtype.Timestamptz `json:"received_after"`+ Statuses []string `json:"statuses"`+ Priorities []string `json:"priorities"`+ Projects []string `json:"projects"`+ Assignees []string `json:"assignees"`+ Labels []string `json:"labels"`+ DueDates []string `json:"due_dates"`+ Today pgtype.Date `json:"today"`+ UnreadOnly bool `json:"unread_only"`+ BeforeTime pgtype.Timestamptz `json:"before_time"`+ BeforeID pgtype.UUID `json:"before_id"`+ PageLimit int32 `json:"page_limit"`}type ListArchivedInboxPageRow struct {@@ -346,6 +361,7 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInbrows, err := q.db.Query(ctx, listArchivedInboxPage,arg.WorkspaceID,arg.RecipientID,+ arg.HiddenProjectIds,arg.GroupID,arg.Types,arg.Negated,diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 63bc619a77..033de863e2 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -179,14 +179,16 @@ WHERE i.workspace_id = $1AND ($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::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))- AND ($9::jsonb IS NULL OR i.metadata @> $9::jsonb)+ -- MUL-8472: private projects the caller cannot see.+ AND ($8::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($8::uuid[])))+ AND ($9::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND ($10::jsonb IS NULL OR i.metadata @> $10::jsonb)AND (- $10::uuid IS NULL+ $11::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::uuid))OR (i.assignee_type = 'squad' AND i.assignee_id IN (SELECT sm.squad_id@@ -194,14 +196,14 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $10::uuid+ AND sm.member_id = $11::uuidUNIONSELECT s.idFROM squad sJOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::uuidUNIONSELECT sm.squad_idFROM squad_member sm@@ -210,22 +212,23 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::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"`- Scheduled pgtype.Bool `json:"scheduled"`- MetadataFilter []byte `json:"metadata_filter"`- InvolvesUserID pgtype.UUID `json:"involves_user_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"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ Scheduled pgtype.Bool `json:"scheduled"`+ MetadataFilter []byte `json:"metadata_filter"`+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`}// See ListIssues for the semantics of involves_user_id.@@ -238,6 +241,7 @@ func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64arg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.HiddenProjectIds,arg.Scheduled,arg.MetadataFilter,arg.InvolvesUserID,@@ -1394,15 +1398,17 @@ WHERE i.workspace_id = $1AND ($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::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))- AND ($11::jsonb IS NULL OR i.metadata @> $11::jsonb)+ -- MUL-8472: private projects the caller cannot see.+ AND ($10::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($10::uuid[])))+ AND ($11::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))+ AND ($12::jsonb IS NULL OR i.metadata @> $12::jsonb)AND (- $12::uuid IS NULL+ $13::uuid IS NULL-- (1) assignee is an agent owned by the userOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $12::uuid+ AND a.owner_id = $13::uuid))-- (2)(3)(4) assignee is a squad related to the user — three relationsOR (i.assignee_type = 'squad' AND i.assignee_id IN (@@ -1412,7 +1418,7 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $12::uuid+ AND sm.member_id = $13::uuidUNION-- (3) the squad's canonical leader is an agent owned by the user.-- We read squad.leader_id directly rather than relying on a@@ -1423,7 +1429,7 @@ WHERE i.workspace_id = $1JOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $12::uuid+ AND a.owner_id = $13::uuidUNION-- (4) the squad has an agent member owned by the userSELECT sm.squad_id@@ -1433,7 +1439,7 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $12::uuid+ AND a.owner_id = $13::uuid)))ORDER BY i.position ASC, i.created_at DESC@@ -1441,18 +1447,19 @@ LIMIT $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"`- Scheduled pgtype.Bool `json:"scheduled"`- MetadataFilter []byte `json:"metadata_filter"`- InvolvesUserID pgtype.UUID `json:"involves_user_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"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ Scheduled pgtype.Bool `json:"scheduled"`+ MetadataFilter []byte `json:"metadata_filter"`+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`}type ListIssuesRow struct {@@ -1499,6 +1506,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListIarg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.HiddenProjectIds,arg.Scheduled,arg.MetadataFilter,arg.InvolvesUserID,@@ -1560,7 +1568,9 @@ WHERE i.workspace_id = $1AND ($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::jsonb IS NULL OR i.metadata @> $8::jsonb)+ -- MUL-8472: private projects the caller cannot see.+ AND ($8::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY($8::uuid[])))+ AND ($9::jsonb IS NULL OR i.metadata @> $9::jsonb)-- properties_filter is a jsonb array of groups, each group an array of-- patterns (built by parsePropertiesFilterParam): the issue must match at-- least one pattern from EVERY group (AND of ORs). Three pattern shapes:@@ -1578,10 +1588,10 @@ WHERE i.workspace_id = $1-- terminal-status predicate intentionally remains a filter rather than a-- positive index narrowing so unknown legacy status keys stay visible.AND (- $9::jsonb IS NULL+ $10::jsonb IS NULLOR NOT EXISTS (SELECT 1- FROM jsonb_array_elements($9::jsonb) AS pf(alternatives)+ FROM jsonb_array_elements($10::jsonb) AS pf(alternatives)WHERE NOT EXISTS (SELECT 1FROM jsonb_array_elements(pf.alternatives) AS alt(pattern)@@ -1619,11 +1629,11 @@ WHERE i.workspace_id = $1))AND (- $10::uuid IS NULL+ $11::uuid IS NULLOR (i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent aWHERE a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::uuid))OR (i.assignee_type = 'squad' AND i.assignee_id IN (SELECT sm.squad_id@@ -1631,14 +1641,14 @@ WHERE i.workspace_id = $1JOIN squad s ON s.id = sm.squad_idWHERE s.workspace_id = $1AND sm.member_type = 'member'- AND sm.member_id = $10::uuid+ AND sm.member_id = $11::uuidUNIONSELECT s.idFROM squad sJOIN agent a ON a.id = s.leader_idWHERE s.workspace_id = $1AND a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::uuidUNIONSELECT sm.squad_idFROM squad_member sm@@ -1647,7 +1657,7 @@ WHERE i.workspace_id = $1WHERE s.workspace_id = $1AND sm.member_type = 'agent'AND a.workspace_id = $1- AND a.owner_id = $10::uuid+ AND a.owner_id = $11::uuid)))ORDER BY i.position ASC, i.created_at DESC@@ -1661,6 +1671,7 @@ type ListOpenIssuesParams struct {AssigneeIds []pgtype.UUID `json:"assignee_ids"`CreatorID pgtype.UUID `json:"creator_id"`ProjectID pgtype.UUID `json:"project_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`MetadataFilter []byte `json:"metadata_filter"`PropertiesFilter []byte `json:"properties_filter"`InvolvesUserID pgtype.UUID `json:"involves_user_id"`@@ -1704,6 +1715,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)arg.AssigneeIds,arg.CreatorID,arg.ProjectID,+ arg.HiddenProjectIds,arg.MetadataFilter,arg.PropertiesFilter,arg.InvolvesUserID,diff --git a/server/pkg/db/generated/issue_unread.sql.go b/server/pkg/db/generated/issue_unread.sql.goindex 5e7abf1c95..4e441fde9f 100644--- a/server/pkg/db/generated/issue_unread.sql.go+++ b/server/pkg/db/generated/issue_unread.sql.go@@ -25,20 +25,27 @@ LEFT JOIN LATERAL () run_comment ON trueWHERE u.workspace_id = $1AND u.user_id = $2+ -- MUL-8472: private projects the caller cannot see.+ AND ($3::uuid[] IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = u.issue_id+ AND hidden_issue.project_id = ANY($3::uuid[])+ ))AND (- $3::timestamptz IS NULL- OR (u.created_at, u.issue_id) < ($3::timestamptz, $4::uuid)+ $4::timestamptz IS NULL+ OR (u.created_at, u.issue_id) < ($4::timestamptz, $5::uuid))ORDER BY u.created_at DESC, u.issue_id DESC-LIMIT $5+LIMIT $6`type ListIssueUnreadParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- UserID pgtype.UUID `json:"user_id"`- BeforeCreatedAt pgtype.Timestamptz `json:"before_created_at"`- BeforeIssueID pgtype.UUID `json:"before_issue_id"`- PageLimit int32 `json:"page_limit"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ BeforeCreatedAt pgtype.Timestamptz `json:"before_created_at"`+ BeforeIssueID pgtype.UUID `json:"before_issue_id"`+ PageLimit int32 `json:"page_limit"`}type ListIssueUnreadRow struct {@@ -60,6 +67,7 @@ func (q *Queries) ListIssueUnread(ctx context.Context, arg ListIssueUnreadParamsrows, err := q.db.Query(ctx, listIssueUnread,arg.WorkspaceID,arg.UserID,+ arg.HiddenProjectIds,arg.BeforeCreatedAt,arg.BeforeIssueID,arg.PageLimit,diff --git a/server/pkg/db/generated/issue_workflow.sql.go b/server/pkg/db/generated/issue_workflow.sql.goindex 85f69bf37f..d603b8eadd 100644--- a/server/pkg/db/generated/issue_workflow.sql.go+++ b/server/pkg/db/generated/issue_workflow.sql.go@@ -338,7 +338,7 @@ func (q *Queries) ListNamedIssueWorkflowSteps(ctx context.Context, workspaceID p}const listProjectsUsingDefaultIssueWorkflow = `-- name: ListProjectsUsingDefaultIssueWorkflow :many-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE workspace_id = $1::uuidAND workflow_id IS NULLORDER BY created_at, id@@ -370,6 +370,7 @@ func (q *Queries) ListProjectsUsingDefaultIssueWorkflow(ctx context.Context, wor&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,); err != nil {return nil, err}@@ -382,7 +383,7 @@ func (q *Queries) ListProjectsUsingDefaultIssueWorkflow(ctx context.Context, wor}const listProjectsUsingIssueWorkflow = `-- name: ListProjectsUsingIssueWorkflow :many-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE workspace_id = $1::uuidAND workflow_id = $2::uuidORDER BY created_at, id@@ -419,6 +420,7 @@ func (q *Queries) ListProjectsUsingIssueWorkflow(ctx context.Context, arg ListPr&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,); err != nil {return nil, err}@@ -431,7 +433,7 @@ func (q *Queries) ListProjectsUsingIssueWorkflow(ctx context.Context, arg ListPr}const lockProjectForWorkflowChange = `-- name: LockProjectForWorkflowChange :one-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE id = $1::uuidAND workspace_id = $2::uuidFOR UPDATE@@ -463,6 +465,7 @@ func (q *Queries) LockProjectForWorkflowChange(ctx context.Context, arg LockProj&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,)return i, err}@@ -586,7 +589,7 @@ UPDATE project SETupdated_at = now()WHERE id = $2::uuidAND workspace_id = $3::uuid-RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id+RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility`type SetProjectWorkflowParams struct {@@ -615,6 +618,7 @@ func (q *Queries) SetProjectWorkflow(ctx context.Context, arg SetProjectWorkflow&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex e339625336..af17032070 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1466,6 +1466,15 @@ type Project struct {WorkflowID pgtype.UUID `json:"workflow_id"`CreatorType pgtype.Text `json:"creator_type"`CreatorID pgtype.UUID `json:"creator_id"`+ Visibility string `json:"visibility"`+}++type ProjectMember struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ UserID pgtype.UUID `json:"user_id"`+ AddedBy pgtype.UUID `json:"added_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`}type ProjectResource struct {diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.goindex 4b68220e49..99d132a143 100644--- a/server/pkg/db/generated/project.sql.go+++ b/server/pkg/db/generated/project.sql.go@@ -30,7 +30,7 @@ INSERT INTO project (creator_type, creator_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13-) RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id+) RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility`type CreateProjectParams struct {@@ -83,6 +83,7 @@ func (q *Queries) CreateProject(ctx context.Context, arg CreateProjectParams) (P&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,)return i, err}@@ -103,7 +104,7 @@ func (q *Queries) DeleteProject(ctx context.Context, arg DeleteProjectParams) er}const getProjectInWorkspace = `-- name: GetProjectInWorkspace :one-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE id = $1 AND workspace_id = $2`@@ -132,6 +133,7 @@ func (q *Queries) GetProjectInWorkspace(ctx context.Context, arg GetProjectInWor&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,)return i, err}@@ -179,7 +181,7 @@ func (q *Queries) GetProjectIssueStats(ctx context.Context, arg GetProjectIssueS}const listProjects = `-- name: ListProjects :many-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE workspace_id = $1AND ($2::text IS NULL OR status = $2)AND ($3::text IS NULL OR priority = $3)@@ -218,6 +220,7 @@ func (q *Queries) ListProjects(ctx context.Context, arg ListProjectsParams) ([]P&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,); err != nil {return nil, err}@@ -282,7 +285,7 @@ UPDATE project SETdue_date = CASE WHEN $15::boolean THEN $16 ELSE due_date END,updated_at = now()WHERE id = $1-RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id+RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility`type UpdateProjectParams struct {@@ -341,6 +344,7 @@ func (q *Queries) UpdateProject(ctx context.Context, arg UpdateProjectParams) (P&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,)return i, err}diff --git a/server/pkg/db/generated/project_member.sql.go b/server/pkg/db/generated/project_member.sql.gonew file mode 100644index 0000000000..0927bc5b54--- /dev/null+++ b/server/pkg/db/generated/project_member.sql.go@@ -0,0 +1,422 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: project_member.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const addProjectMembers = `-- name: AddProjectMembers :many+INSERT INTO project_member (workspace_id, project_id, user_id, added_by)+SELECT m.workspace_id, $1::uuid, m.user_id, $2::uuid+FROM member m+WHERE m.workspace_id = $3+ AND m.user_id = ANY($4::uuid[])+ON CONFLICT (project_id, user_id) DO NOTHING+RETURNING workspace_id, project_id, user_id, added_by, created_at+`++type AddProjectMembersParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ AddedBy pgtype.UUID `json:"added_by"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserIds []pgtype.UUID `json:"user_ids"`+}++// Only current workspace members are inserted; the caller compares the+// returned rows with its input to reject unknown users.+func (q *Queries) AddProjectMembers(ctx context.Context, arg AddProjectMembersParams) ([]ProjectMember, error) {+ rows, err := q.db.Query(ctx, addProjectMembers,+ arg.ProjectID,+ arg.AddedBy,+ arg.WorkspaceID,+ arg.UserIds,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ProjectMember{}+ for rows.Next() {+ var i ProjectMember+ if err := rows.Scan(+ &i.WorkspaceID,+ &i.ProjectID,+ &i.UserID,+ &i.AddedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const deleteProjectMember = `-- name: DeleteProjectMember :execrows+DELETE FROM project_member+WHERE project_id = $1+ AND workspace_id = $2+ AND user_id = $3+`++type DeleteProjectMemberParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) DeleteProjectMember(ctx context.Context, arg DeleteProjectMemberParams) (int64, error) {+ result, err := q.db.Exec(ctx, deleteProjectMember, arg.ProjectID, arg.WorkspaceID, arg.UserID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const deleteProjectMembersByProject = `-- name: DeleteProjectMembersByProject :exec+DELETE FROM project_member+WHERE project_id = $1 AND workspace_id = $2+`++type DeleteProjectMembersByProjectParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteProjectMembersByProject(ctx context.Context, arg DeleteProjectMembersByProjectParams) error {+ _, err := q.db.Exec(ctx, deleteProjectMembersByProject, arg.ProjectID, arg.WorkspaceID)+ return err+}++const deleteProjectMembersByUser = `-- name: DeleteProjectMembersByUser :exec+DELETE FROM project_member+WHERE workspace_id = $1 AND user_id = $2+`++type DeleteProjectMembersByUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// A member leaving the workspace leaves every private project in it.+func (q *Queries) DeleteProjectMembersByUser(ctx context.Context, arg DeleteProjectMembersByUserParams) error {+ _, err := q.db.Exec(ctx, deleteProjectMembersByUser, arg.WorkspaceID, arg.UserID)+ return err+}++const getCommentIssueProjectID = `-- name: GetCommentIssueProjectID :one+SELECT i.project_id FROM comment c+JOIN issue i ON i.id = c.issue_id+WHERE c.id = $1+`++func (q *Queries) GetCommentIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, getCommentIssueProjectID, id)+ var project_id pgtype.UUID+ err := row.Scan(&project_id)+ return project_id, err+}++const getIssueProjectID = `-- name: GetIssueProjectID :one+SELECT project_id FROM issue WHERE id = $1+`++// Realtime fanout resolves an event's issue to its project.+func (q *Queries) GetIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, getIssueProjectID, id)+ var project_id pgtype.UUID+ err := row.Scan(&project_id)+ return project_id, err+}++const listHiddenProjectIDsForUser = `-- name: ListHiddenProjectIDsForUser :many+SELECT p.id FROM project p+WHERE p.workspace_id = $1+ AND p.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = p.id AND pm.user_id = $2+ )+`++type ListHiddenProjectIDsForUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Private projects a regular (non owner/admin) workspace member cannot see.+// Owners and admins see every project; callers skip this query for them.+func (q *Queries) ListHiddenProjectIDsForUser(ctx context.Context, arg ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listHiddenProjectIDsForUser, arg.WorkspaceID, arg.UserID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listIssueProjectIDs = `-- name: ListIssueProjectIDs :many+SELECT id, project_id FROM issue WHERE id = ANY($1::uuid[])+`++type ListIssueProjectIDsRow struct {+ ID pgtype.UUID `json:"id"`+ ProjectID pgtype.UUID `json:"project_id"`+}++// Issue -> project for run-history redaction; issues outside a project are+// returned with a NULL project_id.+func (q *Queries) ListIssueProjectIDs(ctx context.Context, ids []pgtype.UUID) ([]ListIssueProjectIDsRow, error) {+ rows, err := q.db.Query(ctx, listIssueProjectIDs, ids)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueProjectIDsRow{}+ for rows.Next() {+ var i ListIssueProjectIDsRow+ if err := rows.Scan(&i.ID, &i.ProjectID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPrivateProjectAudience = `-- name: ListPrivateProjectAudience :many+SELECT p.id AS project_id, pm.user_id+FROM project p+LEFT JOIN project_member pm ON pm.project_id = p.id+WHERE p.workspace_id = $1 AND p.visibility = 'private'+`++type ListPrivateProjectAudienceRow struct {+ ProjectID pgtype.UUID `json:"project_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Realtime fanout for private-project events: each private project with its+// member user ids (NULL user_id when the project has no members yet).+func (q *Queries) ListPrivateProjectAudience(ctx context.Context, workspaceID pgtype.UUID) ([]ListPrivateProjectAudienceRow, error) {+ rows, err := q.db.Query(ctx, listPrivateProjectAudience, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListPrivateProjectAudienceRow{}+ for rows.Next() {+ var i ListPrivateProjectAudienceRow+ if err := rows.Scan(&i.ProjectID, &i.UserID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listPrivateProjectIDs = `-- name: ListPrivateProjectIDs :many+SELECT id FROM project+WHERE workspace_id = $1 AND visibility = 'private'+`++// Every private project in the workspace: the hidden set for a viewer no+// workspace member vouches for (an unattributed agent run, a removed member).+func (q *Queries) ListPrivateProjectIDs(ctx context.Context, workspaceID pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listPrivateProjectIDs, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listProjectMemberUserIDs = `-- name: ListProjectMemberUserIDs :many+SELECT user_id FROM project_member+WHERE project_id = $1 AND workspace_id = $2+`++type ListProjectMemberUserIDsParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) ListProjectMemberUserIDs(ctx context.Context, arg ListProjectMemberUserIDsParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listProjectMemberUserIDs, arg.ProjectID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var user_id pgtype.UUID+ if err := rows.Scan(&user_id); err != nil {+ return nil, err+ }+ items = append(items, user_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listProjectMembers = `-- name: ListProjectMembers :many+SELECT pm.workspace_id, pm.project_id, pm.user_id, pm.added_by, pm.created_at,+ u.name AS user_name, u.email AS user_email, u.avatar_url AS user_avatar_url+FROM project_member pm+JOIN "user" u ON u.id = pm.user_id+WHERE pm.project_id = $1 AND pm.workspace_id = $2+ORDER BY pm.created_at ASC, pm.user_id ASC+`++type ListProjectMembersParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListProjectMembersRow struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ UserID pgtype.UUID `json:"user_id"`+ AddedBy pgtype.UUID `json:"added_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UserName string `json:"user_name"`+ UserEmail string `json:"user_email"`+ UserAvatarUrl pgtype.Text `json:"user_avatar_url"`+}++func (q *Queries) ListProjectMembers(ctx context.Context, arg ListProjectMembersParams) ([]ListProjectMembersRow, error) {+ rows, err := q.db.Query(ctx, listProjectMembers, arg.ProjectID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListProjectMembersRow{}+ for rows.Next() {+ var i ListProjectMembersRow+ if err := rows.Scan(+ &i.WorkspaceID,+ &i.ProjectID,+ &i.UserID,+ &i.AddedBy,+ &i.CreatedAt,+ &i.UserName,+ &i.UserEmail,+ &i.UserAvatarUrl,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const touchProjectSearchIndexEntries = `-- name: TouchProjectSearchIndexEntries :exec+INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)+SELECT 'project', p.id, p.workspace_id, pg_current_xact_id(), now()+FROM project p+WHERE p.id = $1 AND p.workspace_id = $2+UNION ALL+SELECT 'issue', i.id, i.workspace_id, pg_current_xact_id(), now()+FROM issue i+WHERE i.project_id = $1 AND i.workspace_id = $2+UNION ALL+SELECT 'comment', c.id, c.workspace_id, pg_current_xact_id(), now()+FROM comment c+JOIN issue i ON i.id = c.issue_id+WHERE i.project_id = $1 AND i.workspace_id = $2+ON CONFLICT (entity_type, entity_id) DO UPDATE+ SET workspace_id = EXCLUDED.workspace_id,+ change_xid = EXCLUDED.change_xid,+ changed_at = EXCLUDED.changed_at+`++type TouchProjectSearchIndexEntriesParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Re-announce a project, its issues and their comments to local search sync+// after its access changed, so clients that lost access receive them as+// deletions and clients that gained it receive them as upserts.+func (q *Queries) TouchProjectSearchIndexEntries(ctx context.Context, arg TouchProjectSearchIndexEntriesParams) error {+ _, err := q.db.Exec(ctx, touchProjectSearchIndexEntries, arg.ProjectID, arg.WorkspaceID)+ return err+}++const updateProjectVisibility = `-- name: UpdateProjectVisibility :one+UPDATE project SET visibility = $1, updated_at = now()+WHERE id = $2 AND workspace_id = $3+RETURNING id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility+`++type UpdateProjectVisibilityParams struct {+ Visibility string `json:"visibility"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) UpdateProjectVisibility(ctx context.Context, arg UpdateProjectVisibilityParams) (Project, error) {+ row := q.db.QueryRow(ctx, updateProjectVisibility, arg.Visibility, arg.ID, arg.WorkspaceID)+ var i Project+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Title,+ &i.Description,+ &i.Icon,+ &i.Status,+ &i.LeadType,+ &i.LeadID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Priority,+ &i.StartDate,+ &i.DueDate,+ &i.WorkflowID,+ &i.CreatorType,+ &i.CreatorID,+ &i.Visibility,+ )+ return i, err+}diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.goindex 00b49ae809..5cdc5f402a 100644--- a/server/pkg/db/generated/search_index.sql.go+++ b/server/pkg/db/generated/search_index.sql.go@@ -360,7 +360,7 @@ func (q *Queries) ListSearchIndexIssuesPage(ctx context.Context, arg ListSearchI}const listSearchIndexProjects = `-- name: ListSearchIndexProjects :many-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE workspace_id = $1ORDER BY id`@@ -391,6 +391,7 @@ func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtyp&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,); err != nil {return nil, err}@@ -403,7 +404,7 @@ func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtyp}const listSearchIndexProjectsByIDs = `-- name: ListSearchIndexProjectsByIDs :many-SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id FROM project+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility FROM projectWHERE workspace_id = $1 AND id = ANY($2::uuid[])`@@ -438,6 +439,7 @@ func (q *Queries) ListSearchIndexProjectsByIDs(ctx context.Context, arg ListSear&i.WorkflowID,&i.CreatorType,&i.CreatorID,+ &i.Visibility,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex a010543da2..077fa877ff 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -632,6 +632,9 @@ deleted_runtimes AS (),deleted_profiles AS (DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1+),+deleted_project_members AS (+ DELETE FROM project_member WHERE project_member.workspace_id = $1)DELETE FROM project WHERE project.workspace_id = $1`diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 860417e320..f3d2d7d97c 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -15,6 +15,7 @@ SELECT i.*,FROM inbox_item iLEFT JOIN issue iss ON iss.id = i.issue_idWHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = false+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))ORDER BY i.created_at DESC;-- name: ListArchivedInboxItems :many@@ -49,6 +50,12 @@ WITH eligible_archived AS MATERIALIZED (AND i.recipient_type = $2AND i.recipient_id = $3AND i.archived = true+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])+ ))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1FROM inbox_item active@@ -115,10 +122,27 @@ INSERT INTO inbox_item (actor_type, actor_id, details, id)SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())-WHERE ($2::text = 'member' AND EXISTS (+WHERE (($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (SELECT 1 FROM agent WHERE workspace_id = $1 AND id = $3+)))+-- MUL-8472: a member outside a private project gets no notification about its+-- issues. Owners/admins and project members do.+AND NOT ($2::text = 'member' AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = $6+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = $3+ )+ AND NOT EXISTS (+ SELECT 1 FROM member manager+ WHERE manager.workspace_id = $1 AND manager.user_id = $3+ AND manager.role IN ('owner', 'admin')+ )))RETURNING *;@@ -191,8 +215,18 @@ WHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = falseRETURNING recipient_type, recipient_id;-- name: CountUnreadInbox :one-SELECT count(*) FROM inbox_item-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false;+SELECT count(*) FROM inbox_item i+WHERE i.workspace_id = sqlc.arg('workspace_id')+ AND i.recipient_type = sqlc.arg('recipient_type')+ AND i.recipient_id = sqlc.arg('recipient_id')+ AND i.read = false+ AND i.archived = false+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])+ ));-- name: CountUnreadInboxByWorkspace :many-- Per-workspace unread inbox counts for a recipient member, matching the@@ -215,6 +249,18 @@ FROM (WHERE i.recipient_type = 'member'AND i.recipient_id = $1AND i.archived = false+ -- MUL-8472: issues in private projects the recipient is outside of+ -- (neither a project member nor a workspace owner/admin) do not count.+ AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = i.issue_id+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id+ )+ ))ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC) newestWHERE newest.read = falsediff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlindex 7f6f7b1b5d..269fce10d7 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -24,6 +24,12 @@ WITH base AS MATERIALIZED (AND i.recipient_type = 'member'AND i.recipient_id = sqlc.arg(recipient_id)::uuidAND i.archived = true+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])+ ))AND (sqlc.narg(group_id)::uuid IS NULL OR i.issue_id = sqlc.narg(group_id)::uuidOR (i.issue_id IS NULL AND i.id = sqlc.narg(group_id)::uuid))AND (i.issue_id IS NULL OR NOT EXISTS (@@ -131,6 +137,12 @@ WITH base AS MATERIALIZED (AND i.recipient_type = 'member'AND i.recipient_id = sqlc.arg(recipient_id)::uuidAND i.archived = true+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = i.issue_id+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])+ ))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item activeWHERE active.workspace_id = i.workspace_iddiff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex ac608905c6..5079417272 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -17,6 +17,8 @@ WHERE i.workspace_id = $1AND (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'))+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)AND (@@ -523,6 +525,8 @@ WHERE i.workspace_id = $1AND (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'))+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)-- properties_filter is a jsonb array of groups, each group an array of-- patterns (built by parsePropertiesFilterParam): the issue must match at@@ -625,6 +629,8 @@ WHERE i.workspace_id = $1AND (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'))+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))AND (sqlc.narg('scheduled')::bool IS NULL OR (i.start_date IS NOT NULL OR i.due_date IS NOT NULL))AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)AND (diff --git a/server/pkg/db/queries/issue_unread.sql b/server/pkg/db/queries/issue_unread.sqlindex 2e0da2b504..e66c0ad34b 100644--- a/server/pkg/db/queries/issue_unread.sql+++ b/server/pkg/db/queries/issue_unread.sql@@ -40,6 +40,12 @@ LEFT JOIN LATERAL () run_comment ON trueWHERE u.workspace_id = sqlc.arg(workspace_id)AND u.user_id = sqlc.arg(user_id)+ -- MUL-8472: private projects the caller cannot see.+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR NOT EXISTS (+ SELECT 1 FROM issue hidden_issue+ WHERE hidden_issue.id = u.issue_id+ AND hidden_issue.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])+ ))AND (sqlc.narg(before_created_at)::timestamptz IS NULLOR (u.created_at, u.issue_id) < (sqlc.narg(before_created_at)::timestamptz, sqlc.narg(before_issue_id)::uuid)diff --git a/server/pkg/db/queries/project_member.sql b/server/pkg/db/queries/project_member.sqlnew file mode 100644index 0000000000..5064dc9082--- /dev/null+++ b/server/pkg/db/queries/project_member.sql@@ -0,0 +1,103 @@+-- name: ListPrivateProjectIDs :many+-- Every private project in the workspace: the hidden set for a viewer no+-- workspace member vouches for (an unattributed agent run, a removed member).+SELECT id FROM project+WHERE workspace_id = $1 AND visibility = 'private';++-- name: ListHiddenProjectIDsForUser :many+-- Private projects a regular (non owner/admin) workspace member cannot see.+-- Owners and admins see every project; callers skip this query for them.+SELECT p.id FROM project p+WHERE p.workspace_id = sqlc.arg('workspace_id')+ AND p.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = p.id AND pm.user_id = sqlc.arg('user_id')+ );++-- name: ListPrivateProjectAudience :many+-- Realtime fanout for private-project events: each private project with its+-- member user ids (NULL user_id when the project has no members yet).+SELECT p.id AS project_id, pm.user_id+FROM project p+LEFT JOIN project_member pm ON pm.project_id = p.id+WHERE p.workspace_id = $1 AND p.visibility = 'private';++-- name: ListProjectMembers :many+SELECT pm.workspace_id, pm.project_id, pm.user_id, pm.added_by, pm.created_at,+ u.name AS user_name, u.email AS user_email, u.avatar_url AS user_avatar_url+FROM project_member pm+JOIN "user" u ON u.id = pm.user_id+WHERE pm.project_id = sqlc.arg('project_id') AND pm.workspace_id = sqlc.arg('workspace_id')+ORDER BY pm.created_at ASC, pm.user_id ASC;++-- name: ListProjectMemberUserIDs :many+SELECT user_id FROM project_member+WHERE project_id = sqlc.arg('project_id') AND workspace_id = sqlc.arg('workspace_id');++-- name: AddProjectMembers :many+-- Only current workspace members are inserted; the caller compares the+-- returned rows with its input to reject unknown users.+INSERT INTO project_member (workspace_id, project_id, user_id, added_by)+SELECT m.workspace_id, sqlc.arg('project_id')::uuid, m.user_id, sqlc.narg('added_by')::uuid+FROM member m+WHERE m.workspace_id = sqlc.arg('workspace_id')+ AND m.user_id = ANY(sqlc.arg('user_ids')::uuid[])+ON CONFLICT (project_id, user_id) DO NOTHING+RETURNING *;++-- name: DeleteProjectMember :execrows+DELETE FROM project_member+WHERE project_id = sqlc.arg('project_id')+ AND workspace_id = sqlc.arg('workspace_id')+ AND user_id = sqlc.arg('user_id');++-- name: DeleteProjectMembersByProject :exec+DELETE FROM project_member+WHERE project_id = sqlc.arg('project_id') AND workspace_id = sqlc.arg('workspace_id');++-- name: DeleteProjectMembersByUser :exec+-- A member leaving the workspace leaves every private project in it.+DELETE FROM project_member+WHERE workspace_id = sqlc.arg('workspace_id') AND user_id = sqlc.arg('user_id');++-- name: UpdateProjectVisibility :one+UPDATE project SET visibility = sqlc.arg('visibility'), updated_at = now()+WHERE id = sqlc.arg('id') AND workspace_id = sqlc.arg('workspace_id')+RETURNING *;++-- name: GetIssueProjectID :one+-- Realtime fanout resolves an event's issue to its project.+SELECT project_id FROM issue WHERE id = $1;++-- name: GetCommentIssueProjectID :one+SELECT i.project_id FROM comment c+JOIN issue i ON i.id = c.issue_id+WHERE c.id = $1;++-- name: TouchProjectSearchIndexEntries :exec+-- Re-announce a project, its issues and their comments to local search sync+-- after its access changed, so clients that lost access receive them as+-- deletions and clients that gained it receive them as upserts.+INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)+SELECT 'project', p.id, p.workspace_id, pg_current_xact_id(), now()+FROM project p+WHERE p.id = sqlc.arg('project_id') AND p.workspace_id = sqlc.arg('workspace_id')+UNION ALL+SELECT 'issue', i.id, i.workspace_id, pg_current_xact_id(), now()+FROM issue i+WHERE i.project_id = sqlc.arg('project_id') AND i.workspace_id = sqlc.arg('workspace_id')+UNION ALL+SELECT 'comment', c.id, c.workspace_id, pg_current_xact_id(), now()+FROM comment c+JOIN issue i ON i.id = c.issue_id+WHERE i.project_id = sqlc.arg('project_id') AND i.workspace_id = sqlc.arg('workspace_id')+ON CONFLICT (entity_type, entity_id) DO UPDATE+ SET workspace_id = EXCLUDED.workspace_id,+ change_xid = EXCLUDED.change_xid,+ changed_at = EXCLUDED.changed_at;++-- name: ListIssueProjectIDs :many+-- Issue -> project for run-history redaction; issues outside a project are+-- returned with a NULL project_id.+SELECT id, project_id FROM issue WHERE id = ANY(sqlc.arg('ids')::uuid[]);diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex a53a4b14ad..3ecd9afea4 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -717,6 +717,9 @@ deleted_runtimes AS (),deleted_profiles AS (DELETE FROM runtime_profile WHERE runtime_profile.workspace_id = $1+),+deleted_project_members AS (+ DELETE FROM project_member WHERE project_member.workspace_id = $1)DELETE FROM project WHERE project.workspace_id = $1;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 9ed914c0fa..1a1d9d62d4 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -102,6 +102,10 @@ const (EventProjectResourceUpdated = "project_resource:updated"EventProjectResourceDeleted = "project_resource:deleted"+ // EventProjectMembersChanged carries {project_id}: a private project's+ // member list changed (MUL-8472).+ EventProjectMembersChanged = "project:members_changed"+// Label eventsEventLabelCreated = "label:created"EventLabelUpdated = "label:updated"