Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6343: Enforce recently created issue windows (#7305)
Multica Eve1dc135598e4a
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 1561fd6cc1..44c6fdc453 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -238,6 +238,7 @@ import {SendChatMessageResponseSchema,StartMikaOnboardingResponseSchema,ChildIssuesResponseSchema,+ ChildIssueProgressResponseSchema,CommentsListSchema,CommentTriggerPreviewSchema,IssueTriggerPreviewSchema,@@ -1093,8 +1094,20 @@ export class ApiClient {});}- async getChildIssueProgress(): Promise<{ progress: { parent_issue_id: string; total: number; done: number }[] }> {- return this.fetch("/api/issues/child-progress");+ async getChildIssueProgress(): Promise<{+ progress: {+ parent_issue_id: string;+ total: number;+ done: number;+ visible_total?: number;+ visible_done?: number;+ hidden_total?: number;+ }[];+ }> {+ const raw = await this.fetch<unknown>("/api/issues/child-progress");+ return parseWithFallback(raw, ChildIssueProgressResponseSchema, { progress: [] }, {+ endpoint: "GET /api/issues/child-progress",+ });}async deleteIssue(id: string): Promise<void> {diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex ff54080382..cf588d76de 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {AppConfigSchema,+ ChildIssueProgressResponseSchema,WecomInstallationSchema,ListWecomInstallationsResponseSchema,RedeemWecomBindingTokenResponseSchema,@@ -94,6 +95,40 @@ const baseIssue = {updated_at: "2026-01-01T00:00:00Z",};+describe("ChildIssueProgressResponseSchema", () => {+ it("keeps older server responses compatible when visibility fields are absent", () => {+ const parsed = ChildIssueProgressResponseSchema.parse({+ progress: [{ parent_issue_id: "parent-1", total: 3, done: 1 }],+ });+ expect(parsed.progress[0]).toEqual({ parent_issue_id: "parent-1", total: 3, done: 1 });+ });++ it("parses full and visible progress independently", () => {+ const parsed = ChildIssueProgressResponseSchema.parse({+ progress: [{+ parent_issue_id: "parent-1",+ total: 10,+ done: 3,+ visible_total: 4,+ visible_done: 3,+ hidden_total: 6,+ }],+ });+ expect(parsed.progress[0]?.hidden_total).toBe(6);+ expect(parsed.progress[0]?.visible_total).toBe(4);+ });++ it("falls back instead of exposing malformed progress to installed clients", () => {+ const fallback = { progress: [] };+ expect(parseWithFallback(+ { progress: [{ parent_issue_id: "parent-1", total: "many", done: 1 }] },+ ChildIssueProgressResponseSchema,+ fallback,+ { endpoint: "GET /api/issues/child-progress" },+ )).toEqual(fallback);+ });+});+describe("IssueSchema (via ListIssuesResponseSchema)", () => {it("accepts null activity during backfill and rejects malformed activity", () => {const parsed = ListIssuesResponseSchema.parse({diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5791183d7c..f987939c8a 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1259,6 +1259,17 @@ export const ChildIssuesResponseSchema = z.object({issues: z.array(IssueSchema).default([]),}).loose();+export const ChildIssueProgressResponseSchema = z.object({+ progress: z.array(z.object({+ parent_issue_id: z.string(),+ total: z.number(),+ done: z.number(),+ visible_total: z.number().optional(),+ visible_done: z.number().optional(),+ hidden_total: z.number().optional(),+ }).loose()).default([]),+}).loose();+export const CloudRuntimeNodeSchema = z.object({id: z.string(),owner_id: z.string(),diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex f64a2dd339..72ac67a3b7 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -461,9 +461,21 @@ export function childIssueProgressOptions(wsId: string) {queryKey: issueKeys.childProgress(wsId),queryFn: () => api.getChildIssueProgress(),select: (data) => {- const map = new Map<string, { done: number; total: number }>();+ const map = new Map<string, {+ done: number;+ total: number;+ visibleDone: number;+ visibleTotal: number;+ hiddenTotal: number;+ }>();for (const entry of data.progress) {- map.set(entry.parent_issue_id, { done: entry.done, total: entry.total });+ map.set(entry.parent_issue_id, {+ done: entry.done,+ total: entry.total,+ visibleDone: entry.visible_done ?? entry.done,+ visibleTotal: entry.visible_total ?? entry.total,+ hiddenTotal: entry.hidden_total ?? 0,+ });}return map;},diff --git a/packages/views/issues/components/board-card-assignee-picker.test.tsx b/packages/views/issues/components/board-card-assignee-picker.test.tsxindex 50e7f6f60d..d4f12a6e44 100644--- a/packages/views/issues/components/board-card-assignee-picker.test.tsx+++ b/packages/views/issues/components/board-card-assignee-picker.test.tsx@@ -48,7 +48,7 @@ const viewState = vi.hoisted(() => ({startDate: true,dueDate: true,project: false,- childProgress: false,+ childProgress: true,labels: false,},cardPropertyIds: [],@@ -67,7 +67,10 @@ vi.mock("@multica/core/workspace/hooks", () => ({}));vi.mock("../../i18n", () => ({- useT: () => ({ t: () => "Translated" }),+ useT: () => ({+ t: (_selector: unknown, options?: { count?: number }) =>+ options?.count === undefined ? "Translated" : `${options.count} restricted`,+ }),useTimeAgo: () => () => "now",}));@@ -160,4 +163,28 @@ describe("BoardCardContent assignee picker", () => {expect(navigation.push).not.toHaveBeenCalled();},);++ it("shows the full progress and the number of restricted children", () => {+ const issue = makeIssue("member");+ render(+ <NavigationProvider value={navigation}>+ <IssueSurfaceActionsProvider actions={actions}>+ <AppLink href={`/acme/issues/${issue.id}`}>+ <BoardCardContent+ issue={issue}+ childProgress={{+ done: 3,+ total: 10,+ visibleDone: 3,+ visibleTotal: 4,+ hiddenTotal: 6,+ }}+ />+ </AppLink>+ </IssueSurfaceActionsProvider>+ </NavigationProvider>,+ );+ expect(screen.getByText("3/10")).toBeInTheDocument();+ expect(screen.getByText("6 restricted")).toBeInTheDocument();+ });});diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsxindex 017b6a23c8..d7bf3b5025 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -292,11 +292,16 @@ export const BoardCardContent = memo(function BoardCardContent({))}{showChildProgress && (- <div className="inline-flex shrink-0 items-center gap-1">+ <div className="inline-flex shrink-0 items-center gap-1.5"><ProgressRing done={childProgress!.done} total={childProgress!.total} size={14} /><span className="text-micro text-muted-foreground tabular-nums font-medium">{childProgress!.done}/{childProgress!.total}</span>+ {(childProgress!.hiddenTotal ?? 0) > 0 && (+ <span className="text-micro text-warning tabular-nums font-medium">+ {t(($) => $.card.child_progress_restricted, { count: childProgress!.hiddenTotal ?? 0 })}+ </span>+ )}</div>)}{showUpdatedHint && (diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsxindex 00525307b5..ab87238b0b 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -25,10 +25,14 @@ import { LabelChip } from "../../labels/label-chip";import { CustomStatusChip } from "./custom-status-chip";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";import { useIssueSurfaceSelection } from "../surface/selection-context";+import { useT } from "../../i18n";export interface ChildProgress {done: number;total: number;+ visibleDone?: number;+ visibleTotal?: number;+ hiddenTotal?: number;}function formatDate(date: string): string {@@ -54,6 +58,7 @@ function ListRowContent({containerProps?: Record<string, unknown>;checkboxProps?: Pick<React.HTMLAttributes<HTMLDivElement>, "onClick" | "onMouseDown" | "onPointerDown">;}) {+ const { t } = useT("issues");const selection = useIssueSurfaceSelection();const selected = selection.selectedIds.has(issue.id);const toggle = selection.toggle;@@ -124,6 +129,11 @@ function ListRowContent({<span className="text-micro text-muted-foreground tabular-nums font-medium">{childProgress!.done}/{childProgress!.total}</span>+ {(childProgress!.hiddenTotal ?? 0) > 0 && (+ <span className="text-micro text-warning tabular-nums font-medium">+ {t(($) => $.card.child_progress_restricted, { count: childProgress!.hiddenTotal ?? 0 })}+ </span>+ )}</span>)}{showLabels && (diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex b49bd25b0e..28ece67bd2 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -626,7 +626,9 @@},"card": {"update_failed": "Failed to update issue",- "updated_ago": "Updated {{time}}"+ "updated_ago": "Updated {{time}}",+ "child_progress_restricted_one": "{{count}} restricted",+ "child_progress_restricted_other": "{{count}} restricted"},"actions": {"status": "Status",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 995c5db26b..6bb51cf450 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -596,7 +596,8 @@},"card": {"update_failed": "タスクを更新できませんでした",- "updated_ago": "{{time}} に更新"+ "updated_ago": "{{time}} に更新",+ "child_progress_restricted_other": "サブタスク {{count}} 件が制限中"},"actions": {"status": "ステータス",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex f0200e63bd..771c5ec918 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -596,7 +596,8 @@},"card": {"update_failed": "태스크를 업데이트하지 못했습니다",- "updated_ago": "{{time}} 수정됨"+ "updated_ago": "{{time}} 수정됨",+ "child_progress_restricted_other": "하위 태스크 {{count}}개 제한됨"},"actions": {"status": "상태",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex b73a5fd92d..deb23e67ad 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -596,7 +596,8 @@},"card": {"update_failed": "更新任务失败",- "updated_ago": "更新于 {{time}}"+ "updated_ago": "更新于 {{time}}",+ "child_progress_restricted_other": "{{count}} 个子任务受限"},"actions": {"status": "状态",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ba3a6f989c..14dc227bc8 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -380,6 +380,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busopts.BusinessMetrics.RecordEntitlementConfigError()} else if entitlementClient.Enabled() {entitlementClient.SetEmergencyDisabled(envBool("MULTICA_ENTITLEMENT_EMERGENCY_DISABLED", false))+ h.Entitlements = entitlementClienth.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}@@ -1718,6 +1719,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Issuesr.Route("/api/issues", func(r chi.Router) {+ r.Get("/window-usage", h.GetIssueWindowUsage)r.Post("/table/groups", h.ListIssueTableGroups)r.Post("/table/rows", h.ListIssueTableRows)r.Post("/table/facets", h.ListIssueTableFacets)diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 0903603ba6..ebd9e7966e 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -10,7 +10,8 @@ Production wiring remains explicit and off by default. Set`MULTICA_ENTITLEMENT_POLICY_URL`, and the independent`MULTICA_ENTITLEMENT_SERVICE_TOKEN` to enable the client. A disabled clientperforms no HTTP request, and the autopilot consumer does not access its quota-tables; self-hosted deployments therefore retain the legacy dispatch path.+tables; the issue-window consumer likewise keeps its legacy SQL and performs no+window read. Self-hosted deployments therefore retain the legacy paths.Timeout, stale grace, and the emergency down switch are controlled by`MULTICA_ENTITLEMENT_POLICY_TIMEOUT`, `MULTICA_ENTITLEMENT_STALE_GRACE`, and`MULTICA_ENTITLEMENT_EMERGENCY_DISABLED`.@@ -56,3 +57,33 @@ policy-neutral accounting and recovery lifecycle separately.Future consumers should depend on the small `Provider` interface. Tests can use`server/internal/entitlement/entitlementtest.Stub` without Cloud.++## Recently-created issue window++The `issue_window` gate limits reads, not creation. Its base set is the+workspace's newest `limit` rows by immutable `issue.number DESC`; deleted+numbers may leave gaps, so implementations always use an indexed `LIMIT` and+never derive a threshold from `workspace.issue_counter`. Every ancestor of a+base issue is added so clients do not receive orphaned child references.+Supplemental ancestors do not consume the base limit and do not make their+other children visible.++`last_activity_at` remains an independent issue activity/sort field. Comments,+edits, archive-like status changes, and restores do not change membership in+the creation window. No activity backfill is required for this gate.++`off` preserves the original queries. `observe` preserves responses and records+whether the response would contain a hidden issue. `enforce` filters list,+search, table, children, Inbox, plugin, and agent-context reads through the same+recursive set. A same-workspace direct read outside the set returns HTTP 402+with `issue_outside_creation_window`; cross-workspace identifiers are resolved+inside the requested workspace first and remain indistinguishable 404s. The+bounded `/api/issues/window-usage` probe scans at most `limit + 1` entries from+the existing unique `(workspace_id, number)` index.++The two failure stages intentionally differ. An unavailable, stale, or+malformed Cloud decision degrades through `observe` to `off`, so it never+creates a new read-path dependency. After a valid `enforce` decision exists,+however, a database failure while evaluating the visible set fails closed: the+server cannot prove that the requested issue is allowed. `observe` evaluation+errors remain fail-open and are recorded as telemetry only.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 0ac1a634dd..340cf8aa3a 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -22,6 +22,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/daemonws"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/integrations/slack""github.com/multica-ai/multica/server/internal/issuestatus"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"@@ -1890,6 +1891,36 @@ func claimResponseAgentIdentityMatches(resp AgentTaskResponse) bool {func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {// Build response with fresh agent data (name + skills + custom_env + custom_args).resp = taskToResponse(*task, runtimeWorkspaceID)+ if task.IssueID.Valid {+ if policy, enabled := h.issueWindowPolicy(r.Context(), runtime.WorkspaceID); enabled {+ visible, visibilityErr := h.issueIDsWithinWindow(r.Context(), runtime.WorkspaceID, policy, []pgtype.UUID{task.IssueID})+ if visibilityErr != nil {+ h.recordIssueWindow(policy.action, "agent_context", "error")+ if policy.action == entitlement.ActionEnforce {+ if _, requeueErr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); requeueErr != nil {+ slog.Error("task claim: requeue after issue window failure failed", "task_id", uuidToString(task.ID), "error", requeueErr)+ }+ return resp, nil, 0, 0, &claimBuildFailure{+ outcome: "error_issue_window_check", status: http.StatusInternalServerError, message: "failed to check issue access",+ }+ }+ } else if !visible {+ if policy.action == entitlement.ActionObserve {+ h.recordIssueWindow(policy.action, "agent_context", "would_block")+ } else {+ h.recordIssueWindow(policy.action, "agent_context", "blocked")+ return resp, nil, 0, 0, h.failClaimedTaskBeforeLaunch(+ r.Context(), task,+ "This issue is outside the workspace's recently created issue window.",+ taskfailure.ReasonIssueWindowRestricted,+ "error_issue_window_restricted", http.StatusPaymentRequired, "issue is outside the recently created window",+ )+ }+ } else {+ h.recordIssueWindow(policy.action, "agent_context", "allowed")+ }+ }+ }// Claim-only capability: this server resolves the squad-leader role on the// wire (is_leader_task / squad_id), so the daemon must not re-derive it// from the briefing text. Set unconditionally — on every claim, leader ordiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex c896af7bc1..fb678d6eb6 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -22,6 +22,7 @@ import ("github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/daemonws"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/integrations/channel/engine"composio "github.com/multica-ai/multica/server/internal/integrations/composio"@@ -163,9 +164,13 @@ type DaemonPendingWorkNotifier interface {}type Handler struct {- Queries *db.Queries- DB dbExecutor- TxStarter txStarter+ Queries *db.Queries+ DB dbExecutor+ TxStarter txStarter+ // issueTableWindowCache is initialized only on the request-local Handler+ // copy used by a repeatable-read table request. It lets facets reuse one+ // visible-id snapshot without adding mutable state to the shared Handler.+ issueTableWindowCache *issueTableWindowCacheHub *realtime.HubDaemonHub *daemonws.HubDaemonProfileRefresh RuntimeProfileRefreshNotifier@@ -175,12 +180,15 @@ type Handler struct {PluginService *service.PluginServiceIssueService *service.IssueServiceAutopilotService *service.AutopilotService- EmailService *service.EmailService- UpdateStore UpdateStore- ModelListStore ModelListStore- LocalSkillListStore LocalSkillListStore- LocalSkillImportStore LocalSkillImportStore- FeatureFlags *featureflag.Service+ // Entitlements supplies workspace-scoped commercial gates. A nil provider+ // preserves the self-hosted and pre-rollout behavior without extra reads.+ Entitlements entitlement.Provider+ EmailService *service.EmailService+ UpdateStore UpdateStore+ ModelListStore ModelListStore+ LocalSkillListStore LocalSkillListStore+ LocalSkillImportStore LocalSkillImportStore+ FeatureFlags *featureflag.Service// IssueStatusCatalog reads the workspace status catalog. Defaults to// Queries; a test can substitute a counting wrapper to assert HOW MANY// catalog reads a request performs, which is the only property that@@ -960,6 +968,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.authorizeIssueWindow(w, r, issue.ID, issue.WorkspaceID, "direct") {+ return db.Issue{}, false+ }return issue, true}@@ -983,6 +994,9 @@ func (h *Handler) loadIssueForUser(w http.ResponseWriter, r *http.Request, issuewriteError(w, http.StatusNotFound, "issue not found")return db.Issue{}, false}+ if !h.authorizeIssueWindow(w, r, issue.ID, issue.WorkspaceID, "direct") {+ return db.Issue{}, false+ }return issue, true}@@ -1154,5 +1168,8 @@ func (h *Handler) loadInboxItemForUser(w http.ResponseWriter, r *http.Request, iwriteError(w, http.StatusNotFound, "inbox item not found")return db.InboxItem{}, false}+ if item.IssueID.Valid && !h.authorizeIssueWindow(w, r, item.IssueID, item.WorkspaceID, "inbox") {+ return db.InboxItem{}, false+ }return item, true}diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex ad1147d303..f4cb263408 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -3,11 +3,13 @@ package handlerimport ("context""encoding/json"+ "fmt""log/slog""net/http""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -114,9 +116,31 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {return}- resp := make([]InboxItemResponse, len(items))- for i, item := range items {- resp[i] = inboxRowToResponse(item)+ policy, windowEnabled := h.issueWindowPolicy(r.Context(), wsUUID)+ issueIDs := make([]pgtype.UUID, 0, len(items))+ for _, item := range items {+ if item.IssueID.Valid {+ issueIDs = append(issueIDs, item.IssueID)+ }+ }+ var visible map[pgtype.UUID]struct{}+ if windowEnabled && policy.action == entitlement.ActionEnforce {+ visible, err = h.visibleIssueIDSet(r.Context(), wsUUID, policy, issueIDs)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list inbox")+ return+ }+ } else if windowEnabled {+ h.observeIssueWindow(r.Context(), wsUUID, policy, issueIDs, "inbox")+ }+ resp := make([]InboxItemResponse, 0, len(items))+ for _, item := range items {+ if visible != nil && item.IssueID.Valid {+ if _, ok := visible[item.IssueID]; !ok {+ continue+ }+ }+ resp = append(resp, inboxRowToResponse(item))}writeJSON(w, http.StatusOK, resp)@@ -151,9 +175,31 @@ func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {return}- resp := make([]InboxItemResponse, len(items))- for i, item := range items {- resp[i] = archivedInboxRowToResponse(item)+ policy, windowEnabled := h.issueWindowPolicy(r.Context(), wsUUID)+ issueIDs := make([]pgtype.UUID, 0, len(items))+ for _, item := range items {+ if item.IssueID.Valid {+ issueIDs = append(issueIDs, item.IssueID)+ }+ }+ var visible map[pgtype.UUID]struct{}+ if windowEnabled && policy.action == entitlement.ActionEnforce {+ visible, err = h.visibleIssueIDSet(r.Context(), wsUUID, policy, issueIDs)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list archived inbox")+ return+ }+ } else if windowEnabled {+ h.observeIssueWindow(r.Context(), wsUUID, policy, issueIDs, "inbox")+ }+ resp := make([]InboxItemResponse, 0, len(items))+ for _, item := range items {+ if visible != nil && item.IssueID.Valid {+ if _, ok := visible[item.IssueID]; !ok {+ continue+ }+ }+ resp = append(resp, archivedInboxRowToResponse(item))}writeJSON(w, http.StatusOK, resp)@@ -298,15 +344,33 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {return}- count, err := h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),- })+ var count int64+ var err error+ policy, windowEnabled := h.issueWindowPolicy(r.Context(), wsUUID)+ if windowEnabled && policy.action == entitlement.ActionEnforce {+ count, err = h.countUnreadInboxWithinWindow(r.Context(), wsUUID, parseUUID(userID), policy)+ } else {+ count, err = h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ })+ }if err != nil {writeError(w, http.StatusInternalServerError, "failed to count unread inbox")return}+ if windowEnabled && policy.action == entitlement.ActionObserve {+ windowed, observeErr := h.countUnreadInboxWithinWindow(r.Context(), wsUUID, parseUUID(userID), policy)+ if observeErr != nil {+ slog.Warn("observe unread inbox window failed", "error", observeErr)+ h.recordIssueWindow(policy.action, "inbox_count", "error")+ } else if windowed == count {+ h.recordIssueWindow(policy.action, "inbox_count", "allowed")+ } else {+ h.recordIssueWindow(policy.action, "inbox_count", "would_block")+ }+ }writeJSON(w, http.StatusOK, map[string]int64{"count": count})}@@ -336,17 +400,122 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {return}- resp := make([]InboxWorkspaceUnreadResponse, len(rows))- for i, row := range rows {- resp[i] = InboxWorkspaceUnreadResponse{- WorkspaceID: uuidToString(row.WorkspaceID),- Count: row.Count,+ type workspacePolicy struct {+ policy issueWindowPolicy+ legacyCount int64+ }+ policies := make(map[pgtype.UUID]workspacePolicy, len(rows))+ workspaceIDs := make([]pgtype.UUID, 0, len(rows))+ limits := make([]int64, 0, len(rows))+ for _, row := range rows {+ if policy, enabled := h.issueWindowPolicy(r.Context(), row.WorkspaceID); enabled {+ policies[row.WorkspaceID] = workspacePolicy{policy: policy, legacyCount: row.Count}+ workspaceIDs = append(workspaceIDs, row.WorkspaceID)+ limits = append(limits, policy.limit)+ }+ }+ windowedCounts := map[pgtype.UUID]int64{}+ if len(workspaceIDs) > 0 {+ windowedCounts, err = h.unreadInboxCountsWithinWindows(r.Context(), parseUUID(userID), workspaceIDs, limits)+ if err != nil {+ failClosed := false+ for _, item := range policies {+ if item.policy.action == entitlement.ActionEnforce {+ failClosed = true+ } else {+ h.recordIssueWindow(item.policy.action, "inbox_summary", "error")+ }+ }+ if failClosed {+ writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")+ return+ }+ slog.Warn("observe unread inbox summary window failed", "error", err)}}+ resp := make([]InboxWorkspaceUnreadResponse, 0, len(rows))+ for _, row := range rows {+ count := row.Count+ if item, enabled := policies[row.WorkspaceID]; enabled && err == nil {+ windowed := windowedCounts[row.WorkspaceID]+ if item.policy.action == entitlement.ActionEnforce {+ count = windowed+ } else if windowed == item.legacyCount {+ h.recordIssueWindow(item.policy.action, "inbox_summary", "allowed")+ } else {+ h.recordIssueWindow(item.policy.action, "inbox_summary", "would_block")+ }+ }+ if count == 0 {+ continue+ }+ resp = append(resp, InboxWorkspaceUnreadResponse{+ WorkspaceID: uuidToString(row.WorkspaceID),+ Count: count,+ })+ }+writeJSON(w, http.StatusOK, resp)}+func (h *Handler) countUnreadInboxWithinWindow(ctx context.Context, workspaceID, recipientID pgtype.UUID, policy issueWindowPolicy) (int64, error) {+ query := fmt.Sprintf(`SELECT COUNT(*)::bigint+ FROM inbox_item i+ WHERE i.workspace_id = $1+ AND i.recipient_type = 'member'+ AND i.recipient_id = $2+ AND i.read = false+ AND i.archived = false+ AND (i.issue_id IS NULL OR %s)`, issueWindowIDPredicate("i.issue_id", "$1", "$3"))+ var count int64+ err := h.DB.QueryRow(ctx, query, workspaceID, recipientID, policy.limit).Scan(&count)+ return count, err+}++// unreadInboxCountsWithinWindows preserves CountUnreadInboxByWorkspace's+// DISTINCT ON semantics while applying every enabled workspace policy in one+// database round trip. Observe callers use the result only for telemetry; the+// legacy response remains untouched.+func (h *Handler) unreadInboxCountsWithinWindows(ctx context.Context, recipientID pgtype.UUID, workspaceIDs []pgtype.UUID, limits []int64) (map[pgtype.UUID]int64, error) {+ query := fmt.Sprintf(`WITH policies AS (+ SELECT workspace_id, issue_limit+ FROM unnest($1::uuid[], $2::bigint[]) AS policy(workspace_id, issue_limit)+)+ SELECT policy.workspace_id, filtered.count+ FROM policies policy+ CROSS JOIN LATERAL (+ SELECT COUNT(*)::bigint AS count+ FROM (+ SELECT DISTINCT ON (COALESCE(i.issue_id, i.id)) i.read+ FROM inbox_item i+ JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id+ WHERE i.workspace_id = policy.workspace_id+ AND i.recipient_type = 'member'+ AND i.recipient_id = $3+ AND i.archived = false+ AND (i.issue_id IS NULL OR %s)+ ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC+ ) newest+ WHERE newest.read = false+ ) filtered`, issueWindowIDPredicate("i.issue_id", "policy.workspace_id", "policy.issue_limit"))+ rows, err := h.DB.Query(ctx, query, workspaceIDs, limits, recipientID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ counts := make(map[pgtype.UUID]int64, len(workspaceIDs))+ for rows.Next() {+ var workspaceID pgtype.UUID+ var count int64+ if err := rows.Scan(&workspaceID, &count); err != nil {+ return nil, err+ }+ counts[workspaceID] = count+ }+ return counts, rows.Err()+}+func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 84890b4e04..eb901511f5 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -20,6 +20,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/channelmedia""github.com/multica-ai/multica/server/internal/dispatch"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger"@@ -595,7 +596,7 @@ type searchResult struct {// It uses LOWER(column) LIKE for case-insensitive matching compatible with pg_bigm 1.2 GIN indexes.// Search patterns are lowercased in Go to avoid redundant LOWER() on the pattern side in SQL.// LIKE patterns are pre-built in Go (e.g. "%html%") so pg_bigm can extract bigrams from a single parameter value.-func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool) (string, []any) {+func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, creationWindowLimit *int64) (string, []any) {// Lowercase in Go so SQL only needs LOWER() on the column side.phrase = strings.ToLower(phrase)for i, t := range terms {@@ -679,6 +680,10 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,if !includeClosed {whereClause += " AND issue_effective_status(i.workspace_id, i.status) NOT IN ('done', 'cancelled')"}+ if creationWindowLimit != nil {+ limitRef := nextArg(*creationWindowLimit)+ whereClause = issueWindowPredicate("i", wsParam, limitRef) + " AND " + whereClause+ }// --- ORDER BY clause ---// Build ranking CASE with fine-grained tiers.@@ -888,8 +893,13 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {}terms := splitSearchTerms(q)queryNum, hasNum := parseQueryNumber(q)+ policy, windowEnabled := h.issueWindowPolicy(ctx, wsUUID)- sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed)+ var creationWindowLimit *int64+ if windowEnabled && policy.action == entitlement.ActionEnforce {+ creationWindowLimit = &policy.limit+ }+ sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, creationWindowLimit)// Fill placeholder args: $4 = workspace_id, last two = limit, offsetargs[3] = wsUUIDargs[len(args)-2] = limit@@ -955,6 +965,13 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {if len(results) > 0 {total = results[0].totalCount}+ resultIDs := make([]pgtype.UUID, len(results))+ for i, result := range results {+ resultIDs[i] = result.issue.ID+ }+ if windowEnabled {+ h.observeIssueWindow(ctx, wsUUID, policy, resultIDs, "search")+ }prefix := h.getIssuePrefix(ctx, wsUUID)fillSearch := h.newStatusCategoryFiller(ctx, wsUUID)@@ -1019,6 +1036,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {if !ok {return}+ windowPolicy, windowEnabled := h.issueWindowPolicy(ctx, wsUUID)// Parse optional filter params. Malformed UUIDs in filters return 400 —// silently coercing them to a zero UUID would mask a client bug and let@@ -1118,6 +1136,26 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list issues")return}+ openIDs := make([]pgtype.UUID, len(issues))+ for i, issue := range issues {+ openIDs[i] = issue.ID+ }+ if windowEnabled && windowPolicy.action == entitlement.ActionEnforce {+ visible, visibleErr := h.visibleIssueIDSet(ctx, wsUUID, windowPolicy, openIDs)+ if visibleErr != nil {+ writeError(w, http.StatusInternalServerError, "failed to list issues")+ return+ }+ filtered := issues[:0]+ for _, issue := range issues {+ if _, ok := visible[issue.ID]; ok {+ filtered = append(filtered, issue)+ }+ }+ issues = filtered+ } else if windowEnabled {+ h.observeIssueWindow(ctx, wsUUID, windowPolicy, openIDs, "list")+ }prefix := h.getIssuePrefix(ctx, wsUUID)ids := make([]pgtype.UUID, len(issues))@@ -1429,6 +1467,9 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {)))`, ref))}+ if windowEnabled {+ where = appendIssueWindow(where, addArg, windowPolicy, "$1", "i")+ }whereSql := strings.Join(where, " AND ")@@ -1526,6 +1567,9 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)for i, issue := range issues {ids[i] = issue.ID}+ if windowEnabled {+ h.observeIssueWindow(ctx, wsUUID, windowPolicy, ids, "list")+ }labelsMap := h.labelsByIssue(ctx, wsUUID, ids)resp := make([]IssueResponse, len(issues))for i, issue := range issues {@@ -1720,6 +1764,7 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {if !ok {return}+ windowPolicy, windowEnabled := h.issueWindowPolicy(ctx, wsUUID)limit := 50offset := 0@@ -1966,6 +2011,9 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {))}}+ if windowEnabled {+ where = appendIssueWindow(where, addArg, windowPolicy, "$1", "i")+ }sortCol := "position"sortIsExpr := false@@ -2129,6 +2177,9 @@ ORDER BYfor i, row := range groupedRows {ids[i] = row.ID}+ if windowEnabled {+ h.observeIssueWindow(ctx, wsUUID, windowPolicy, ids, "grouped")+ }labelsMap := h.labelsByIssue(ctx, wsUUID, ids)prefix := h.getIssuePrefix(ctx, wsUUID)// One Resolver for the whole page — a per-row filler would query the@@ -2216,6 +2267,27 @@ func (h *Handler) ListChildIssues(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list child issues")return}+ windowPolicy, windowEnabled := h.issueWindowPolicy(r.Context(), issue.WorkspaceID)+ childIDs := make([]pgtype.UUID, len(children))+ for i, child := range children {+ childIDs[i] = child.ID+ }+ if windowEnabled && windowPolicy.action == entitlement.ActionEnforce {+ visible, visibleErr := h.visibleIssueIDSet(r.Context(), issue.WorkspaceID, windowPolicy, childIDs)+ if visibleErr != nil {+ writeError(w, http.StatusInternalServerError, "failed to list child issues")+ return+ }+ filtered := children[:0]+ for _, child := range children {+ if _, ok := visible[child.ID]; ok {+ filtered = append(filtered, child)+ }+ }+ children = filtered+ } else if windowEnabled {+ h.observeIssueWindow(r.Context(), issue.WorkspaceID, windowPolicy, childIDs, "children")+ }prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)ids := make([]pgtype.UUID, len(children))for i, child := range children {@@ -2302,6 +2374,27 @@ func (h *Handler) ListChildrenByParents(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to list child issues")return}+ windowPolicy, windowEnabled := h.issueWindowPolicy(r.Context(), wsUUID)+ childIDs := make([]pgtype.UUID, len(children))+ for i, child := range children {+ childIDs[i] = child.ID+ }+ if windowEnabled && windowPolicy.action == entitlement.ActionEnforce {+ visible, visibleErr := h.visibleIssueIDSet(r.Context(), wsUUID, windowPolicy, childIDs)+ if visibleErr != nil {+ writeError(w, http.StatusInternalServerError, "failed to list child issues")+ return+ }+ filtered := children[:0]+ for _, child := range children {+ if _, ok := visible[child.ID]; ok {+ filtered = append(filtered, child)+ }+ }+ children = filtered+ } else if windowEnabled {+ h.observeIssueWindow(r.Context(), wsUUID, windowPolicy, childIDs, "children")+ }prefix := h.getIssuePrefix(r.Context(), wsUUID)ids := make([]pgtype.UUID, len(children))for i, child := range children {@@ -2336,23 +2429,66 @@ func (h *Handler) ChildIssueProgress(w http.ResponseWriter, r *http.Request) {return}- rows, err := h.Queries.ChildIssueProgress(r.Context(), wsUUID)- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to get child issue progress")- return- }-type progressEntry struct {ParentIssueID string `json:"parent_issue_id"`Total int64 `json:"total"`Done int64 `json:"done"`- }- resp := make([]progressEntry, len(rows))- for i, row := range rows {- resp[i] = progressEntry{- ParentIssueID: uuidToString(row.ParentIssueID),- Total: row.Total,- Done: row.Done,+ VisibleTotal int64 `json:"visible_total"`+ VisibleDone int64 `json:"visible_done"`+ HiddenTotal int64 `json:"hidden_total"`+ }+ policy, windowEnabled := h.issueWindowPolicy(r.Context(), wsUUID)+ resp := []progressEntry{}+ if windowEnabled && policy.action == entitlement.ActionEnforce {+ query := fmt.Sprintf(`WITH visible_issue_ids AS MATERIALIZED (+ %s+ )+ SELECT i.parent_issue_id,+ COUNT(*)::bigint AS total,+ COUNT(*) FILTER (WHERE issue_effective_status(i.workspace_id, i.status) IN ('done', 'cancelled'))::bigint AS done,+ COUNT(child_visible.id)::bigint AS visible_total,+ COUNT(child_visible.id) FILTER (WHERE issue_effective_status(i.workspace_id, i.status) IN ('done', 'cancelled'))::bigint AS visible_done+ FROM issue i+ JOIN visible_issue_ids parent_visible ON parent_visible.id = i.parent_issue_id+ LEFT JOIN visible_issue_ids child_visible ON child_visible.id = i.id+ WHERE i.workspace_id = $1+ AND i.parent_issue_id IS NOT NULL+ GROUP BY i.parent_issue_id`, issueWindowVisibleSetSQL("$1", "$2"))+ rows, err := h.DB.Query(r.Context(), query, wsUUID, policy.limit)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to get child issue progress")+ return+ }+ defer rows.Close()+ for rows.Next() {+ var parentID pgtype.UUID+ var entry progressEntry+ if err := rows.Scan(&parentID, &entry.Total, &entry.Done, &entry.VisibleTotal, &entry.VisibleDone); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to get child issue progress")+ return+ }+ entry.ParentIssueID = uuidToString(parentID)+ entry.HiddenTotal = entry.Total - entry.VisibleTotal+ resp = append(resp, entry)+ }+ if err := rows.Err(); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to get child issue progress")+ return+ }+ } else {+ rows, err := h.Queries.ChildIssueProgress(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to get child issue progress")+ return+ }+ for _, row := range rows {+ resp = append(resp, progressEntry{+ ParentIssueID: uuidToString(row.ParentIssueID),+ Total: row.Total,+ Done: row.Done,+ VisibleTotal: row.Total,+ VisibleDone: row.Done,+ })}}writeJSON(w, http.StatusOK, map[string]any{diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 8e5259892d..5a20e1fa30 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -9,6 +9,7 @@ import ("errors""fmt""io"+ "log/slog""net/http""sort""strconv"@@ -17,6 +18,8 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -25,6 +28,9 @@ const (issueTableDefaultPageSize = 50issueTableMaxPageSize = 100issueTableQueryTimeout = 8 * time.Second+ // This is a transport and memory guard, independent of entitlement limits.+ // Larger visible sets stay in PostgreSQL instead of becoming UUID arrays.+ issueTableWindowIDCacheLimit = 4_096)func withIssueTableQueryTimeout(r *http.Request) (*http.Request, context.CancelFunc) {@@ -47,9 +53,44 @@ func (h *Handler) beginIssueTableSnapshot(ctx context.Context) (*Handler, pgx.Txsnapshot := *hsnapshot.DB = txsnapshot.Queries = db.New(tx)+ snapshot.issueTableWindowCache = &issueTableWindowCache{}return &snapshot, tx, nil}+type issueTableWindowCache struct {+ workspaceID pgtype.UUID+ limit int64+ policyRevision int64+ ids []pgtype.UUID+ useIDs bool+ loaded bool+}++func (h *Handler) issueTableVisibleIssueIDs(ctx context.Context, workspaceID pgtype.UUID, policy issueWindowPolicy) ([]pgtype.UUID, bool, error) {+ cache := h.issueTableWindowCache+ if cache != nil && cache.loaded && cache.workspaceID == workspaceID && cache.limit == policy.limit && cache.policyRevision == policy.policyRevision {+ return cache.ids, cache.useIDs, nil+ }+ var ids []pgtype.UUID+ useIDs := policy.limit <= issueTableWindowIDCacheLimit+ if useIDs {+ var err error+ ids, useIDs, err = h.issueWindowVisibleIDsUpTo(ctx, workspaceID, policy, issueTableWindowIDCacheLimit)+ if err != nil {+ return nil, false, err+ }+ }+ if cache != nil {+ cache.workspaceID = workspaceID+ cache.limit = policy.limit+ cache.policyRevision = policy.policyRevision+ cache.ids = ids+ cache.useIDs = useIDs+ cache.loaded = true+ }+ return ids, useIDs, nil+}+func writeIssueTableQueryFailure(w http.ResponseWriter, r *http.Request, message string) {if errors.Is(r.Context().Err(), context.DeadlineExceeded) {writeJSON(w, http.StatusGatewayTimeout, map[string]any{@@ -405,6 +446,13 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,writeError(w, http.StatusInternalServerError, "failed to canonicalize table query")return issueTableSQL{}, false}+ windowPolicy, windowEnabled := h.issueWindowPolicy(r.Context(), workspaceUUID)+ if windowEnabled && windowPolicy.action == entitlement.ActionEnforce {+ // A cursor issued under a different entitlement revision or limit must+ // not be accepted after the visible collection changes.+ digest := sha256.Sum256([]byte(fmt.Sprintf("%s|%s|%d|%d", fingerprint, windowPolicy.action, windowPolicy.limit, windowPolicy.policyRevision)))+ fingerprint = "sha256:" + hex.EncodeToString(digest[:])+ }where := []string{"i.workspace_id = $1"}args := []any{workspaceUUID}@@ -633,6 +681,21 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,where = append(where, "i.parent_issue_id IS NULL")}where = appendIssueTableSearchFilter(where, addArg, spec.Search)+ if windowEnabled && windowPolicy.action == entitlement.ActionEnforce && h.issueTableWindowCache != nil {+ visibleIDs, useIDs, err := h.issueTableVisibleIssueIDs(r.Context(), workspaceUUID, windowPolicy)+ if err != nil {+ slog.Warn("resolve table issue window failed", append(logger.RequestAttrs(r), "error", err)...)+ writeIssueTableQueryFailure(w, r, "failed to resolve table issue window")+ return issueTableSQL{}, false+ }+ if useIDs {+ where = append(where, fmt.Sprintf("i.id = ANY(%s::uuid[])", addArg(visibleIDs)))+ } else {+ where = appendIssueWindow(where, addArg, windowPolicy, "$1", "i")+ }+ } else if windowEnabled {+ where = appendIssueWindow(where, addArg, windowPolicy, "$1", "i")+ }return issueTableSQL{where: strings.Join(where, " AND "),diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex 6bda9b8ab9..3da54a0bc7 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -479,6 +479,9 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,for index, row := range scanned {issueIDs[index] = row.issue.ID}+ if windowPolicy, enabled := baseHandler.issueWindowPolicy(r.Context(), compiled.workspaceID); enabled {+ baseHandler.observeIssueWindow(r.Context(), compiled.workspaceID, windowPolicy, issueIDs, "table")+ }labelsByIssue := baseHandler.labelsByIssue(r.Context(), compiled.workspaceID, issueIDs)// One Resolver for the page — see newStatusCategoryFiller. (MUL-6243)fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID)diff --git a/server/internal/handler/issue_window.go b/server/internal/handler/issue_window.gonew file mode 100644index 0000000000..83daa4b1ed--- /dev/null+++ b/server/internal/handler/issue_window.go@@ -0,0 +1,271 @@+package handler++import (+ "context"+ "fmt"+ "log/slog"+ "net/http"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+)++const (+ issueWindowErrorCode = "issue_outside_creation_window"+ // Defensive ceiling for a malformed Cloud payload. Failing open is safer+ // than accepting an effectively unbounded recursive/list query.+ maxIssueWindowLimit = 1_000_000+)++// issueWindowPolicy is the validated, request-local interpretation of the+// Cloud gate. Invalid decisions fail open and do not touch the issue table.+type issueWindowPolicy struct {+ action entitlement.Action+ limit int64+ policyRevision int64+}++type IssueWindowUsageResponse struct {+ Action string `json:"action"`+ Used *int64 `json:"used"`+ Limit *int64 `json:"limit"`+ HasMore *bool `json:"has_more"`+ PolicyRevision *int64 `json:"policy_revision"`+ CalculatedAt *string `json:"calculated_at"`+}++func (h *Handler) issueWindowPolicy(ctx context.Context, workspaceID pgtype.UUID) (issueWindowPolicy, bool) {+ if h.Entitlements == nil || !workspaceID.Valid {+ return issueWindowPolicy{}, false+ }+ decision := h.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateIssueWindow)+ gate := decision.Gate+ if gate.Action == entitlement.ActionOff {+ return issueWindowPolicy{}, false+ }+ if (gate.Action != entitlement.ActionObserve && gate.Action != entitlement.ActionEnforce) ||+ gate.Limit == nil || *gate.Limit <= 0 || *gate.Limit > maxIssueWindowLimit {+ // Cloud is the source of truth for the limit. A malformed decision is+ // fail-open, matching the entitlement client's unavailable behavior.+ return issueWindowPolicy{}, false+ }+ return issueWindowPolicy{+ action: gate.Action,+ limit: int64(*gate.Limit),+ policyRevision: decision.PolicyRevision,+ }, true+}++// issueWindowVisibleSetSQL returns the tenant-scoped query for the newest N+// issues by immutable workspace issue number plus every ancestor needed to+// render those issues. Ancestors supplement the base N and never expose their+// other children.+func issueWindowVisibleSetSQL(workspaceRef, limitRef string) string {+ return fmt.Sprintf(`WITH RECURSIVE issue_window_base AS MATERIALIZED (+ SELECT id, parent_issue_id+ FROM issue+ WHERE workspace_id = %s+ ORDER BY number DESC+ LIMIT %s+ ), issue_window_visible(id, parent_issue_id) AS (+ SELECT id, parent_issue_id FROM issue_window_base+ UNION+ SELECT parent.id, parent.parent_issue_id+ FROM issue parent+ JOIN issue_window_visible child ON child.parent_issue_id = parent.id+ WHERE parent.workspace_id = %s+ )+ SELECT id FROM issue_window_visible`, workspaceRef, limitRef, workspaceRef)+}++func issueWindowIDPredicate(issueIDExpr, workspaceRef, limitRef string) string {+ return fmt.Sprintf("%s IN (\n\t%s\n)", issueIDExpr, issueWindowVisibleSetSQL(workspaceRef, limitRef))+}++func issueWindowPredicate(issueAlias, workspaceRef, limitRef string) string {+ return issueWindowIDPredicate(issueAlias+".id", workspaceRef, limitRef)+}++// appendIssueWindow applies enforcement to a dynamic issue query. Observe and+// off deliberately leave the legacy SQL byte-for-byte unchanged.+func appendIssueWindow(where []string, addArg func(any) string, policy issueWindowPolicy, workspaceRef, issueAlias string) []string {+ if policy.action != entitlement.ActionEnforce {+ return where+ }+ return append(where, issueWindowPredicate(issueAlias, workspaceRef, addArg(policy.limit)))+}++// issueIDsWithinWindow checks a response batch against one stable window+// snapshot. It is used both for direct enforcement and observe-mode telemetry.+func (h *Handler) issueIDsWithinWindow(ctx context.Context, workspaceID pgtype.UUID, policy issueWindowPolicy, issueIDs []pgtype.UUID) (bool, error) {+ if len(issueIDs) == 0 {+ return true, nil+ }+ visible, err := h.visibleIssueIDSet(ctx, workspaceID, policy, issueIDs)+ requested := make(map[pgtype.UUID]struct{}, len(issueIDs))+ for _, id := range issueIDs {+ requested[id] = struct{}{}+ }+ return len(visible) == len(requested), err+}++func (h *Handler) visibleIssueIDSet(ctx context.Context, workspaceID pgtype.UUID, policy issueWindowPolicy, issueIDs []pgtype.UUID) (map[pgtype.UUID]struct{}, error) {+ visible := make(map[pgtype.UUID]struct{}, len(issueIDs))+ if len(issueIDs) == 0 {+ return visible, nil+ }+ query := fmt.Sprintf(`SELECT requested.id+ FROM unnest($3::uuid[]) requested(id)+ WHERE %s`, issueWindowPredicate("requested", "$1", "$2"))+ rows, err := h.DB.Query(ctx, query, workspaceID, policy.limit, issueIDs)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ visible[id] = struct{}{}+ }+ return visible, rows.Err()+}++// issueWindowVisibleIDsUpTo returns the complete visible set only when it fits+// within maxIDs. The extra row detects ancestor expansion without loading an+// unbounded UUID slice into the application.+func (h *Handler) issueWindowVisibleIDsUpTo(ctx context.Context, workspaceID pgtype.UUID, policy issueWindowPolicy, maxIDs int64) ([]pgtype.UUID, bool, error) {+ query := fmt.Sprintf("SELECT id FROM (\n%s\n) bounded_issue_window LIMIT $3", issueWindowVisibleSetSQL("$1", "$2"))+ rows, err := h.DB.Query(ctx, query, workspaceID, policy.limit, maxIDs+1)+ if err != nil {+ return nil, false, err+ }+ defer rows.Close()+ ids := make([]pgtype.UUID, 0, maxIDs)+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, false, err+ }+ ids = append(ids, id)+ }+ if err := rows.Err(); err != nil {+ return nil, false, err+ }+ if int64(len(ids)) > maxIDs {+ return nil, false, nil+ }+ return ids, true, nil+}++func (h *Handler) recordIssueWindow(action entitlement.Action, surface, result string) {+ if h.Metrics != nil {+ h.Metrics.RecordIssueWindowDecision(string(action), surface, result)+ }+}++// observeIssueWindow records whether this response would have changed under+// enforcement, without changing the response itself. Database failures remain+// fail-open and are represented as a bounded metric outcome.+func (h *Handler) observeIssueWindow(ctx context.Context, workspaceID pgtype.UUID, policy issueWindowPolicy, issueIDs []pgtype.UUID, surface string) {+ if policy.action != entitlement.ActionObserve || len(issueIDs) == 0 {+ return+ }+ allVisible, err := h.issueIDsWithinWindow(ctx, workspaceID, policy, issueIDs)+ if err != nil {+ slog.Warn("observe issue creation window failed", "error", err, "surface", surface)+ h.recordIssueWindow(policy.action, surface, "error")+ return+ }+ if allVisible {+ h.recordIssueWindow(policy.action, surface, "allowed")+ return+ }+ h.recordIssueWindow(policy.action, surface, "would_block")+}++// authorizeIssueWindow runs only after the issue was loaded inside the caller's+// workspace. This preserves cross-workspace 404s while returning a product-+// actionable response for a same-workspace issue outside an enforced window.+// Once Cloud has supplied a valid enforce policy, a database error is an+// authorization uncertainty and therefore fails closed. That is deliberately+// different from an unavailable or malformed Cloud policy, which fails open+// before any window query runs.+func (h *Handler) authorizeIssueWindow(w http.ResponseWriter, r *http.Request, issueID, workspaceID pgtype.UUID, surface string) bool {+ policy, enabled := h.issueWindowPolicy(r.Context(), workspaceID)+ if !enabled {+ return true+ }+ allVisible, err := h.issueIDsWithinWindow(r.Context(), workspaceID, policy, []pgtype.UUID{issueID})+ if err != nil {+ if policy.action == entitlement.ActionObserve {+ slog.Warn("observe issue creation window failed", "error", err, "surface", surface)+ h.recordIssueWindow(policy.action, surface, "error")+ return true+ }+ h.recordIssueWindow(policy.action, surface, "error")+ writeError(w, http.StatusInternalServerError, "failed to check issue access")+ return false+ }+ if allVisible {+ h.recordIssueWindow(policy.action, surface, "allowed")+ return true+ }+ if policy.action == entitlement.ActionObserve {+ h.recordIssueWindow(policy.action, surface, "would_block")+ return true+ }+ h.recordIssueWindow(policy.action, surface, "blocked")+ writeJSON(w, http.StatusPaymentRequired, map[string]any{+ "error": issueWindowErrorCode,+ "message": "This issue is outside the workspace's recently created issue window.",+ "limit": policy.limit,+ "policy_revision": policy.policyRevision,+ })+ return false+}++// GetIssueWindowUsage returns a bounded used/limit snapshot for Billing. The+// query reads at most limit+1 index entries, so a large workspace never pays+// for a full COUNT(*). Off and malformed policies perform no issue-table read.+func (h *Handler) GetIssueWindowUsage(w http.ResponseWriter, r *http.Request) {+ workspaceID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")+ if !ok {+ return+ }+ policy, enabled := h.issueWindowPolicy(r.Context(), workspaceID)+ if !enabled {+ writeJSON(w, http.StatusOK, IssueWindowUsageResponse{Action: string(entitlement.ActionOff)})+ return+ }+ var sampled int64+ err := h.DB.QueryRow(r.Context(), `SELECT COUNT(*)::bigint+ FROM (+ SELECT 1+ FROM issue+ WHERE workspace_id = $1+ ORDER BY number DESC+ LIMIT $2+ ) recent`, workspaceID, policy.limit+1).Scan(&sampled)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load issue window usage")+ return+ }+ used := sampled+ hasMore := sampled > policy.limit+ if hasMore {+ used = policy.limit+ }+ calculatedAt := time.Now().UTC().Format(time.RFC3339)+ writeJSON(w, http.StatusOK, IssueWindowUsageResponse{+ Action: string(policy.action),+ Used: &used,+ Limit: &policy.limit,+ HasMore: &hasMore,+ PolicyRevision: &policy.policyRevision,+ CalculatedAt: &calculatedAt,+ })+}diff --git a/server/internal/handler/issue_window_test.go b/server/internal/handler/issue_window_test.gonew file mode 100644index 0000000000..00b64e9226--- /dev/null+++ b/server/internal/handler/issue_window_test.go@@ -0,0 +1,454 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+)++type staticIssueWindowProvider struct {+ decision entitlement.Decision+}++type countingIssueWindowDB struct {+ dbExecutor+ windowQueries int+}++func (db *countingIssueWindowDB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if strings.Contains(sql, "issue_window_base") {+ db.windowQueries+++ }+ return db.dbExecutor.Query(ctx, sql, args...)+}++func (p staticIssueWindowProvider) Gate(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return p.decision+}++func issueWindowProvider(action entitlement.Action, limit int) staticIssueWindowProvider {+ return staticIssueWindowProvider{decision: entitlement.Decision{+ Gate: entitlement.Gate{Action: action, Limit: &limit},+ PolicyRevision: 7,+ }}+}++func TestIssueWindowPolicyFailsOpen(t *testing.T) {+ workspaceID := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ tests := []struct {+ name string+ provider entitlement.Provider+ }{+ {name: "nil provider"},+ {name: "off", provider: issueWindowProvider(entitlement.ActionOff, 17)},+ {name: "zero limit", provider: issueWindowProvider(entitlement.ActionEnforce, 0)},+ {name: "negative limit", provider: issueWindowProvider(entitlement.ActionObserve, -1)},+ {name: "oversized limit", provider: issueWindowProvider(entitlement.ActionEnforce, maxIssueWindowLimit+1)},+ {name: "unknown action", provider: issueWindowProvider(entitlement.Action("future"), 17)},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ h := &Handler{Entitlements: tt.provider}+ if _, enabled := h.issueWindowPolicy(context.Background(), workspaceID); enabled {+ t.Fatal("malformed or disabled policy must fail open")+ }+ })+ }+}++func TestIssueWindowPredicateUsesCreationNumberAndAncestors(t *testing.T) {+ predicate := issueWindowPredicate("i", "$1", "$2")+ for _, want := range []string{+ "WHERE workspace_id = $1",+ "ORDER BY number DESC",+ "LIMIT $2",+ "child.parent_issue_id = parent.id",+ "parent.workspace_id = $1",+ } {+ if !strings.Contains(predicate, want) {+ t.Fatalf("predicate missing %q:\n%s", want, predicate)+ }+ }+ if strings.Contains(predicate, "last_activity_at") || strings.Contains(predicate, "created_at") {+ t.Fatalf("creation window must not depend on mutable/timestamp ordering:\n%s", predicate)+ }+}++func TestAppendIssueWindowOnlyEnforces(t *testing.T) {+ for _, action := range []entitlement.Action{entitlement.ActionOff, entitlement.ActionObserve} {+ args := []any{"workspace"}+ where := appendIssueWindow([]string{"i.workspace_id = $1"}, func(value any) string {+ args = append(args, value)+ return "$2"+ }, issueWindowPolicy{action: action, limit: 17}, "$1", "i")+ if len(where) != 1 || len(args) != 1 {+ t.Fatalf("%s changed the legacy query: where=%v args=%v", action, where, args)+ }+ }+}++func TestIssueTableReusesOneVisibleIDSnapshot(t *testing.T) {+ counter := &countingIssueWindowDB{dbExecutor: testHandler.DB}+ h := *testHandler+ h.DB = counter+ h.Entitlements = issueWindowProvider(entitlement.ActionEnforce, 1)+ h.issueTableWindowCache = &issueTableWindowCache{}+ spec := issueTableQuerySpec{+ Scope: issueTableScope{Kind: "workspace"},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ }+ for range 2 {+ recorder := httptest.NewRecorder()+ compiled, ok := h.compileIssueTableQuery(recorder, newRequest(http.MethodPost, "/api/issues/table/rows", nil), spec)+ if !ok {+ t.Fatalf("compile table query: %d %s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(compiled.where, "i.id = ANY(") || strings.Contains(compiled.where, "issue_window_base") {+ t.Fatalf("table query did not use cached ids: %s", compiled.where)+ }+ }+ if counter.windowQueries != 1 {+ t.Fatalf("visible window queries = %d, want one per table snapshot", counter.windowQueries)+ }+}++func TestIssueTableLargeWindowStaysInPostgres(t *testing.T) {+ counter := &countingIssueWindowDB{dbExecutor: testHandler.DB}+ h := *testHandler+ h.DB = counter+ h.Entitlements = issueWindowProvider(entitlement.ActionEnforce, issueTableWindowIDCacheLimit+1)+ h.issueTableWindowCache = &issueTableWindowCache{}+ spec := issueTableQuerySpec{+ Scope: issueTableScope{Kind: "workspace"},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ }+ for range 2 {+ recorder := httptest.NewRecorder()+ compiled, ok := h.compileIssueTableQuery(recorder, newRequest(http.MethodPost, "/api/issues/table/rows", nil), spec)+ if !ok {+ t.Fatalf("compile table query: %d %s", recorder.Code, recorder.Body.String())+ }+ if !strings.Contains(compiled.where, "issue_window_base") || strings.Contains(compiled.where, "i.id = ANY(") {+ t.Fatalf("large table window did not stay in PostgreSQL: %s", compiled.where)+ }+ }+ if counter.windowQueries != 0 {+ t.Fatalf("large table window preloads = %d, want none", counter.windowQueries)+ }+}++func TestIssueWindowUsageOffDoesNotNeedDatabase(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest(http.MethodGet, "/api/issues/window-usage", nil)+ req.Header.Set("X-Workspace-ID", uuid.NewString())+ recorder := httptest.NewRecorder()+ h.GetIssueWindowUsage(recorder, req)+ if recorder.Code != http.StatusOK {+ t.Fatalf("off usage status = %d: %s", recorder.Code, recorder.Body.String())+ }+ var body IssueWindowUsageResponse+ if err := json.NewDecoder(recorder.Body).Decode(&body); err != nil {+ t.Fatalf("decode off usage: %v", err)+ }+ if body.Action != string(entitlement.ActionOff) || body.Used != nil || body.Limit != nil {+ t.Fatalf("unexpected off usage: %#v", body)+ }+}++func TestIssueCreationWindowEnforcesNewestBaseAndAncestorChain(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Issue window", "issue-window-"+uuid.NewString(), testutil.Cols{+ "issue_prefix": "WIN",+ })+ dbfx.Member(t, workspaceID, testUserID, "owner")++ rootID := dbfx.Issue(t, "old root", testutil.Cols{"workspace_id": workspaceID, "number": 1})+ hiddenSiblingID := dbfx.Issue(t, "hidden sibling", testutil.Cols{+ "workspace_id": workspaceID,+ "number": 50,+ "parent_issue_id": rootID,+ })+ newestChildID := dbfx.Issue(t, "newest child", testutil.Cols{+ "workspace_id": workspaceID,+ "number": 100,+ "parent_issue_id": rootID,+ })+ // Activity on an older issue must not move it into a creation window.+ dbfx.Exec(t, `UPDATE issue SET last_activity_at = now() + interval '1 hour' WHERE id = $1`, hiddenSiblingID)++ h := *testHandler+ h.Entitlements = issueWindowProvider(entitlement.ActionEnforce, 1)+ policy, enabled := h.issueWindowPolicy(context.Background(), parseUUID(workspaceID))+ if !enabled {+ t.Fatal("expected enforce policy")+ }+ newestUUID := parseUUID(newestChildID)+ if visible, err := h.issueIDsWithinWindow(context.Background(), parseUUID(workspaceID), policy, []pgtype.UUID{newestUUID, newestUUID}); err != nil || !visible {+ t.Fatalf("duplicate visible ids = %v, %v", visible, err)+ }++ request := func(issueID string) *http.Request {+ req := httptest.NewRequest(http.MethodGet, "/api/issues/"+issueID, nil)+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ return req+ }+ for _, visibleID := range []string{newestChildID, rootID} {+ recorder := httptest.NewRecorder()+ if _, ok := h.loadIssueForUser(recorder, request(visibleID), visibleID); !ok {+ t.Fatalf("expected %s to be visible, got %d: %s", visibleID, recorder.Code, recorder.Body.String())+ }+ }++ blocked := httptest.NewRecorder()+ if _, ok := h.loadIssueForUser(blocked, request(hiddenSiblingID), hiddenSiblingID); ok {+ t.Fatal("hidden sibling unexpectedly passed direct access")+ }+ if blocked.Code != http.StatusPaymentRequired {+ t.Fatalf("hidden direct access status = %d, want 402: %s", blocked.Code, blocked.Body.String())+ }+ var blockedBody map[string]any+ if err := json.NewDecoder(blocked.Body).Decode(&blockedBody); err != nil {+ t.Fatalf("decode blocked response: %v", err)+ }+ if blockedBody["error"] != issueWindowErrorCode || blockedBody["limit"] != float64(1) {+ t.Fatalf("unexpected blocked response: %#v", blockedBody)+ }++ listRecorder := httptest.NewRecorder()+ listReq := request("")+ listReq.URL.Path = "/api/issues"+ h.ListIssues(listRecorder, listReq)+ if listRecorder.Code != http.StatusOK {+ t.Fatalf("list status = %d: %s", listRecorder.Code, listRecorder.Body.String())+ }+ var listBody struct {+ Issues []IssueResponse `json:"issues"`+ Total int64 `json:"total"`+ }+ if err := json.NewDecoder(listRecorder.Body).Decode(&listBody); err != nil {+ t.Fatalf("decode list: %v", err)+ }+ if listBody.Total != 2 || len(listBody.Issues) != 2 {+ t.Fatalf("visible list = %d/%d, want newest child + ancestor: %#v", len(listBody.Issues), listBody.Total, listBody.Issues)+ }+ for _, issue := range listBody.Issues {+ if issue.ID == hiddenSiblingID {+ t.Fatal("ancestor supplementation exposed a hidden sibling")+ }+ }+ usageRecorder := httptest.NewRecorder()+ usageReq := request("")+ usageReq.URL.Path = "/api/issues/window-usage"+ h.GetIssueWindowUsage(usageRecorder, usageReq)+ if usageRecorder.Code != http.StatusOK {+ t.Fatalf("usage status = %d: %s", usageRecorder.Code, usageRecorder.Body.String())+ }+ var usage IssueWindowUsageResponse+ if err := json.NewDecoder(usageRecorder.Body).Decode(&usage); err != nil {+ t.Fatalf("decode usage: %v", err)+ }+ if usage.Used == nil || *usage.Used != 1 || usage.Limit == nil || *usage.Limit != 1 || usage.HasMore == nil || !*usage.HasMore {+ t.Fatalf("unexpected bounded usage: %#v", usage)+ }+ childrenRecorder := httptest.NewRecorder()+ childrenReq := withURLParam(request(rootID), "id", rootID)+ h.ListChildIssues(childrenRecorder, childrenReq)+ if childrenRecorder.Code != http.StatusOK {+ t.Fatalf("children status = %d: %s", childrenRecorder.Code, childrenRecorder.Body.String())+ }+ var childrenBody struct {+ Issues []IssueResponse `json:"issues"`+ }+ if err := json.NewDecoder(childrenRecorder.Body).Decode(&childrenBody); err != nil {+ t.Fatalf("decode children: %v", err)+ }+ if len(childrenBody.Issues) != 1 || childrenBody.Issues[0].ID != newestChildID {+ t.Fatalf("children bypassed window: %#v", childrenBody.Issues)+ }++ // Loading the same UUID through another workspace still produces a 404,+ // never the commercial response that would reveal same-workspace existence.+ otherWorkspaceID := dbfx.Workspace(t, "Other issue window", "other-window-"+uuid.NewString())+ crossReq := request(hiddenSiblingID)+ crossReq.Header.Set("X-Workspace-ID", otherWorkspaceID)+ cross := httptest.NewRecorder()+ if _, ok := h.loadIssueForUser(cross, crossReq, hiddenSiblingID); ok || cross.Code != http.StatusNotFound {+ t.Fatalf("cross-workspace load = ok:%v status:%d body:%s", ok, cross.Code, cross.Body.String())+ }+}++func TestIssueCreationWindowObserveDoesNotFilter(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Observed issue window", "observed-window-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ oldID := dbfx.Issue(t, "observed old", testutil.Cols{"workspace_id": workspaceID, "number": 1})+ _ = dbfx.Issue(t, "observed new", testutil.Cols{"workspace_id": workspaceID, "number": 2})++ h := *testHandler+ h.Entitlements = issueWindowProvider(entitlement.ActionObserve, 1)+ req := httptest.NewRequest(http.MethodGet, "/api/issues/"+oldID, nil)+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ recorder := httptest.NewRecorder()+ if _, ok := h.loadIssueForUser(recorder, req, oldID); !ok {+ t.Fatalf("observe changed direct response: %d %s", recorder.Code, recorder.Body.String())+ }+ listRecorder := httptest.NewRecorder()+ listReq := req.Clone(req.Context())+ listReq.URL.Path = "/api/issues"+ h.ListIssues(listRecorder, listReq)+ if listRecorder.Code != http.StatusOK {+ t.Fatalf("observe list status = %d: %s", listRecorder.Code, listRecorder.Body.String())+ }+ var body struct {+ Issues []IssueResponse `json:"issues"`+ Total int64 `json:"total"`+ }+ if err := json.NewDecoder(listRecorder.Body).Decode(&body); err != nil {+ t.Fatalf("decode observe list: %v", err)+ }+ if len(body.Issues) != 2 || body.Total != 2 {+ t.Fatalf("observe filtered the list: %#v", body)+ }+}++func TestIssueCreationWindowPreservesUnreadInboxSemantics(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Inbox issue window", "inbox-window-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ hiddenIssueID := dbfx.Issue(t, "hidden inbox issue", testutil.Cols{"workspace_id": workspaceID, "number": 1})+ visibleIssueID := dbfx.Issue(t, "visible inbox issue", testutil.Cols{"workspace_id": workspaceID, "number": 2})++ insertInbox := func(title, issueID string, read bool, createdAt string) {+ t.Helper()+ dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": workspaceID,+ "recipient_type": "member",+ "recipient_id": testUserID,+ "type": "issue_assigned",+ "severity": "info",+ "issue_id": issueID,+ "title": title,+ "read": read,+ "archived": false,+ "created_at": testutil.Raw(createdAt),+ })+ }+ // The visible issue's newest row is read, so its older unread sibling must+ // not light the cross-workspace summary (MUL-3695).+ insertInbox("visible older unread", visibleIssueID, false, "now() - interval '2 minutes'")+ insertInbox("visible newest read", visibleIssueID, true, "now() - interval '1 minute'")+ insertInbox("hidden newest unread", hiddenIssueID, false, "now()")++ request := func(path string) *http.Request {+ req := httptest.NewRequest(http.MethodGet, path, nil)+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ return req+ }+ assertCounts := func(t *testing.T, action entitlement.Action, wantWorkspaceCount, wantSummaryCount int64) {+ t.Helper()+ h := *testHandler+ h.Entitlements = issueWindowProvider(action, 1)++ countRecorder := httptest.NewRecorder()+ middleware.RequireWorkspaceMember(h.Queries)(http.HandlerFunc(h.CountUnreadInbox)).ServeHTTP(+ countRecorder,+ request("/api/inbox/unread-count"),+ )+ if countRecorder.Code != http.StatusOK {+ t.Fatalf("unread count status = %d: %s", countRecorder.Code, countRecorder.Body.String())+ }+ var countBody map[string]int64+ if err := json.NewDecoder(countRecorder.Body).Decode(&countBody); err != nil {+ t.Fatalf("decode unread count: %v", err)+ }+ if countBody["count"] != wantWorkspaceCount {+ t.Fatalf("unread count = %d, want %d", countBody["count"], wantWorkspaceCount)+ }++ summaryRecorder := httptest.NewRecorder()+ h.UnreadInboxSummary(summaryRecorder, request("/api/inbox/unread-summary"))+ if summaryRecorder.Code != http.StatusOK {+ t.Fatalf("unread summary status = %d: %s", summaryRecorder.Code, summaryRecorder.Body.String())+ }+ var summary []InboxWorkspaceUnreadResponse+ if err := json.NewDecoder(summaryRecorder.Body).Decode(&summary); err != nil {+ t.Fatalf("decode unread summary: %v", err)+ }+ var got int64+ for _, row := range summary {+ if row.WorkspaceID == workspaceID {+ got = row.Count+ }+ }+ if got != wantSummaryCount {+ t.Fatalf("unread summary = %d, want %d: %#v", got, wantSummaryCount, summary)+ }+ }++ t.Run("observe leaves both legacy responses unchanged", func(t *testing.T) {+ assertCounts(t, entitlement.ActionObserve, 2, 1)+ })+ t.Run("enforce filters hidden issues without reviving older siblings", func(t *testing.T) {+ assertCounts(t, entitlement.ActionEnforce, 1, 0)+ })+}++func TestIssueCreationWindowChildProgressKeepsFullTotals(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Progress issue window", "progress-window-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ parentID := dbfx.Issue(t, "progress parent", testutil.Cols{"workspace_id": workspaceID, "number": 100})+ _ = dbfx.Issue(t, "hidden done child", testutil.Cols{+ "workspace_id": workspaceID, "number": 1, "parent_issue_id": parentID, "status": "done",+ })+ _ = dbfx.Issue(t, "hidden open child", testutil.Cols{+ "workspace_id": workspaceID, "number": 2, "parent_issue_id": parentID, "status": "todo",+ })+ _ = dbfx.Issue(t, "unrelated recent issue", testutil.Cols{"workspace_id": workspaceID, "number": 200})+ _ = dbfx.Issue(t, "visible open child", testutil.Cols{+ "workspace_id": workspaceID, "number": 300, "parent_issue_id": parentID, "status": "todo",+ })++ h := *testHandler+ h.Entitlements = issueWindowProvider(entitlement.ActionEnforce, 2)+ req := httptest.NewRequest(http.MethodGet, "/api/issues/child-progress", nil)+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ recorder := httptest.NewRecorder()+ h.ChildIssueProgress(recorder, req)+ if recorder.Code != http.StatusOK {+ t.Fatalf("child progress status = %d: %s", recorder.Code, recorder.Body.String())+ }+ var body struct {+ Progress []struct {+ ParentIssueID string `json:"parent_issue_id"`+ Total int64 `json:"total"`+ Done int64 `json:"done"`+ VisibleTotal int64 `json:"visible_total"`+ VisibleDone int64 `json:"visible_done"`+ HiddenTotal int64 `json:"hidden_total"`+ } `json:"progress"`+ }+ if err := json.NewDecoder(recorder.Body).Decode(&body); err != nil {+ t.Fatalf("decode child progress: %v", err)+ }+ for _, progress := range body.Progress {+ if progress.ParentIssueID != parentID {+ continue+ }+ if progress.Total != 3 || progress.Done != 1 || progress.VisibleTotal != 1 || progress.VisibleDone != 0 || progress.HiddenTotal != 2 {+ t.Fatalf("child progress = %#v, want full 1/3 and visible 0/1 with 2 hidden", progress)+ }+ return+ }+ t.Fatalf("visible parent missing from child progress: %#v", body.Progress)+}diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex 120cd8c126..919cc0ed46 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -199,6 +199,9 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, calwriteError(w, http.StatusNotFound, "issue not found")return db.Issue{}, false}+ if !h.authorizeIssueWindow(w, r, issue.ID, issue.WorkspaceID, "plugin") {+ return db.Issue{}, false+ }return issue, true}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex a3947d2736..5967f19209 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -6,7 +6,7 @@ import ()func TestBuildSearchQuery_SingleTerm(t *testing.T) {- query, args := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false)+ query, args := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, nil)// Pattern should be lowercased in Go.if args[0] != "hello" {@@ -42,7 +42,7 @@ func TestBuildSearchQuery_SingleTerm(t *testing.T) {}func TestBuildSearchQuery_MultiTerm(t *testing.T) {- query, args := buildSearchQuery("Foo Bar", []string{"Foo", "Bar"}, 0, false, false)+ query, args := buildSearchQuery("Foo Bar", []string{"Foo", "Bar"}, 0, false, false, nil)// Both phrase and terms should be lowercased.if args[0] != "foo bar" {@@ -63,7 +63,7 @@ func TestBuildSearchQuery_MultiTerm(t *testing.T) {}func TestBuildSearchQuery_WithNumber(t *testing.T) {- query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false)+ query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false, nil)_ = args// Number match should be in WHERE.@@ -77,7 +77,7 @@ func TestBuildSearchQuery_WithNumber(t *testing.T) {}func TestBuildSearchQuery_IncludeClosed(t *testing.T) {- query, _ := buildSearchQuery("test", []string{"test"}, 0, false, true)+ query, _ := buildSearchQuery("test", []string{"test"}, 0, false, true, nil)if strings.Contains(query, "NOT IN ('done', 'cancelled')") {t.Error("query should not exclude done/cancelled when includeClosed=true")@@ -85,7 +85,7 @@ func TestBuildSearchQuery_IncludeClosed(t *testing.T) {}func TestBuildSearchQuery_SpecialChars(t *testing.T) {- query, args := buildSearchQuery("100%", []string{"100%"}, 0, false, false)+ query, args := buildSearchQuery("100%", []string{"100%"}, 0, false, false, nil)_ = query// % should be escaped in the phrase arg.@@ -204,7 +204,7 @@ func TestExtractSnippet_CJKContent(t *testing.T) {// --- Ranking regression tests ---func TestBuildSearchQuery_CommentRankTiers(t *testing.T) {- query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false)+ query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false, nil)// Comment phrase match should be tier 7if !strings.Contains(query, "THEN 7") {@@ -221,7 +221,7 @@ func TestBuildSearchQuery_CommentRankTiers(t *testing.T) {}func TestBuildSearchQuery_DescriptionRankTiers(t *testing.T) {- query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, nil)// Description phrase match should be tier 5if !strings.Contains(query, "THEN 5") {@@ -234,7 +234,7 @@ func TestBuildSearchQuery_DescriptionRankTiers(t *testing.T) {}func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {- query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)+ query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, nil)// Extract the rank CASE expression (ends with "ELSE 9 END") to avoid// false matches against statusRank which also contains THEN 4/6.@@ -268,7 +268,7 @@ func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {// $4 is buildSearchQuery's canonical workspace_id placeholder (the// caller writes wsUUID into args[3] before executing).func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {- singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)+ singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, nil)// Every occurrence of `FROM comment c` must be followed by the// c.workspace_id = $4 constraint. Counting is safer than a single@@ -286,7 +286,7 @@ func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {// Multi-term uses one extra comment subquery in the WHERE and one in// the rank CASE for the all-terms match — same invariant applies.- multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)+ multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, nil)fromCountMulti := strings.Count(multiQuery, "FROM comment c")scopedCountMulti := strings.Count(multiQuery, "c.workspace_id = $4")if scopedCountMulti < fromCountMulti {@@ -398,6 +398,6 @@ func TestBuildProjectSearchQuery_CancelledDemotedAheadOfRelevance(t *testing.T)// keeps each test's literals independent.func buildSearchQueryForTest(t *testing.T, phrase string, terms []string, num int, hasNum bool, includeClosed bool) string {t.Helper()- query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed)+ query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed, nil)return query}diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 6a60d01a2d..f1bd129058 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -49,6 +49,7 @@ type BusinessMetrics struct {entitlementDecision *prometheus.CounterVecentitlementVersionRegression *prometheus.CounterVecautopilotQuotaDecision *prometheus.CounterVec+ issueWindowDecision *prometheus.CounterVecactiveMu sync.MutexactiveTasks map[string]activeTaskLabels@@ -232,6 +233,10 @@ func NewBusinessMetrics() *BusinessMetrics {Namespace: "multica", Subsystem: "autopilot_quota", Name: "decision_total",Help: "Total autopilot quota admission outcomes.",}, metricLabels("multica_autopilot_quota_decision_total")),+ issueWindowDecision: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "issue_window", Name: "decision_total",+ Help: "Total recently-created issue window outcomes by request surface.",+ }, metricLabels("multica_issue_window_decision_total")),activeTasks: map[string]activeTaskLabels{},events: newBusinessEventMetrics(),}@@ -271,6 +276,7 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.entitlementDecision,m.entitlementVersionRegression,m.autopilotQuotaDecision,+ m.issueWindowDecision,}, m.events.collectors()...)}@@ -318,6 +324,18 @@ func (m *BusinessMetrics) RecordAutopilotQuotaDecision(action, source, result stm.autopilotQuotaDecision.WithLabelValues(action, source, result).Inc()}+func (m *BusinessMetrics) RecordIssueWindowDecision(action, surface, result string) {+ if m == nil {+ return+ }+ switch surface {+ case "direct", "list", "search", "grouped", "table", "children", "plugin", "inbox", "agent_context":+ default:+ surface = "other"+ }+ m.issueWindowDecision.WithLabelValues(action, surface, result).Inc()+}+func (m *BusinessMetrics) RecordRuntimeGCDeleted() {if m == nil {returndiff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 14159fd3a9..fbee51e48e 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -182,6 +182,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")m.RecordEntitlementVersionRegression("refresh")m.RecordAutopilotQuotaDecision("observe", "manual", "admitted")+ m.RecordIssueWindowDecision("observe", "list", "would_block")families, err := registry.Gather()if err != nil {diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 83e398cf10..e4dcf70000 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -34,6 +34,7 @@ const (labelOp = "op"labelGate = "gate"labelOutcome = "outcome"+ labelSurface = "surface")var businessMetricLabels = map[string][]string{@@ -98,6 +99,7 @@ var businessMetricLabels = map[string][]string{"multica_entitlement_decision_total": {labelGate, labelAction, labelReason},"multica_entitlement_version_regression_total": {labelSource},"multica_autopilot_quota_decision_total": {labelAction, labelSource, labelResult},+ "multica_issue_window_decision_total": {labelAction, labelSurface, labelResult},}var forbiddenMetricLabels = map[string]struct{}{diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex e24acc71c6..f006dc7342 100644--- a/server/pkg/taskfailure/failure.go+++ b/server/pkg/taskfailure/failure.go@@ -26,7 +26,7 @@// queued_expired, runtime_offline, runtime_reconnect_timeout,// runtime_recovery, timeout, iteration_limit, agent_blocked,// api_invalid_request, skill_bundle_unavailable,-// runtime_cli_timeout, invalid_task_identity+// runtime_cli_timeout, invalid_task_identity, issue_window_restricted//// - 14 agent-side values (with `agent_error.` prefix) produced by// Classify(rawError) when the agent process surfaced an error string.@@ -138,6 +138,12 @@ const (// only repeat an isolation failure.ReasonInvalidTaskIdentity Reason = "invalid_task_identity"+ // ReasonIssueWindowRestricted: an entitlement change made the task's issue+ // unavailable before a daemon claimed it. The agent process is never+ // launched and retrying the same issue remains non-actionable until the+ // workspace policy changes.+ ReasonIssueWindowRestricted Reason = "issue_window_restricted"+// Agent process side: failure surfaced by the agent CLI / SDK as// an error string. Classify(rawError) is responsible for picking// the right sub-reason from the string. IsAgentError returns true@@ -213,7 +219,7 @@ const (ReasonAgentUnknown Reason = "agent_error.unknown")-// allReasons is the canonical ordered list of the 25 reasons. Order is+// allReasons is the canonical ordered list of the 26 reasons. Order is// stable so callers (e.g. Prometheus collectors that pre-warm series via// AllReasons) can build deterministic label sets across restarts.//@@ -235,6 +241,7 @@ var allReasons = []Reason{ReasonSkillBundleUnavailable,ReasonRuntimeCLITimeout,ReasonInvalidTaskIdentity,+ ReasonIssueWindowRestricted,// Agent process side: provider errors.ReasonAgentProviderAuthOrAccess,diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.goindex 2a5f0eed0c..2d4a8720a3 100644--- a/server/pkg/taskfailure/failure_test.go+++ b/server/pkg/taskfailure/failure_test.go@@ -30,6 +30,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonSkillBundleUnavailable, "skill_bundle_unavailable"},{ReasonRuntimeCLITimeout, "runtime_cli_timeout"},{ReasonInvalidTaskIdentity, "invalid_task_identity"},+ {ReasonIssueWindowRestricted, "issue_window_restricted"},// Agent-side.{ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},{ReasonAgentProviderQuotaLimit, "agent_error.provider_quota_limit"},@@ -47,7 +48,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonAgentUnknown, "agent_error.unknown"},}- if got, want := len(cases), 25; got != want {+ if got, want := len(cases), 26; got != want {t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)}@@ -78,6 +79,7 @@ func TestIsAgentError(t *testing.T) {ReasonSkillBundleUnavailable,ReasonRuntimeCLITimeout,ReasonInvalidTaskIdentity,+ ReasonIssueWindowRestricted,}for _, r := range platformSide {if r.IsAgentError() {@@ -118,8 +120,8 @@ func TestAllReasonsContents(t *testing.T) {t.Parallel()got := AllReasons()- if len(got) != 25 {- t.Fatalf("AllReasons() returned %d entries, want 25", len(got))+ if len(got) != 26 {+ t.Fatalf("AllReasons() returned %d entries, want 26", len(got))}seen := make(map[Reason]bool, len(got))@@ -136,8 +138,8 @@ func TestAllReasonsContents(t *testing.T) {}}- if platformCount != 11 {- t.Errorf("AllReasons(): platform-side count = %d, want 11", platformCount)+ if platformCount != 12 {+ t.Errorf("AllReasons(): platform-side count = %d, want 12", platformCount)}if agentCount != 14 {t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)@@ -152,7 +154,7 @@ func TestAllReasonsContents(t *testing.T) {ReasonRuntimeRecovery,ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,- ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity,+ ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity, ReasonIssueWindowRestricted,ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,ReasonAgentProviderNetwork, ReasonAgentProcessFailure,