Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(billing): enforce Cloud issue count limits (#7619)
LinYushen5fa65bd12585
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 62b78d319c..f8fda8625f 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -206,8 +206,8 @@ import type {CreateBillingCheckoutSessionResponse,BillingCheckoutSessionStatus,CreateBillingPortalSessionResponse,- WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,+ IssueLimitUsage,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,@@ -333,8 +333,8 @@ import {CreateBillingCheckoutSessionResponseSchema,BillingCheckoutSessionStatusSchema,CreateBillingPortalSessionResponseSchema,- WorkspaceSubscriptionEntitlementsSchema,WorkspaceSubscriptionSummarySchema,+ IssueLimitUsageSchema,WorkspaceSubscriptionPricesSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,@@ -1232,19 +1232,26 @@ export class ApiClient {}async getChildIssueProgress(): Promise<{- progress: {- parent_issue_id: string;- total: number;- done: number;- visible_total?: number;- visible_done?: number;- hidden_total?: number;- }[];+ progress: { parent_issue_id: string; total: number; done: number }[];}> {const raw = await this.fetch<unknown>("/api/issues/child-progress");- return parseWithFallback(raw, ChildIssueProgressResponseSchema, { progress: [] }, {- endpoint: "GET /api/issues/child-progress",- });+ return parseWithFallback(+ raw,+ ChildIssueProgressResponseSchema,+ { progress: [] },+ { endpoint: "GET /api/issues/child-progress" },+ );+ }++ async getIssueLimitUsage(): Promise<IssueLimitUsage | null> {+ const raw = await this.fetch<unknown>("/api/issues/limit-usage");+ if (raw == null) return null;+ return parseWithFallback<IssueLimitUsage | null>(+ raw,+ IssueLimitUsageSchema,+ null,+ { endpoint: "GET /api/issues/limit-usage" },+ );}async deleteIssue(id: string): Promise<void> {@@ -1821,18 +1828,6 @@ export class ApiClient {// - a 2xx body that does not match the contract returns null here.// ---------------------------------------------------------------------- async getWorkspaceSubscriptionEntitlements(): Promise<WorkspaceSubscriptionEntitlements | null> {- const raw = await this.fetch<unknown>(- "/api/cloud-subscriptions/entitlements",- );- return parseWithFallback<WorkspaceSubscriptionEntitlements | null>(- raw,- WorkspaceSubscriptionEntitlementsSchema,- null,- { endpoint: "GET /api/cloud-subscriptions/entitlements" },- );- }-async getWorkspaceSubscriptionSummary(): Promise<WorkspaceSubscriptionSummary | null> {const raw = await this.fetch<unknown>("/api/cloud-subscriptions/summary");return parseWithFallback<WorkspaceSubscriptionSummary | null>(@@ -4161,7 +4156,9 @@ export class ApiClient {action: "off",used: null,reserved: null,+ total: null,limit: null,+ reached: null,period_start: null,period_end: null,reset_at: null,diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 62b2b7d4b0..6afc43b363 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -712,6 +712,17 @@ describe("ApiClient schema fallback", () => {});});+ describe("getChildIssueProgress", () => {+ it("validates the response before query selectors iterate it", async () => {+ stubFetchJson({ progress: "invalid" });+ const client = new ApiClient("https://api.example.test");++ await expect(client.getChildIssueProgress()).resolves.toEqual({+ progress: [],+ });+ });+ });+describe("listAutopilotDeliveries", () => {it("falls back to an empty list when the body is null", async () => {stubFetchJson(null);@@ -947,56 +958,6 @@ describe("ApiClient schema fallback", () => {});});- it("parses workspace entitlements into camelCase without fabricating Free", async () => {- stubFetchJson({- workspace_id: "workspace-1",- plan: "pro",- status: "active",- seats: 4,- issue_window: null,- autopilot_runs: null,- current_period_end: "2026-09-13T00:00:00Z",- snapshot_expires_at: null,- version: 7,- });- const client = new ApiClient("https://api.example.test");-- await expect(- client.getWorkspaceSubscriptionEntitlements(),- ).resolves.toEqual({- workspaceId: "workspace-1",- plan: "pro",- status: "active",- seats: 4,- issueWindow: null,- autopilotRuns: null,- currentPeriodEnd: "2026-09-13T00:00:00Z",- snapshotExpiresAt: null,- version: 7,- });-- stubFetchJson({ plan: "free", seats: "unknown" });- await expect(client.getWorkspaceSubscriptionEntitlements()).resolves.toBeNull();- });-- it("accepts an empty workspace entitlement snapshot", async () => {- stubFetchJson({- workspace_id: "workspace-1",- plan: "free",- status: "inactive",- seats: 0,- issue_window: 1000,- autopilot_runs: 100,- snapshot_expires_at: null,- version: 0,- });- const client = new ApiClient("https://api.example.test");-- await expect(- client.getWorkspaceSubscriptionEntitlements(),- ).resolves.toMatchObject({ seats: 0, plan: "free" });- });-it("sends the Checkout idempotency key in the header and body", async () => {stubFetchJson({@@ -1109,13 +1070,37 @@ describe("workspace subscription contract", () => {plan: "pro",status: "active",seats: 3,- issue_window: null,- autopilot_runs: null,+ limits: {+ issue_count: { mode: "unlimited" },+ autopilot_runs: { mode: "unlimited" },+ },current_period_end: "2026-09-01T00:00:00Z",snapshot_expires_at: null,version: 7,};+ it("maps limited issue usage and accepts a no-content unlimited response", async () => {+ stubFetchJson({+ used: 11,+ limit: 17,+ });+ const client = new ApiClient("https://api.example.test");++ await expect(client.getIssueLimitUsage()).resolves.toEqual({+ used: 11,+ limit: 17,+ });++ stubFetchJson({ used: 11 });+ await expect(client.getIssueLimitUsage()).resolves.toBeNull();++ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(new Response(null, { status: 204 })),+ );+ await expect(client.getIssueLimitUsage()).resolves.toBeNull();+ });+it("maps a full summary to camelCase without inventing values", async () => {stubFetchJson({entitlement,@@ -1126,6 +1111,7 @@ describe("workspace subscription contract", () => {used: 3,reserved: 2,available: 0,+ overcommitted: false,version: 11,pending_quantity: 3,active_purchase: {@@ -1137,6 +1123,11 @@ describe("workspace subscription contract", () => {cancel_at_period_end: true,grace_until: "2026-09-08T00:00:00Z",has_stripe_customer: true,+ available_actions: {+ checkout: false,+ portal: true,+ purchase_seats: false,+ },});const client = new ApiClient("https://api.example.test");const summary = await client.getWorkspaceSubscriptionSummary();@@ -1161,6 +1152,11 @@ describe("workspace subscription contract", () => {expect(summary?.cancelAtPeriodEnd).toBe(true);expect(summary?.graceUntil).toBe("2026-09-08T00:00:00Z");expect(summary?.hasStripeCustomer).toBe(true);+ expect(summary?.availableActions).toEqual({+ checkout: false,+ portal: true,+ purchaseSeats: false,+ });});it("represents canceled subscriptions without current seat capacity", async () => {@@ -1172,6 +1168,11 @@ describe("workspace subscription contract", () => {cancel_at_period_end: false,grace_until: null,has_stripe_customer: true,+ available_actions: {+ checkout: true,+ portal: true,+ purchase_seats: false,+ },});const client = new ApiClient("https://api.example.test");const summary = await client.getWorkspaceSubscriptionSummary();@@ -1192,6 +1193,11 @@ describe("workspace subscription contract", () => {cancel_at_period_end: false,grace_until: null,has_stripe_customer: false,+ available_actions: {+ checkout: false,+ portal: false,+ purchase_seats: false,+ },});const client = new ApiClient("https://api.example.test");const summary = await client.getWorkspaceSubscriptionSummary();@@ -1235,6 +1241,11 @@ describe("workspace subscription contract", () => {cancel_at_period_end: false,grace_until: null,has_stripe_customer: true,+ available_actions: {+ checkout: false,+ portal: true,+ purchase_seats: false,+ },future_field: { nested: true },});const client = new ApiClient("https://api.example.test");diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex d04b062df4..779f04b926 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import {AppConfigSchema,- ChildIssueProgressResponseSchema,WecomInstallationSchema,ListWecomInstallationsResponseSchema,RedeemWecomBindingTokenResponseSchema,@@ -99,40 +98,6 @@ 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("ChatSessionSchema", () => {const baseSession = {id: "chat-1",@@ -201,7 +166,6 @@ describe("ChatSessionSchema", () => {expect(parsed[1]?.last_message?.message_kind).toBe("onboarding_opening");});});-describe("IssueSchema (via ListIssuesResponseSchema)", () => {it("keeps the issue while independently dropping a malformed source context", () => {const parsed = ListIssuesResponseSchema.parse({diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex ac720a1530..99fbcbebc5 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -24,6 +24,7 @@ import type {CreateBillingPortalSessionResponse,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,+ IssueLimitUsage,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutResponse,@@ -1460,14 +1461,17 @@ export const ChildIssuesResponseSchema = z.object({}).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([]),+ progress: z+ .array(+ z+ .object({+ parent_issue_id: z.string(),+ total: z.number(),+ done: z.number(),+ })+ .loose(),+ )+ .default([]),}).loose();export const CloudRuntimeNodeSchema = z.object({@@ -2256,7 +2260,9 @@ export const AutopilotQuotaUsageSchema = z.object({action: z.enum(["off", "observe", "enforce"]).default("off"),used: z.number().nullable().default(null),reserved: z.number().nullable().default(null),+ total: z.number().nullable().default(null),limit: z.number().nullable().default(null),+ reached: z.boolean().nullable().default(null),period_start: z.string().nullable().default(null),period_end: z.string().nullable().default(null),reset_at: z.string().nullable().default(null),@@ -2607,6 +2613,22 @@ const StripeHostedURLSchema = z.string().url().refine({ message: "Stripe hosted URL must use HTTPS" },);+const WorkspaceEntitlementLimitSchema = z+ .discriminatedUnion("mode", [+ z+ .object({+ mode: z.literal("limited"),+ limit: z.number().int().positive(),+ })+ .loose(),+ z.object({ mode: z.literal("unlimited") }).loose(),+ ])+ .transform(+ (value): WorkspaceSubscriptionEntitlements["limits"]["issueCount"] =>+ value.mode === "limited"+ ? { mode: "limited", limit: value.limit }+ : { mode: "unlimited", limit: null },+ );export const WorkspaceSubscriptionEntitlementsSchema = z.object({@@ -2617,8 +2639,12 @@ export const WorkspaceSubscriptionEntitlementsSchema = z// workspace that momentarily reports no human members readable instead of// failing the whole snapshot.seats: z.number().int().nonnegative(),- issue_window: z.number().int().nonnegative().nullable(),- autopilot_runs: z.number().int().nonnegative().nullable(),+ limits: z+ .object({+ issue_count: WorkspaceEntitlementLimitSchema,+ autopilot_runs: WorkspaceEntitlementLimitSchema,+ })+ .loose(),current_period_end: z.string().nullable().optional(),snapshot_expires_at: z.string().nullable().optional(),version: z.number().int().nonnegative(),@@ -2630,8 +2656,10 @@ export const WorkspaceSubscriptionEntitlementsSchema = zplan: value.plan,status: value.status,seats: value.seats,- issueWindow: value.issue_window,- autopilotRuns: value.autopilot_runs,+ limits: {+ issueCount: value.limits.issue_count,+ autopilotRuns: value.limits.autopilot_runs,+ },currentPeriodEnd: value.current_period_end ?? null,snapshotExpiresAt: value.snapshot_expires_at ?? null,version: value.version,@@ -2649,6 +2677,7 @@ export const WorkspaceSubscriptionSummarySchema = zused: z.number().int().nonnegative(),reserved: z.number().int().nonnegative(),available: z.number().int().nonnegative(),+ overcommitted: z.boolean(),version: z.number().int().positive(),pending_quantity: z.number().int().positive().nullable(),active_purchase: z@@ -2666,6 +2695,11 @@ export const WorkspaceSubscriptionSummarySchema = zcancel_at_period_end: z.boolean(),grace_until: z.string().nullable(),has_stripe_customer: z.boolean(),+ available_actions: z.object({+ checkout: z.boolean(),+ portal: z.boolean(),+ purchase_seats: z.boolean(),+ }).loose(),}).loose().transform(@@ -2679,6 +2713,7 @@ export const WorkspaceSubscriptionSummarySchema = zused: value.seat_capacity.used,reserved: value.seat_capacity.reserved,available: value.seat_capacity.available,+ overcommitted: value.seat_capacity.overcommitted,version: value.seat_capacity.version,pendingQuantity: value.seat_capacity.pending_quantity,activePurchase: value.seat_capacity.active_purchase@@ -2697,6 +2732,24 @@ export const WorkspaceSubscriptionSummarySchema = zcancelAtPeriodEnd: value.cancel_at_period_end,graceUntil: value.grace_until,hasStripeCustomer: value.has_stripe_customer,+ availableActions: {+ checkout: value.available_actions.checkout,+ portal: value.available_actions.portal,+ purchaseSeats: value.available_actions.purchase_seats,+ },+ }),+ );++export const IssueLimitUsageSchema = z+ .object({+ used: z.number().int().nonnegative(),+ limit: z.number().int().positive(),+ })+ .loose()+ .transform(+ (value): IssueLimitUsage => ({+ used: value.used,+ limit: value.limit,}),);diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.tsindex ef88b6f656..7f693965d1 100644--- a/packages/core/billing/workspace-subscription-mutations.ts+++ b/packages/core/billing/workspace-subscription-mutations.ts@@ -14,7 +14,7 @@ export function useCreateWorkspaceSubscriptionCheckout(wsId: string) {api.createWorkspaceSubscriptionCheckout(data),onSuccess: () => {void queryClient.invalidateQueries({- queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ queryKey: workspaceSubscriptionKeys.summary(wsId),});},});@@ -26,7 +26,7 @@ export function useReconcileWorkspaceSubscriptionSeats(wsId: string) {mutationFn: () => api.reconcileWorkspaceSubscriptionSeats(),onSuccess: () => {void queryClient.invalidateQueries({- queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ queryKey: workspaceSubscriptionKeys.summary(wsId),});},});@@ -45,9 +45,6 @@ export function usePurchaseWorkspaceSeats(wsId: string) {mutationFn: (data: PurchaseWorkspaceSeatsRequest) =>api.purchaseWorkspaceSeats(data),onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: workspaceSubscriptionKeys.entitlements(wsId),- });void queryClient.invalidateQueries({queryKey: workspaceSubscriptionKeys.summary(wsId),});@@ -62,7 +59,7 @@ export function useCreateWorkspaceSubscriptionPortal(wsId: string) {api.createWorkspaceSubscriptionPortal(idempotencyKey),onSuccess: () => {void queryClient.invalidateQueries({- queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ queryKey: workspaceSubscriptionKeys.summary(wsId),});},});diff --git a/packages/core/billing/workspace-subscription-queries.ts b/packages/core/billing/workspace-subscription-queries.tsindex 4a8627af25..15e4a8d4f1 100644--- a/packages/core/billing/workspace-subscription-queries.ts+++ b/packages/core/billing/workspace-subscription-queries.ts@@ -15,24 +15,14 @@ const WORKSPACE_SUBSCRIPTION_PRICES_STALE_TIME_MS = 10 * 60 * 1000;*/export const workspaceSubscriptionKeys = {all: (wsId: string) => ["workspace-subscriptions", wsId] as const,- entitlements: (wsId: string) =>- [...workspaceSubscriptionKeys.all(wsId), "entitlements"] as const,summary: (wsId: string) =>[...workspaceSubscriptionKeys.all(wsId), "summary"] as const,prices: (wsId: string) =>[...workspaceSubscriptionKeys.all(wsId), "prices"] as const,+ issueLimitUsage: (wsId: string) =>+ [...workspaceSubscriptionKeys.all(wsId), "issue-limit-usage"] as const,};-export function workspaceSubscriptionEntitlementsOptions(wsId: string) {- return queryOptions({- queryKey: workspaceSubscriptionKeys.entitlements(wsId),- queryFn: () => api.getWorkspaceSubscriptionEntitlements(),- enabled: wsId.length > 0,- staleTime: 60 * 1000,- refetchOnWindowFocus: true,- });-}-/*** The Billing page's primary read. Short stale time plus refetch on focus: a* user returning from Stripe in another tab or the system browser should see the@@ -49,6 +39,16 @@ export function workspaceSubscriptionSummaryOptions(wsId: string) {});}+export function issueLimitUsageOptions(wsId: string) {+ return queryOptions({+ queryKey: workspaceSubscriptionKeys.issueLimitUsage(wsId),+ queryFn: () => api.getIssueLimitUsage(),+ enabled: wsId.length > 0,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}+/*** A validated price snapshot is stable deployment configuration, but a null* parse fallback is not a snapshot. Keeping null fresh made one transientdiff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex c41ba01354..3d3d35a295 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -475,21 +475,9 @@ export function childIssueProgressOptions(wsId: string) {queryKey: issueKeys.childProgress(wsId),queryFn: () => api.getChildIssueProgress(),select: (data) => {- const map = new Map<string, {- done: number;- total: number;- visibleDone: number;- visibleTotal: number;- hiddenTotal: number;- }>();+ const map = new Map<string, { done: number; total: number }>();for (const entry of data.progress) {- 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,- });+ map.set(entry.parent_issue_id, { done: entry.done, total: entry.total });}return map;},diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 75b6b6560e..8ef32f9102 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -139,7 +139,9 @@ export interface AutopilotQuotaUsage {action: "off" | "observe" | "enforce";used: number | null;reserved: number | null;+ total: number | null;limit: number | null;+ reached: boolean | null;period_start: string | null;period_end: string | null;reset_at: string | null;diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex a3c942d4c3..7415d462e4 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -195,6 +195,13 @@ export interface CreateBillingPortalSessionResponse {export type WorkspaceSubscriptionInterval = "month" | "year";+export type WorkspaceEntitlementLimit =+ | { mode: "limited"; limit: number }+ | { mode: "unlimited"; limit: null };++export type WorkspaceEntitlementLimitMode =+ WorkspaceEntitlementLimit["mode"];+export interface WorkspaceSubscriptionEntitlements {workspaceId: string;// Deliberately open strings: cloud may add plans and Stripe statuses without@@ -202,8 +209,10 @@ export interface WorkspaceSubscriptionEntitlements {plan: string;status: string;seats: number;- issueWindow: number | null;- autopilotRuns: number | null;+ limits: {+ issueCount: WorkspaceEntitlementLimit;+ autopilotRuns: WorkspaceEntitlementLimit;+ };currentPeriodEnd: string | null;snapshotExpiresAt: string | null;version: number;@@ -223,12 +232,19 @@ export interface WorkspaceSubscriptionSummary {seatCapacity: WorkspaceSeatCapacity | null;cancelAtPeriodEnd: boolean;graceUntil: string | null;- /**- * Whether a local Stripe customer exists for this workspace. It is a fact,- * NOT a permission: Billing Portal still requires owner/admin, so a caller- * must gate that control on the member's role as well.- */+ /** Whether a local Stripe customer exists; never use this as an action gate. */hasStripeCustomer: boolean;+ /** Cloud-authorized actions for this exact caller and effective snapshot. */+ availableActions: {+ checkout: boolean;+ portal: boolean;+ purchaseSeats: boolean;+ };+}++export interface IssueLimitUsage {+ used: number;+ limit: number;}export interface WorkspaceSeatCapacity {@@ -237,6 +253,8 @@ export interface WorkspaceSeatCapacity {reserved: number;/** Server-computed purchased capacity not currently used or reserved. */available: number;+ /** Cloud-computed human-seat overcommit state. */+ overcommitted: boolean;version: number;/** A lower quantity already scheduled for the next period, if any. */pendingQuantity: number | null;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 69da919ca4..93948eeea1 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -311,8 +311,11 @@ export type {BillingCheckoutSessionStatus,CreateBillingPortalSessionResponse,WorkspaceSubscriptionInterval,+ WorkspaceEntitlementLimitMode,+ WorkspaceEntitlementLimit,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,+ IssueLimitUsage,WorkspaceSeatCapacity,WorkspaceSeatPurchaseSummary,WorkspaceSubscriptionPrice,diff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.tsindex 416c296424..8e5a960632 100644--- a/packages/views/agents/components/tabs/task-failure.test.ts+++ b/packages/views/agents/components/tabs/task-failure.test.ts@@ -111,9 +111,6 @@ describe("failureReasonLabel", () => {expect(failureReasonLabel("invalid_task_identity", enT)).toBe("Task identity mismatch",);- expect(failureReasonLabel("issue_window_restricted", enT)).toBe(- "Issue unavailable under workspace limits",- );});it("covers operational reasons emitted outside the canonical taxonomy", () => {diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex 6f7a61225e..dac7daee5b 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -19,7 +19,6 @@ export const FAILURE_REASON_I18N_KEYS = {skill_bundle_unavailable: "skill_bundle_unavailable",runtime_cli_timeout: "runtime_cli_timeout",invalid_task_identity: "invalid_task_identity",- issue_window_restricted: "issue_window_restricted",// Agent process side — provider."agent_error.provider_auth_or_access":diff --git a/packages/views/autopilots/components/run-now-toast.test.ts b/packages/views/autopilots/components/run-now-toast.test.tsindex c0aa588b9f..d99b50f742 100644--- a/packages/views/autopilots/components/run-now-toast.test.ts+++ b/packages/views/autopilots/components/run-now-toast.test.ts@@ -35,6 +35,9 @@ describe("runNowBlockedKey", () => {expect(runNowBlockedKey("attribution_blocked")).toBe("run_blocked_attribution");expect(runNowBlockedKey("already_active")).toBe("run_blocked_already_active");expect(runNowBlockedKey("quota_exceeded")).toBe("run_blocked_quota_exceeded");+ expect(runNowBlockedKey("issue_limit_reached")).toBe(+ "run_blocked_issue_limit_reached",+ );});it("degrades an unknown or absent code to the generic message", () => {diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.tsindex 2dd7bc95aa..535b8791ef 100644--- a/packages/views/autopilots/components/run-now-toast.ts+++ b/packages/views/autopilots/components/run-now-toast.ts@@ -37,6 +37,7 @@ export type RunNowBlockedKey =| "run_blocked_attribution"| "run_blocked_already_active"| "run_blocked_quota_exceeded"+ | "run_blocked_issue_limit_reached"| "run_blocked_generic";export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKey {@@ -57,6 +58,8 @@ export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKreturn "run_blocked_already_active";case "quota_exceeded":return "run_blocked_quota_exceeded";+ case "issue_limit_reached":+ return "run_blocked_issue_limit_reached";default:return "run_blocked_generic";}diff --git a/packages/views/issues/components/board-card-assignee-picker.test.tsx b/packages/views/issues/components/board-card-assignee-picker.test.tsxindex d4f12a6e44..50e7f6f60d 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: true,+ childProgress: false,labels: false,},cardPropertyIds: [],@@ -67,10 +67,7 @@ vi.mock("@multica/core/workspace/hooks", () => ({}));vi.mock("../../i18n", () => ({- useT: () => ({- t: (_selector: unknown, options?: { count?: number }) =>- options?.count === undefined ? "Translated" : `${options.count} restricted`,- }),+ useT: () => ({ t: () => "Translated" }),useTimeAgo: () => () => "now",}));@@ -163,28 +160,4 @@ 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 d7bf3b5025..017b6a23c8 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -292,16 +292,11 @@ export const BoardCardContent = memo(function BoardCardContent({))}{showChildProgress && (- <div className="inline-flex shrink-0 items-center gap-1.5">+ <div className="inline-flex shrink-0 items-center gap-1"><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 ab87238b0b..00525307b5 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -25,14 +25,10 @@ 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 {@@ -58,7 +54,6 @@ 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;@@ -129,11 +124,6 @@ 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/agents.json b/packages/views/locales/en/agents.jsonindex be0aa4f617..f7be39b170 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -907,7 +907,6 @@"skill_bundle_unavailable": "Couldn't download the agent's skills","runtime_cli_timeout": "Local runtime CLI timed out","invalid_task_identity": "Task identity mismatch",- "issue_window_restricted": "Issue unavailable under workspace limits","agent_error_provider_auth_or_access": "Provider auth failed","agent_error_provider_quota_limit": "Provider quota exhausted","agent_error_provider_capacity_or_rate_limit": "Rate limited by provider",diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex d2c1471ba0..85d09ea49f 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -84,6 +84,7 @@"run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member","run_blocked_already_active": "Not triggered — a recent run already covers this","run_blocked_quota_exceeded": "Not triggered — the run limit for this period has been reached",+ "run_blocked_issue_limit_reached": "Not triggered — the workspace has reached its issue limit","run_blocked_generic": "Not triggered — the run was blocked","section_properties": "Properties","section_triggers": "Triggers",diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 5f14166ad5..19e295a863 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -142,10 +142,6 @@"canceled_title": "Subscription is canceled","canceled_description": "The entitlement badge above shows the plan currently enforced for this workspace."},- "read_only": {- "title": "Read-only billing access",- "description": "You can view the workspace plan and limits. Only owners and admins can purchase or manage a subscription."- },"current": {"title": "Current plan","plan": "Workspace plan",@@ -169,8 +165,6 @@"pro_for_team_other": "Pro for {{count}} human seats","price_loading": "Loading subscription prices","unit_price": "{{price}} per human seat",- "estimated_monthly_total": "Estimated monthly total: {{price}}",- "estimated_yearly_total": "Estimated yearly total: {{price}}","price_at_checkout": "The server re-counts human members before purchase. Stripe Checkout shows the authoritative per-seat price and total before you pay."},"management": {@@ -182,13 +176,12 @@},"limits": {"title": "Usage and limits",- "description": "Limits come from the current entitlement. Automation usage comes from server quota accounting.",- "issues": "Recent tasks",- "issues_description": "Free keeps the most recently active tasks available. Pro has no window limit.",- "autopilots": "Successful automations",- "autopilots_description": "The Free allowance resets each UTC calendar month. Pro is unlimited.",+ "description": "Limits and usage come from the server's current entitlement and quota accounting.",+ "issues": "Issues",+ "issues_description": "Current issue usage and the effective limit reported by the server.",+ "autopilots": "Automation runs",+ "autopilots_description": "Current automation usage and reset time reported by the server.","unlimited": "Unlimited",- "unavailable": "Unavailable","per_month": "{{count}} / month","usage_loading": "Loading automation usage","usage_label": "Automation quota usage",diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 3163ec83cd..560c886033 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -689,9 +689,7 @@},"card": {"update_failed": "Failed to update issue",- "updated_ago": "Updated {{time}}",- "child_progress_restricted_one": "{{count}} restricted",- "child_progress_restricted_other": "{{count}} restricted"+ "updated_ago": "Updated {{time}}"},"actions": {"status": "Status",diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex d452a00f71..3f28978448 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -159,6 +159,7 @@"toast_failed": "Failed to create issue","toast_duplicate_title": "Duplicate issue","toast_duplicate_view": "View existing issue",+ "toast_issue_limit_reached": "This workspace has reached its issue limit","toast_link_subissues_all_failed": "Failed to link sub-issues","toast_link_subissues_partial": "Failed to link {{failed}} of {{total}} sub-issues","toast_link_labels_failed": "Failed to attach labels",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex abda317d15..cb8d8db100 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -782,7 +782,6 @@"skill_bundle_unavailable": "エージェントのスキルをダウンロードできませんでした","runtime_cli_timeout": "ローカルランタイム CLI がタイムアウトしました","invalid_task_identity": "作業のエージェント情報が一致しません",- "issue_window_restricted": "ワークスペースの制限によりタスクを利用できません","agent_error_provider_auth_or_access": "プロバイダーの認証に失敗しました","agent_error_provider_quota_limit": "プロバイダーのクォータを使い切りました","agent_error_provider_capacity_or_rate_limit": "プロバイダーによるレート制限",diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 261470256e..2ab4747b9f 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -84,6 +84,7 @@"run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした","run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています","run_blocked_quota_exceeded": "実行されませんでした — この期間の実行上限に達しました",+ "run_blocked_issue_limit_reached": "実行されませんでした — ワークスペースのタスク数上限に達しました","run_blocked_generic": "実行されませんでした — 実行がブロックされました","section_properties": "プロパティ","section_triggers": "トリガー",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex da857f51c2..9f0bfed7b6 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -142,10 +142,6 @@"canceled_title": "サブスクリプションはキャンセル済みです","canceled_description": "上のプランバッジは、このワークスペースに現在適用されているプランを示します。"},- "read_only": {- "title": "請求情報の閲覧のみ",- "description": "ワークスペースのプランと上限を確認できます。サブスクリプションの購入と管理は owner と admin のみ実行できます。"- },"current": {"title": "現在のプラン","plan": "ワークスペースプラン",@@ -167,8 +163,6 @@"pro_for_team_other": "{{count}}席で Pro を利用","price_loading": "サブスクリプション価格を読み込んでいます","unit_price": "1席あたり {{price}}",- "estimated_monthly_total": "月払いの見積合計:{{price}}",- "estimated_yearly_total": "年払いの見積合計:{{price}}","price_at_checkout": "購入前にサーバーがユーザーメンバーを再集計します。お支払い前に Stripe Checkout で正式な席単価と合計金額を確認できます。"},"management": {@@ -180,13 +174,12 @@},"limits": {"title": "使用量と上限",- "description": "上限は現在の entitlement、自動化の使用量はサーバーのクォータ集計に基づきます。",- "issues": "最近のタスク",- "issues_description": "Free では最近アクティブなタスクを利用できます。Pro には件数制限がありません。",- "autopilots": "成功した自動化",- "autopilots_description": "Free の上限は UTC の暦月ごとにリセットされます。Pro は無制限です。",+ "description": "上限と使用量は、サーバーの現在の entitlement とクォータ集計に基づきます。",+ "issues": "Issue 数",+ "issues_description": "現在の Issue 使用量とサーバーから返された有効な上限です。",+ "autopilots": "自動化の実行",+ "autopilots_description": "現在の自動化使用量とサーバーから返されたリセット時刻です。","unlimited": "無制限",- "unavailable": "利用できません","per_month": "月 {{count}} 回","usage_loading": "自動化の使用量を読み込み中","usage_label": "自動化クォータの使用量",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 5e7f4943d3..1bcdcfa9b4 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -658,8 +658,7 @@},"card": {"update_failed": "タスクを更新できませんでした",- "updated_ago": "{{time}} に更新",- "child_progress_restricted_other": "サブタスク {{count}} 件が制限中"+ "updated_ago": "{{time}} に更新"},"actions": {"status": "ステータス",diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex ee4693261e..834e4e7c3e 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -157,6 +157,7 @@"toast_failed": "タスクを作成できませんでした","toast_duplicate_title": "重複タスク","toast_duplicate_view": "既存のタスクを表示",+ "toast_issue_limit_reached": "このワークスペースはタスク数の上限に達しました","toast_link_subissues_all_failed": "サブタスクをリンクできませんでした","toast_link_subissues_partial": "サブタスク {{total}} 件中 {{failed}} 件をリンクできませんでした","toast_link_labels_failed": "ラベルを付けられませんでした",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 637dfebdcf..eb847d02a6 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -790,7 +790,6 @@"skill_bundle_unavailable": "에이전트 스킬을 다운로드할 수 없음","runtime_cli_timeout": "로컬 런타임 CLI 시간 초과","invalid_task_identity": "작업 ID 정보가 일치하지 않음",- "issue_window_restricted": "워크스페이스 제한으로 태스크를 사용할 수 없음","agent_error_provider_auth_or_access": "공급자 인증 실패","agent_error_provider_quota_limit": "공급자 할당량 소진","agent_error_provider_capacity_or_rate_limit": "공급자 요청 한도에 도달함",diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex 6e9bf03848..563d2f4505 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -84,6 +84,7 @@"run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다","run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다","run_blocked_quota_exceeded": "실행되지 않음 — 이 기간의 실행 한도에 도달했습니다",+ "run_blocked_issue_limit_reached": "실행되지 않음 — 워크스페이스가 태스크 수 한도에 도달했습니다","run_blocked_generic": "실행되지 않음 — 실행이 차단되었습니다","section_properties": "속성","section_triggers": "트리거",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 88ea6a05d9..d41d2a82d0 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -142,10 +142,6 @@"canceled_title": "구독이 취소되었습니다","canceled_description": "위 요금제 배지는 이 워크스페이스에 현재 적용되는 요금제를 보여 줍니다."},- "read_only": {- "title": "결제 정보 읽기 전용",- "description": "워크스페이스 요금제와 한도를 볼 수 있습니다. 구독 구매와 관리는 owner와 admin만 할 수 있습니다."- },"current": {"title": "현재 요금제","plan": "워크스페이스 요금제",@@ -167,8 +163,6 @@"pro_for_team_other": "사용자 좌석 {{count}}개에 Pro 적용","price_loading": "구독 가격을 불러오는 중","unit_price": "사용자 좌석당 {{price}}",- "estimated_monthly_total": "예상 월간 합계: {{price}}",- "estimated_yearly_total": "예상 연간 합계: {{price}}","price_at_checkout": "구매 전에 서버가 사용자 멤버를 다시 계산합니다. 결제 전 Stripe Checkout에서 공식 좌석당 가격과 총액을 확인할 수 있습니다."},"management": {@@ -180,13 +174,12 @@},"limits": {"title": "사용량 및 한도",- "description": "한도는 현재 entitlement에서, 자동화 사용량은 서버 쿼터 집계에서 가져옵니다.",- "issues": "최근 태스크",- "issues_description": "Free에서는 최근 활성 태스크를 이용할 수 있습니다. Pro에는 범위 제한이 없습니다.",- "autopilots": "성공한 자동화",- "autopilots_description": "Free 한도는 UTC 기준 매월 초기화됩니다. Pro는 무제한입니다.",+ "description": "한도와 사용량은 서버의 현재 entitlement와 쿼터 집계에서 가져옵니다.",+ "issues": "Issue 수",+ "issues_description": "현재 Issue 사용량과 서버에서 반환한 유효 한도입니다.",+ "autopilots": "자동화 실행",+ "autopilots_description": "현재 자동화 사용량과 서버에서 반환한 초기화 시각입니다.","unlimited": "무제한",- "unavailable": "사용할 수 없음","per_month": "월 {{count}}회","usage_loading": "자동화 사용량 불러오는 중","usage_label": "자동화 쿼터 사용량",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex d5bde5ac62..325e1ab13e 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -658,8 +658,7 @@},"card": {"update_failed": "태스크를 업데이트하지 못했습니다",- "updated_ago": "{{time}} 수정됨",- "child_progress_restricted_other": "하위 태스크 {{count}}개 제한됨"+ "updated_ago": "{{time}} 수정됨"},"actions": {"status": "상태",diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex 3afa19e199..ab079cfd4f 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -157,6 +157,7 @@"toast_failed": "태스크를 만들지 못했습니다","toast_duplicate_title": "중복 태스크","toast_duplicate_view": "기존 태스크 보기",+ "toast_issue_limit_reached": "이 워크스페이스가 태스크 수 한도에 도달했습니다","toast_link_subissues_all_failed": "하위 태스크를 연결하지 못했습니다","toast_link_subissues_partial": "하위 태스크 {{total}}개 중 {{failed}}개를 연결하지 못했습니다","toast_link_labels_failed": "라벨을 연결하지 못했습니다",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex cb060619e4..6394435edd 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -889,7 +889,6 @@"skill_bundle_unavailable": "无法下载智能体的 skill","runtime_cli_timeout": "本地运行时 CLI 超时","invalid_task_identity": "task 身份不匹配",- "issue_window_restricted": "任务超出工作区可用范围","agent_error_provider_auth_or_access": "提供商认证失败","agent_error_provider_quota_limit": "提供商配额已用尽","agent_error_provider_capacity_or_rate_limit": "受到提供商速率限制",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex d94fa92ba8..f5a6209009 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -84,6 +84,7 @@"run_blocked_attribution": "未触发——无法确定本次运行的负责成员","run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次","run_blocked_quota_exceeded": "未触发——本周期的运行额度已用尽",+ "run_blocked_issue_limit_reached": "未触发——工作区任务总数已达到上限","run_blocked_generic": "未触发——本次运行已被拦截","section_properties": "属性","section_triggers": "触发器",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex f01df0192b..cf524a8f1b 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -142,10 +142,6 @@"canceled_title": "订阅已取消","canceled_description": "上方套餐徽标显示这个工作区当前实际生效的套餐。"},- "read_only": {- "title": "账单只读权限",- "description": "你可以查看工作区套餐和限额。只有 owner 和 admin 可以购买或管理订阅。"- },"current": {"title": "当前套餐","plan": "工作区套餐",@@ -167,8 +163,6 @@"pro_for_team_other": "为 {{count}} 个成员席位升级 Pro","price_loading": "正在加载订阅价格","unit_price": "每个成员席位 {{price}}",- "estimated_monthly_total": "预计月付总额:{{price}}",- "estimated_yearly_total": "预计年付总额:{{price}}","price_at_checkout": "购买前,服务端会重新统计成员。付款前,Stripe Checkout 会显示权威的单席位价格和总额。"},"management": {@@ -180,13 +174,12 @@},"limits": {"title": "用量与限额",- "description": "限额来自当前 entitlement,自动化用量来自服务端额度统计。",- "issues": "最近活跃的任务",- "issues_description": "Free 可访问最近活跃的任务;Pro 没有窗口限制。",- "autopilots": "成功的自动化执行",- "autopilots_description": "Free 限额按 UTC 自然月重置;Pro 不限次数。",+ "description": "限额和用量来自服务端当前 entitlement 与额度统计。",+ "issues": "任务数量",+ "issues_description": "当前任务用量和服务端返回的生效限额。",+ "autopilots": "自动化执行",+ "autopilots_description": "当前自动化用量和服务端返回的重置时间。","unlimited": "不限",- "unavailable": "暂不可用","per_month": "每月 {{count}} 次","usage_loading": "正在加载自动化用量","usage_label": "自动化额度用量",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 26390d0725..397e98cb3c 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -658,8 +658,7 @@},"card": {"update_failed": "更新任务失败",- "updated_ago": "更新于 {{time}}",- "child_progress_restricted_other": "{{count}} 个子任务受限"+ "updated_ago": "更新于 {{time}}"},"actions": {"status": "状态",diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex 48af6610c7..7d92da51cb 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -157,6 +157,7 @@"toast_failed": "创建任务失败","toast_duplicate_title": "已存在同名任务","toast_duplicate_view": "查看已有任务",+ "toast_issue_limit_reached": "该工作区的任务总数已达到上限","toast_link_subissues_all_failed": "关联子任务失败","toast_link_subissues_partial": "{{total}} 个子任务中有 {{failed}} 个关联失败","toast_link_labels_failed": "关联标签失败",diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex b0b9aecd53..1f04e4f1a9 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -676,6 +676,10 @@ export function ManualCreatePanel({toast.error(sourceContextFailureMessage(err) ?? tIssues(($) => $.source_context.error_too_large));return false;}+ if (sourceCode === "issue_limit_reached") {+ toast.error(t(($) => $.create_issue.toast_issue_limit_reached));+ return false;+ }// Duplicate-issue is the only structured 409 the create endpoint// returns. We schema-guard the body (ApiError.body is `unknown`) so a// future server-side rename / drop of `code` / `issue` degrades to thediff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex 62360233a6..64d1091883 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -7,9 +7,7 @@ import type {WorkspaceSubscriptionSummary,} from "@multica/core/types";import {- canPurchaseWorkspaceSubscription,hasActiveWorkspaceSeatCapacity,- hasWorkspaceBillingRelationship,resolveAutopilotUsage,} from "./billing-state";@@ -18,8 +16,10 @@ const freeEntitlements: WorkspaceSubscriptionEntitlements = {plan: "free",status: "inactive",seats: 3,- issueWindow: 17,- autopilotRuns: 7,+ limits: {+ issueCount: { mode: "limited", limit: 17 },+ autopilotRuns: { mode: "limited", limit: 7 },+ },currentPeriodEnd: null,snapshotExpiresAt: null,version: 1,@@ -29,7 +29,9 @@ const quotaUsage: AutopilotQuotaUsage = {action: "enforce",used: 3,reserved: 2,+ total: 5,limit: 7,+ reached: false,period_start: "2030-01-01T00:00:00Z",period_end: "2030-02-01T00:00:00Z",reset_at: "2030-02-01T00:00:00Z",@@ -39,7 +41,7 @@ const quotaUsage: AutopilotQuotaUsage = {describe("resolveAutopilotUsage", () => {it("counts reserved runs toward progress and the reached decision", () => {expect(- resolveAutopilotUsage(freeEntitlements, quotaUsage, false, false),+ resolveAutopilotUsage(freeEntitlements, quotaUsage, false),).toEqual({kind: "metered",used: 3,@@ -54,27 +56,31 @@ describe("resolveAutopilotUsage", () => {expect(resolveAutopilotUsage(freeEntitlements,- { ...quotaUsage, used: 5 },- false,+ { ...quotaUsage, used: 5, total: 7, reached: true },false,),).toMatchObject({ total: 7, reached: true, progress: 100 });});- it("shows Pro as unlimited from entitlement even when usage is unavailable", () => {+ it("renders the server's explicit unlimited mode", () => {expect(resolveAutopilotUsage(- { ...freeEntitlements, plan: "pro", autopilotRuns: null },+ {+ ...freeEntitlements,+ limits: {+ ...freeEntitlements.limits,+ autopilotRuns: { mode: "unlimited", limit: null },+ },+ },undefined,true,- true,),).toEqual({ kind: "unlimited" });});it("does not turn missing or disabled limited usage into zero or unlimited", () => {expect(- resolveAutopilotUsage(freeEntitlements, undefined, true, false),+ resolveAutopilotUsage(freeEntitlements, undefined, true),).toEqual({ kind: "unavailable" });expect(resolveAutopilotUsage(@@ -84,46 +90,40 @@ describe("resolveAutopilotUsage", () => {action: "off",used: null,reserved: null,+ total: null,limit: null,+ reached: null,reset_at: null,},false,- false,),).toEqual({ kind: "unavailable" });- });-- it("prefers trusted Pro unlimited over stale metered usage", () => {expect(resolveAutopilotUsage(- { ...freeEntitlements, plan: "pro", autopilotRuns: null },- quotaUsage,+ freeEntitlements,+ {+ ...quotaUsage,+ action: "observe",+ total: quotaUsage.limit,+ reached: null,+ },false,- true,),- ).toEqual({ kind: "unlimited" });+ ).toEqual({ kind: "unavailable" });});- it("keeps metered usage when the Pro entitlement is not trusted", () => {+ it("uses the explicit limited mode even when plan and status say Pro", () => {expect(resolveAutopilotUsage(- { ...freeEntitlements, plan: "pro", autopilotRuns: null },+ {+ ...freeEntitlements,+ plan: "pro",+ status: "active",+ },quotaUsage,false,- false,),- ).toMatchObject({ kind: "metered", total: 5, limit: 7 });- });-- it("does not derive unlimited when the entitlement fact is not trusted", () => {- expect(- resolveAutopilotUsage(- { ...freeEntitlements, plan: "pro", autopilotRuns: null },- undefined,- true,- false,- ),- ).toEqual({ kind: "unavailable" });+ ).toMatchObject({ kind: "metered", limit: 7 });});});@@ -137,10 +137,14 @@ describe("billing subscription state", () => {cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: true,+ availableActions: {+ checkout: true,+ portal: true,+ purchaseSeats: false,+ },} satisfies WorkspaceSubscriptionSummary;expect(hasActiveWorkspaceSeatCapacity(canceledSummary)).toBe(false);- expect(hasWorkspaceBillingRelationship(canceledSummary)).toBe(true);const activeSummary = {...canceledSummary,@@ -149,42 +153,12 @@ describe("billing subscription state", () => {used: 3,reserved: 1,available: 1,+ overcommitted: false,version: 2,pendingQuantity: null,activePurchase: null,},} satisfies WorkspaceSubscriptionSummary;expect(hasActiveWorkspaceSeatCapacity(activeSummary)).toBe(true);- expect(hasWorkspaceBillingRelationship(undefined)).toBe(false);- });-- it.each([- ["inactive", true],- ["canceled", true],- ["incomplete_expired", true],- ["active", false],- ["trialing", false],- ["past_due", false],- ["incomplete", false],- ["paused", false],- ["unpaid", false],- ["future_status", false],- ])("allows a Free workspace in %s to purchase: %s", (status, expected) => {- expect(- canPurchaseWorkspaceSubscription({- ...freeEntitlements,- status,- }),- ).toBe(expected);- });-- it("never offers Checkout while Pro is currently enforced", () => {- expect(- canPurchaseWorkspaceSubscription({- ...freeEntitlements,- plan: "pro",- status: "active",- }),- ).toBe(false);});});diff --git a/packages/views/settings/components/billing-state.ts b/packages/views/settings/components/billing-state.tsindex 1b9d674006..dacf38afbb 100644--- a/packages/views/settings/components/billing-state.ts+++ b/packages/views/settings/components/billing-state.ts@@ -21,39 +21,35 @@ export type AutopilotUsageView =/*** Quota admission counts completed and reserved runs. Keep reserved work* visible so the progress bar matches the server's blocking decision for a- * limited workspace. A trusted Pro entitlement is authoritative for plan- * limits because the server enforcement policy may lag a subscription change.+ * limited workspace. Limit mode and the reached decision are server facts;+ * this helper only prepares presentation values.*/export function resolveAutopilotUsage(entitlements: WorkspaceSubscriptionEntitlements,usage: AutopilotQuotaUsage | undefined,failed: boolean,- allowEntitlementUnlimited: boolean,): AutopilotUsageView {- if (- allowEntitlementUnlimited &&- entitlements.plan === "pro" &&- entitlements.autopilotRuns === null- ) {+ if (entitlements.limits.autopilotRuns.mode === "unlimited") {return { kind: "unlimited" };}if (!failed && usage !== undefined && usage.action !== "off") {- const { used, reserved, limit, reset_at: resetAt } = usage;+ const { used, reserved, total, limit, reached, reset_at: resetAt } = usage;if (used !== null &&reserved !== null &&+ total !== null &&limit !== null &&+ reached !== null &&resetAt !== null &&used >= 0 &&reserved >= 0 &&limit >= 0 &&Number.isFinite(used) &&Number.isFinite(reserved) &&+ Number.isFinite(total) &&Number.isFinite(limit)) {- const total = used + reserved;- const reached = total >= limit;const progress =limit === 0? 100@@ -75,34 +71,8 @@ export function resolveAutopilotUsage(return { kind: "unavailable" };}-const PURCHASABLE_SUBSCRIPTION_STATUSES = new Set([- "inactive",- "canceled",- "incomplete_expired",-]);-export function hasActiveWorkspaceSeatCapacity(summary: WorkspaceSubscriptionSummary | null | undefined,): boolean {return summary?.seatCapacity != null;}--export function hasWorkspaceBillingRelationship(- summary: WorkspaceSubscriptionSummary | null | undefined,-): boolean {- return summary?.hasStripeCustomer === true;-}--/**- * Checkout creates a new subscription. Cloud accepts an existing record only- * after cancellation or incomplete setup expiry; every other known status may- * still represent a live or recoverable subscription and stays in Portal.- */-export function canPurchaseWorkspaceSubscription(- entitlements: WorkspaceSubscriptionEntitlements,-): boolean {- return (- entitlements.plan === "free" &&- PURCHASABLE_SUBSCRIPTION_STATUSES.has(entitlements.status)- );-}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 5329b83c1a..507d507ab3 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -4,6 +4,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { ApiError } from "@multica/core/api";import { configStore } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";+import type {+ AutopilotQuotaUsage,+ IssueLimitUsage,+ WorkspaceSubscriptionEntitlements,+ WorkspaceSubscriptionSummary,+} from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";const mocks = vi.hoisted(() => ({@@ -15,9 +21,9 @@ const mocks = vi.hoisted(() => ({refetch: vi.fn(),refetchSummary: vi.fn(),refetchUsage: vi.fn(),+ refetchIssueLimitUsage: vi.fn(),refetchPrices: vi.fn(),openExternal: vi.fn(),- role: "owner" as "owner" | "admin" | "member",workspaceId: "workspace-1",prices: null as {month: {@@ -44,22 +50,24 @@ const mocks = vi.hoisted(() => ({usagePending: false,usageFetching: false,usageError: false,- entitlementsDataUpdatedAt: 0,- entitlementsFetchedAfterMount: false,+ summaryDataUpdatedAt: 0,+ summaryFetchedAfterMount: false,entitlements: {workspaceId: "workspace-1",plan: "free",status: "inactive",seats: 3,- issueWindow: 17,- autopilotRuns: 7,+ limits: {+ issueCount: { mode: "limited", limit: 17 },+ autopilotRuns: { mode: "limited", limit: 7 },+ },currentPeriodEnd: null as string | null,snapshotExpiresAt: null as string | null,version: 0,- },+ } as WorkspaceSubscriptionEntitlements,summary: {- entitlement: null as never,- billingInterval: null as "month" | "year" | null,+ entitlement: null as unknown as WorkspaceSubscriptionEntitlements,+ billingInterval: null,humanMembers: 3,seatCapacity: null as {purchased: number;@@ -78,17 +86,28 @@ const mocks = vi.hoisted(() => ({cancelAtPeriodEnd: false,graceUntil: null as string | null,hasStripeCustomer: false,- },+ availableActions: {+ checkout: true,+ portal: false,+ purchaseSeats: false,+ },+ } as WorkspaceSubscriptionSummary,+ issueLimitUsage: {+ used: 11,+ limit: 17,+ } as IssueLimitUsage,usage: {action: "enforce" as "off" | "observe" | "enforce",used: 3 as number | null,reserved: 2 as number | null,+ total: 5 as number | null,limit: 7 as number | null,+ reached: false as boolean | null,period_start: "2030-01-01T00:00:00Z" as string | null,period_end: "2030-02-01T00:00:00Z" as string | null,reset_at: "2030-02-01T00:00:00Z" as string | null,blocked_counts: {} as Record<string, number> | null,- },+ } as AutopilotQuotaUsage,}));vi.mock("@tanstack/react-query", () => ({@@ -96,15 +115,15 @@ vi.mock("@tanstack/react-query", () => ({}));vi.mock("@multica/core/billing", () => ({- workspaceSubscriptionEntitlementsOptions: (wsId: string) => ({- queryKey: ["workspace-subscriptions", wsId, "entitlements"],- }),workspaceSubscriptionPricesOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "prices"],}),workspaceSubscriptionSummaryOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "summary"],}),+ issueLimitUsageOptions: (wsId: string) => ({+ queryKey: ["workspace-subscriptions", wsId, "issue-limit-usage"],+ }),useCreateWorkspaceSubscriptionCheckout: () => ({mutateAsync: mocks.checkout,isPending: false,@@ -137,10 +156,6 @@ vi.mock("@multica/core/paths", () => ({}),}));-vi.mock("@multica/core/permissions", () => ({- useCurrentMember: () => ({ role: mocks.role, isLoading: false }),-}));-const navigationState = {search: "tab=billing",replace: vi.fn(),@@ -185,17 +200,22 @@ function setSeatCapacity({used,reserved,available,+ overcommitted: used > purchased,version,pendingQuantity,activePurchase,};+ Object.assign(mocks.summary.availableActions, {+ checkout: false,+ portal: true,+ purchaseSeats: activePurchase === null,+ });}describe("BillingTab", () => {beforeEach(() => {vi.clearAllMocks();navigationState.search = "tab=billing";- mocks.role = "owner";mocks.workspaceId = "workspace-1";mocks.prices = {month: {@@ -222,14 +242,16 @@ describe("BillingTab", () => {mocks.usagePending = false;mocks.usageFetching = false;mocks.usageError = false;- mocks.entitlementsDataUpdatedAt = 0;- mocks.entitlementsFetchedAfterMount = false;+ mocks.summaryDataUpdatedAt = 0;+ mocks.summaryFetchedAfterMount = false;Object.assign(mocks.entitlements, {plan: "free",status: "inactive",seats: 3,- issueWindow: 17,- autopilotRuns: 7,+ limits: {+ issueCount: { mode: "limited", limit: 17 },+ autopilotRuns: { mode: "limited", limit: 7 },+ },currentPeriodEnd: null,snapshotExpiresAt: null,version: 0,@@ -242,12 +264,23 @@ describe("BillingTab", () => {cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: false,+ availableActions: {+ checkout: true,+ portal: false,+ purchaseSeats: false,+ },+ });+ Object.assign(mocks.issueLimitUsage, {+ used: 11,+ limit: 17,});Object.assign(mocks.usage, {action: "enforce",used: 3,reserved: 2,+ total: 5,limit: 7,+ reached: false,period_start: "2030-01-01T00:00:00Z",period_end: "2030-02-01T00:00:00Z",reset_at: "2030-02-01T00:00:00Z",@@ -274,22 +307,31 @@ describe("BillingTab", () => {isPending: mocks.summaryPending,isFetching: mocks.summaryFetching,isError: mocks.summaryError,+ dataUpdatedAt: mocks.summaryDataUpdatedAt,+ isFetchedAfterMount: mocks.summaryFetchedAfterMount,refetch: mocks.refetchSummary,};}+ if (queryKey?.[queryKey.length - 1] === "issue-limit-usage") {+ return {+ data: mocks.issueLimitUsage,+ isPending: false,+ isFetching: false,+ isError: false,+ refetch: mocks.refetchIssueLimitUsage,+ };+ }if (queryKey?.[queryKey.length - 1] === "usage") {return {data: mocks.usageError ? undefined : mocks.usage,isPending: mocks.usagePending,isFetching: mocks.usageFetching,isError: mocks.usageError,- refetch: mocks.refetchUsage,- };- }+ refetch: mocks.refetchUsage,+ };+ }return {data: mocks.entitlements,- dataUpdatedAt: mocks.entitlementsDataUpdatedAt,- isFetchedAfterMount: mocks.entitlementsFetchedAfterMount,isPending: false,isError: false,refetch: mocks.refetch,@@ -343,13 +385,10 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();- expect(screen.getByText("17")).toBeInTheDocument();+ expect(screen.getByText("11 / 17")).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(screen.getByText("3 completed · 2 in progress")).toBeInTheDocument();expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();- expect(- screen.getByText("Estimated monthly total: $30.00"),- ).toBeInTheDocument();expect(mocks.useQuery).toHaveBeenCalledWith(expect.objectContaining({queryKey: ["workspace-subscriptions", "workspace-1", "prices"],@@ -359,12 +398,6 @@ describe("BillingTab", () => {await user.click(screen.getByRole("button", { name: "Yearly" }));expect(screen.getByText("$96.00 per human seat")).toBeInTheDocument();- expect(- screen.getByText("Estimated yearly total: $288.00"),- ).toBeInTheDocument();- expect(- screen.queryByText("Estimated monthly total: $30.00"),- ).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Retry" }),).not.toBeInTheDocument();@@ -478,20 +511,6 @@ describe("BillingTab", () => {expect(screen.queryByText(/\$0/)).not.toBeInTheDocument();});- it("does not display a price whose recurrence is not every one interval", () => {- if (mocks.prices) mocks.prices.month.intervalCount = 3;-- renderWithI18n(<BillingTab />);-- expect(screen.queryByText("$10.00 per human seat")).not.toBeInTheDocument();- expect(- screen.getByText(/Stripe Checkout shows the authoritative per-seat price/),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Retry" }),- ).not.toBeInTheDocument();- });-it("creates Checkout with a client idempotency key and opens Stripe externally", async () => {const user = userEvent.setup();renderWithI18n(<BillingTab />);@@ -606,9 +625,15 @@ describe("BillingTab", () => {expect(screen.getByText("Activating your subscription"),).toBeInTheDocument();- expect(mocks.useQuery).toHaveBeenCalledWith(- expect.objectContaining({ refetchInterval: 2_000 }),- );+ const summaryOptions = mocks.useQuery.mock.calls+ .map(([options]) => options)+ .find(+ (options) =>+ options.queryKey?.[options.queryKey.length - 1] === "summary",+ );+ expect(+ summaryOptions.refetchInterval({ state: { data: mocks.summary } }),+ ).toBe(2_000);expect(navigationState.replace).toHaveBeenCalledWith("/acme/settings?tab=billing",);@@ -626,18 +651,16 @@ describe("BillingTab", () => {}});- it("keeps Checkout syncing until Pro is fetched after the return callback", () => {+ it("keeps Checkout syncing while Cloud still exposes Checkout", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2030-01-01T00:00:00Z"));navigationState.search = "tab=billing&result=success&session_id=cs_test_1";Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});- mocks.entitlementsDataUpdatedAt = Date.now() - 1;- mocks.entitlementsFetchedAfterMount = true;+ mocks.summaryDataUpdatedAt = Date.now() - 1;+ mocks.summaryFetchedAfterMount = true;try {renderWithI18n(<BillingTab />);@@ -646,28 +669,37 @@ describe("BillingTab", () => {).toBeInTheDocument();expect(screen.queryByText("Pro is active")).not.toBeInTheDocument();expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0);+ expect(screen.getByText("11 / 17")).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();- expect(mocks.useQuery).toHaveBeenCalledWith(- expect.objectContaining({ refetchInterval: 2_000 }),- );+ const summaryOptions = mocks.useQuery.mock.calls+ .map(([options]) => options)+ .find(+ (options) =>+ options.queryKey?.[options.queryKey.length - 1] === "summary",+ );+ expect(+ summaryOptions.refetchInterval({ state: { data: mocks.summary } }),+ ).toBe(2_000);} finally {vi.useRealTimers();}});- it("confirms Pro despite stale metered quota after the return callback", () => {+ it("confirms Checkout from refreshed Cloud actions and limit modes", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2030-01-01T00:00:00Z"));navigationState.search = "tab=billing&result=success&session_id=cs_test_1";Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,+ limits: {+ issueCount: { mode: "unlimited", limit: null },+ autopilotRuns: { mode: "unlimited", limit: null },+ },});- mocks.entitlementsDataUpdatedAt = Date.now() + 1;- mocks.entitlementsFetchedAfterMount = true;+ mocks.summary.availableActions.checkout = false;+ mocks.summaryDataUpdatedAt = Date.now() + 1;+ mocks.summaryFetchedAfterMount = true;try {renderWithI18n(<BillingTab />);@@ -679,15 +711,18 @@ describe("BillingTab", () => {}});- it("keeps plan facts visible but hides subscription mutations from members", () => {- mocks.role = "member";+ it("keeps plan facts visible but hides mutations denied by Cloud", () => {+ Object.assign(mocks.summary.availableActions, {+ checkout: false,+ portal: false,+ purchaseSeats: false,+ });renderWithI18n(<BillingTab />);- expect(screen.getByText("Read-only billing access")).toBeInTheDocument();expect(screen.getAllByText("3 members")).toHaveLength(1);expect(screen.queryByText("Purchased seats")).not.toBeInTheDocument();- expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();+ expect(screen.queryByText("$10.00 per human seat")).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();@@ -697,8 +732,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,currentPeriodEnd: "2030-02-01T00:00:00Z",});Object.assign(mocks.usage, {@@ -737,8 +770,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -811,8 +842,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -869,8 +898,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -899,8 +926,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -938,8 +963,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -981,8 +1004,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -1009,8 +1030,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -1037,8 +1056,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -1071,8 +1088,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,});mocks.summary.hasStripeCustomer = true;setSeatCapacity();@@ -1164,8 +1179,14 @@ describe("BillingTab", () => {}});- it("uses completed and reserved runs for the quota decision", () => {- Object.assign(mocks.usage, { used: 5, reserved: 2, limit: 7 });+ it("renders Cloud's completed, reserved, total, and reached facts", () => {+ Object.assign(mocks.usage, {+ used: 5,+ reserved: 2,+ total: 7,+ limit: 7,+ reached: true,+ });renderWithI18n(<BillingTab />);@@ -1203,18 +1224,16 @@ describe("BillingTab", () => {["request fails", true, false],["response is malformed", false, true],])(- "keeps plan facts visible when the subscription summary %s",+ "fails closed when the authoritative subscription summary %s",(_case, isError, isMalformed) => {mocks.summaryError = isError;mocks.summaryMalformed = isMalformed;renderWithI18n(<BillingTab />);- expect(screen.getByText("Free")).toBeInTheDocument();- expect(- screen.getByText("Some seat details are unavailable"),- ).toBeInTheDocument();- expect(screen.getAllByText("Unavailable")).toHaveLength(4);+ expect(screen.getByText("Billing is temporarily unavailable")).toBeInTheDocument();+ expect(screen.queryByText("Free")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();},);@@ -1257,26 +1276,25 @@ describe("BillingTab", () => {).toBeInTheDocument();});- it("stops deriving Pro access after the summary grace deadline", () => {+ it("renders Cloud-resolved Free access without deriving from past_due", () => {Object.assign(mocks.entitlements, {- plan: "pro",+ plan: "free",status: "past_due",- issueWindow: null,- autopilotRuns: null,});- mocks.summary.graceUntil = "2000-01-01T00:00:00Z";- Object.assign(mocks.usage, {- action: "off",- used: null,- reserved: null,- limit: null,- reset_at: null,+ Object.assign(mocks.summary, {+ graceUntil: null,+ availableActions: {+ checkout: false,+ portal: true,+ purchaseSeats: false,+ },});renderWithI18n(<BillingTab />);expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0);+ expect(screen.getByText("11 / 17")).toBeInTheDocument();+ expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(screen.getByText("Open the Billing Portal to update your payment method. The plan badge above shows the access currently available.",@@ -1315,12 +1333,14 @@ describe("BillingTab", () => {expect(screen.queryByText(/Pro remains available/)).not.toBeInTheDocument();});- it("shows Pro unlimited on a normal load despite stale metered quota", () => {+ it("shows Cloud's explicit unlimited limits on a normal load", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,+ limits: {+ issueCount: { mode: "unlimited", limit: null },+ autopilotRuns: { mode: "unlimited", limit: null },+ },currentPeriodEnd: "2026-09-13T00:00:00Z",version: 3,});@@ -1349,8 +1369,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,version: 3,});setSeatCapacity({ humanMembers: 5, purchased: 4, used: 5 });@@ -1369,8 +1387,6 @@ describe("BillingTab", () => {Object.assign(mocks.entitlements, {plan: "pro",status: "active",- issueWindow: null,- autopilotRuns: null,version: 3,});setSeatCapacity({ humanMembers: 5, purchased: 5, used: 5 });@@ -1394,6 +1410,11 @@ describe("BillingTab", () => {Object.assign(mocks.summary, {seatCapacity: null,hasStripeCustomer: true,+ availableActions: {+ checkout: true,+ portal: true,+ purchaseSeats: false,+ },});renderWithI18n(<BillingTab />);@@ -1421,8 +1442,15 @@ describe("BillingTab", () => {snapshotExpiresAt: null,version: 4,});- mocks.summary.graceUntil = "2000-01-01T00:00:00Z";- mocks.summary.hasStripeCustomer = true;+ Object.assign(mocks.summary, {+ graceUntil: null,+ hasStripeCustomer: true,+ availableActions: {+ checkout: false,+ portal: true,+ purchaseSeats: false,+ },+ });renderWithI18n(<BillingTab />);diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex db8af322a0..d8b69c0e07 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -10,7 +10,6 @@ import {Loader2,Plus,RefreshCw,- ShieldCheck,} from "lucide-react";import { ApiError, errorCode } from "@multica/core/api";import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";@@ -19,13 +18,12 @@ import {useCreateWorkspaceSubscriptionPortal,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,- workspaceSubscriptionEntitlementsOptions,+ issueLimitUsageOptions,workspaceSubscriptionPricesOptions,workspaceSubscriptionSummaryOptions,} from "@multica/core/billing";import { useFeatureEnabled } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";-import { useCurrentMember } from "@multica/core/permissions";import { useCurrentWorkspace } from "@multica/core/paths";import type {PurchaseWorkspaceSeatsRequest,@@ -74,9 +72,7 @@ import {SettingsTab,} from "./settings-layout";import {- canPurchaseWorkspaceSubscription,hasActiveWorkspaceSeatCapacity,- hasWorkspaceBillingRelationship,resolveAutopilotUsage,} from "./billing-state";import { formatStripeMinorAmount } from "./billing-format";@@ -172,9 +168,6 @@ function BillingTabContent() {const navigation = useNavigation();const workspace = useCurrentWorkspace();const wsId = workspace?.id ?? "";- const currentMember = useCurrentMember(wsId);- const canManage =- currentMember.role === "owner" || currentMember.role === "admin";const returnResultParam = parseReturnResult(navigation.searchParams.get("result"),);@@ -295,17 +288,6 @@ function BillingTabContent() {return () => window.clearTimeout(timeout);}, [returnResult, wsId]);- const entitlementQuery = useQuery({- ...workspaceSubscriptionEntitlementsOptions(wsId),- refetchInterval: isSyncingCheckout ? 2_000 : false,- });- const entitlements = entitlementQuery.data;- const isCheckoutProConfirmed =- returnResult === "success" &&- returnObservedAt !== null &&- entitlements?.plan === "pro" &&- entitlementQuery.isFetchedAfterMount &&- entitlementQuery.dataUpdatedAt >= returnObservedAt;const summaryQuery = useQuery({...workspaceSubscriptionSummaryOptions(wsId),// Checkout activation and seat additions both finish asynchronously in a@@ -318,6 +300,13 @@ function BillingTabContent() {? 2_000: false,});+ const entitlements = summaryQuery.data?.entitlement;+ const isCheckoutConfirmed =+ returnResult === "success" &&+ returnObservedAt !== null &&+ summaryQuery.data?.availableActions.checkout === false &&+ summaryQuery.isFetchedAfterMount &&+ summaryQuery.dataUpdatedAt >= returnObservedAt;const activeSeatPurchaseRequestId =summaryQuery.data?.seatCapacity?.activePurchase?.requestId ?? null;@@ -337,13 +326,14 @@ function BillingTabContent() {summaryQuery.isError ||(!summaryQuery.isPending && summaryQuery.data == null);const quotaUsageQuery = useQuery(autopilotQuotaUsageOptions(wsId));+ const issueLimitUsageQuery = useQuery({+ ...issueLimitUsageOptions(wsId),+ enabled:+ wsId.length > 0 &&+ entitlements?.limits.issueCount.mode === "limited",+ });const hasSeatCapacity = hasActiveWorkspaceSeatCapacity(summaryQuery.data);- const hasBillingRelationship = hasWorkspaceBillingRelationship(- summaryQuery.data,- );- const canUpgrade = entitlements- ? canPurchaseWorkspaceSubscription(entitlements)- : false;+ const canUpgrade = summaryQuery.data?.availableActions.checkout === true;const pricesQuery = useQuery({...workspaceSubscriptionPricesOptions(wsId),enabled: wsId.length > 0 && canUpgrade,@@ -352,7 +342,6 @@ function BillingTabContent() {const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);const previewSeatPurchaseMutation = usePreviewWorkspaceSeatPurchase();const purchaseSeatsMutation = usePurchaseWorkspaceSeats(wsId);- const refetchEntitlements = entitlementQuery.refetch;const refetchSummary = summaryQuery.refetch;const previewSeatPurchase = previewSeatPurchaseMutation.mutateAsync;@@ -389,8 +378,7 @@ function BillingTabContent() {!Number.isSafeInteger(additionalSeats) ||additionalSeats < 1 ||currentSeats === null ||- purchaseVersion === null ||- currentSeats + additionalSeats > 10_000+ purchaseVersion === null) {if (seatPreviewCapacityRetryRef.current?.inputKey === retryInputKey &&@@ -502,25 +490,12 @@ function BillingTabContent() {]);useEffect(() => {- if (isSyncingCheckout && isCheckoutProConfirmed) {+ if (isSyncingCheckout && isCheckoutConfirmed) {setIsSyncingCheckout(false);setSyncTimedOut(false);checkoutIntentRef.current = null;}- }, [isCheckoutProConfirmed, isSyncingCheckout]);-- useEffect(() => {- const graceUntil = summaryQuery.data?.graceUntil;- if (!graceUntil) return;- const graceUntilMs = new Date(graceUntil).getTime();- if (Number.isNaN(graceUntilMs)) return;- const delay = Math.max(0, graceUntilMs - Date.now()) + 100;- const timeout = window.setTimeout(() => {- void refetchEntitlements();- void refetchSummary();- }, Math.min(delay, 2_147_000_000));- return () => window.clearTimeout(timeout);- }, [refetchEntitlements, refetchSummary, summaryQuery.data?.graceUntil]);+ }, [isCheckoutConfirmed, isSyncingCheckout]);const planLabel = (plan: string) => {switch (plan) {@@ -599,7 +574,7 @@ function BillingTabContent() {if (error instanceof ApiError && error.status === 409) {checkoutIntentRef.current = null;setActionError(t(($) => $.workspace.errors.already_subscribed));- await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);+ await summaryQuery.refetch();return;}reportActionError(error, t(($) => $.workspace.errors.checkout_failed));@@ -632,7 +607,7 @@ function BillingTabContent() {portalIntentKeyRef.current = null;setPortalUnavailable(true);setActionError(t(($) => $.workspace.errors.portal_unavailable));- await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);+ await summaryQuery.refetch();return;}reportActionError(error, t(($) => $.workspace.errors.portal_failed));@@ -693,7 +668,7 @@ function BillingTabContent() {count: response.resultingSeats,}),);- await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);+ await summaryQuery.refetch();} catch (error) {if (error instanceof ApiError && error.status === 409) {const purchaseErrorCode = errorCode(error);@@ -753,7 +728,7 @@ function BillingTabContent() {setSeatPreview(null);};- if (entitlementQuery.isPending) {+ if (summaryQuery.isPending) {return (<SettingsTabtitle={t(($) => $.workspace.title)}@@ -773,7 +748,7 @@ function BillingTabContent() {);}- if (entitlementQuery.isError || !entitlements) {+ if (summaryQuery.isError || !entitlements) {return (<SettingsTabtitle={t(($) => $.workspace.title)}@@ -787,7 +762,7 @@ function BillingTabContent() {<ButtonclassName="mt-3 h-11"variant="outline"- onClick={() => void entitlementQuery.refetch()}+ onClick={() => void summaryQuery.refetch()}><RefreshCw />{t(($) => $.workspace.actions.retry)}@@ -804,28 +779,13 @@ function BillingTabContent() {);const graceUntilValue = summaryQuery.data?.graceUntil ?? null;const graceUntil = formatDate(graceUntilValue, locale);- const graceUntilMs = graceUntilValue- ? new Date(graceUntilValue).getTime()- : Number.NaN;- const hasActiveProGrace =- entitlements.plan === "pro" &&- entitlements.status === "past_due" &&- Number.isFinite(graceUntilMs) &&- graceUntilMs > Date.now();- const canUseEntitlementUnlimited =- entitlements.plan === "pro" &&- (entitlements.status !== "past_due" || hasActiveProGrace) &&- (returnResult !== "success" || isCheckoutProConfirmed);const actualSeats = summaryQuery.data?.humanMembers ?? entitlements.seats;const seatCapacity = summaryQuery.data?.seatCapacity ?? null;const usedSeats = seatCapacity?.used ?? actualSeats;const billedSeats = seatCapacity?.purchased ?? null;const pendingSeatQuantity = seatCapacity?.pendingQuantity ?? null;const reservedSeats = seatCapacity?.reserved ?? 0;- const membersExceedPurchasedSeats =- hasSeatCapacity &&- billedSeats !== null &&- actualSeats > billedSeats;+ const membersExceedPurchasedSeats = seatCapacity?.overcommitted === true;const availableSeats = seatCapacity?.available ?? null;const activeSeatPurchase = seatCapacity?.activePurchase ?? null;const activeSeatPurchaseExpiry = formatDateTime(@@ -833,22 +793,25 @@ function BillingTabContent() {locale,);const canAddSeats =- canManage &&- hasSeatCapacity &&- (entitlements.status === "active" || entitlements.status === "trialing") &&- !summaryQuery.data?.cancelAtPeriodEnd &&- activeSeatPurchase === null;+ summaryQuery.data?.availableActions.purchaseSeats === true;const quotaUsage = resolveAutopilotUsage(entitlements,quotaUsageQuery.data,quotaUsageQuery.isError,- canUseEntitlementUnlimited,);const quotaResetAt =quotaUsage.kind === "metered"? formatDateTime(quotaUsage.resetAt, locale): null;const numberFormatter = new Intl.NumberFormat(locale);+ const issueCountLimit = entitlements.limits.issueCount;+ const issueLimitUsage = issueLimitUsageQuery.data;+ const issueLimitValue =+ issueCountLimit.mode === "unlimited"+ ? t(($) => $.workspace.limits.unlimited)+ : issueLimitUsage?.limit === issueCountLimit.limit+ ? `${numberFormatter.format(issueLimitUsage.used)} / ${numberFormatter.format(issueLimitUsage.limit)}`+ : numberFormatter.format(issueCountLimit.limit);const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||@@ -861,18 +824,8 @@ function BillingTabContent() {locale,): null;- const formattedEstimatedTotal =- selectedPrice && actualSeats > 0- ? formatStripeMinorAmount(- selectedPrice.unitAmount * actualSeats,- selectedPrice.currency,- locale,- )- : null;const hasDisplayableUnitPrice =selectedPrice?.intervalCount === 1 && formattedUnitPrice !== null;- const hasDisplayableEstimatedTotal =- hasDisplayableUnitPrice && formattedEstimatedTotal !== null;const canRetryPrice = !pricesQuery.isLoading && selectedPrice === null;const formattedSeatProration = seatPreview? formatStripeMinorAmount(@@ -916,7 +869,7 @@ function BillingTabContent() {{returnResult === "success" ? (<Alert>- {isCheckoutProConfirmed ? (+ {isCheckoutConfirmed ? (<CheckCircle2 />) : (<Loader2@@ -928,12 +881,12 @@ function BillingTabContent() {/>)}<AlertTitle>- {isCheckoutProConfirmed+ {isCheckoutConfirmed? t(($) => $.workspace.return.active_title): t(($) => $.workspace.return.syncing_title)}</AlertTitle><AlertDescription>- {isCheckoutProConfirmed+ {isCheckoutConfirmed? t(($) => $.workspace.return.active_description): syncTimedOut? t(($) => $.workspace.return.timeout_description)@@ -969,7 +922,7 @@ function BillingTabContent() {<AlertCircle /><AlertTitle>{t(($) => $.workspace.past_due.title)}</AlertTitle><AlertDescription>- {hasActiveProGrace && graceUntil+ {graceUntil? t(($) => $.workspace.past_due.grace_description, {date: graceUntil,})@@ -1044,16 +997,6 @@ function BillingTabContent() {</Alert>) : null}- {!canManage && !currentMember.isLoading ? (- <Alert>- <ShieldCheck />- <AlertTitle>{t(($) => $.workspace.read_only.title)}</AlertTitle>- <AlertDescription>- {t(($) => $.workspace.read_only.description)}- </AlertDescription>- </Alert>- ) : null}-{actionError ? (<Alert variant="destructive"><AlertCircle />@@ -1163,16 +1106,6 @@ function BillingTabContent() {price: formattedUnitPrice,})}</p>- {hasDisplayableEstimatedTotal ? (- <p className="text-caption leading-5 text-muted-foreground tabular-nums">- {t(- interval === "month"- ? ($) => $.workspace.upgrade.estimated_monthly_total- : ($) => $.workspace.upgrade.estimated_yearly_total,- { price: formattedEstimatedTotal },- )}- </p>- ) : null}</div>) : null}<p className="max-w-[65ch] text-caption leading-5 text-muted-foreground">@@ -1209,22 +1142,20 @@ function BillingTabContent() {</>) : null}</div>- {canManage ? (- <Button- className="h-11 w-full sm:w-auto"- disabled={isMutating}- onClick={() => setCheckoutConfirmOpen(true)}- >- <CreditCard />- {t(($) => $.workspace.actions.upgrade)}- </Button>- ) : null}+ <Button+ className="h-11 w-full sm:w-auto"+ disabled={isMutating}+ onClick={() => setCheckoutConfirmOpen(true)}+ >+ <CreditCard />+ {t(($) => $.workspace.actions.upgrade)}+ </Button></div></SettingsCard></SettingsSection>) : null}- {hasBillingRelationship && canManage ? (+ {summaryQuery.data?.availableActions.portal === true ? (<SettingsSectiontitle={t(($) => $.workspace.management.title)}description={t(($) => $.workspace.management.description)}@@ -1266,13 +1197,7 @@ function BillingTabContent() {label={t(($) => $.workspace.limits.issues)}description={t(($) => $.workspace.limits.issues_description)}>- <span className="tabular-nums">- {entitlements.issueWindow === null- ? canUseEntitlementUnlimited- ? t(($) => $.workspace.limits.unlimited)- : t(($) => $.workspace.limits.unavailable)- : numberFormatter.format(entitlements.issueWindow)}- </span>+ <span className="tabular-nums">{issueLimitValue}</span></SettingsRow><SettingsRowlabel={t(($) => $.workspace.limits.autopilots)}@@ -1327,10 +1252,11 @@ function BillingTabContent() {</div>) : (<div className="flex flex-col gap-2 sm:items-end">- {entitlements.autopilotRuns !== null ? (+ {entitlements.limits.autopilotRuns.mode === "limited" &&+ entitlements.limits.autopilotRuns.limit !== null ? (<span className="tabular-nums">{t(($) => $.workspace.limits.per_month, {- count: entitlements.autopilotRuns,+ count: entitlements.limits.autopilotRuns.limit,})}</span>) : null}@@ -1613,9 +1539,6 @@ function BillingTabContent() {type="number"inputMode="numeric"min={1}- max={- billedSeats === null ? 10_000 : 10_000 - billedSeats- }step={1}value={additionalSeatsInput}disabled={purchaseSeatsMutation.isPending}diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.tsindex fcd337d414..031f715127 100644--- a/packages/views/settings/components/seat-invite-purchase.test.ts+++ b/packages/views/settings/components/seat-invite-purchase.test.ts@@ -30,8 +30,10 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSumplan: "pro",status: "active",seats: purchased,- issueWindow: null,- autopilotRuns: null,+ limits: {+ issueCount: { mode: "unlimited", limit: null },+ autopilotRuns: { mode: "unlimited", limit: null },+ },currentPeriodEnd: null,snapshotExpiresAt: null,version: 1,@@ -43,6 +45,7 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSumused: 4,reserved: purchased - 4 - available,available,+ overcommitted: false,version: 8,pendingQuantity: null,activePurchase: null,@@ -50,6 +53,11 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSumcancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: true,+ availableActions: {+ checkout: false,+ portal: true,+ purchaseSeats: true,+ },};}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 39aab9b358..79cf90b67f 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -429,6 +429,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busopts.BusinessMetrics.RecordEntitlementConfigError()} else if entitlementClient.Enabled() {h.Entitlements = entitlementClient+ h.IssueService.Entitlements = entitlementClienth.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}@@ -1771,17 +1772,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Workspace subscriptions use the same cloud transport and Stripe// webhook as the existing owner-credit billing surface, but every request- // is workspace-scoped. Entitlements, summary and prices are- // member-readable; Checkout, seat reconcile, and Portal mutations require- // owner/admin. The handlers also enforce- // billing_workspace_subscriptions so a route refactor cannot+ // is workspace-scoped. Summary and prices are member-readable. Local role+ // checks cheaply reject unauthorized writes; Cloud remains the final+ // authority and validates every mutation before external writes. Handlers+ // also enforce billing_workspace_subscriptions so a route refactor cannot// accidentally bypass the rollout flag.r.Route("/api/cloud-subscriptions", func(r chi.Router) {r.Use(handler.RequireHumanActor)-r.Group(func(r chi.Router) {r.Use(middleware.RequireWorkspaceMember(queries))- r.Get("/entitlements", h.GetCloudWorkspaceEntitlements)r.Get("/summary", h.GetCloudWorkspaceSubscriptionSummary)r.Get("/prices", h.GetCloudWorkspaceSubscriptionPrices)})@@ -1804,7 +1803,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.Get("/limit-usage", h.GetIssueLimitUsage)r.Post("/table/groups", h.ListIssueTableGroups)r.Post("/table/rows", h.ListIssueTableRows)r.Post("/table/facets", h.ListIssueTableFacets)diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex 8fd7d90aab..db5bc191f8 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -63,6 +63,9 @@ const (// ReasonQuotaExceeded is a policy-neutral refusal for an exhausted// Cloud-provided autopilot interval.ReasonQuotaExceeded ReasonCode = "quota_exceeded"+ // ReasonIssueLimitReached means a create_issue Autopilot was admitted for a+ // run, but Cloud's effective workspace issue-count limit blocked the issue.+ ReasonIssueLimitReached ReasonCode = "issue_limit_reached"// ReasonInternalError: an unexpected server error prevented a clean decision.ReasonInternalError ReasonCode = "internal_error")diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 0e49cb89c1..5d14d8915d 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -7,11 +7,10 @@ switches.Production wiring has one boundary: setting `MULTICA_CLOUD_URL` connects thisconsumer as well as the other managed Cloud clients. An empty URL performs no-HTTP request, and the autopilot consumer does not access its quota tables; the-issue-window consumer likewise keeps its legacy SQL and performs no window-read. Self-hosted deployments therefore retain the legacy paths. Request-timeout and stale grace use bounded code defaults instead of deployment-configuration.+HTTP request, issue creation does not count rows, and the autopilot consumer+does not access its quota tables. Self-hosted deployments therefore retain the+unlimited paths. Request timeout and stale grace use bounded code defaults+instead of deployment configuration.## Contract@@ -51,6 +50,28 @@ cached `enforce` is downgraded to `observe`; after the grace, the result isalso bounds Cloud request rate when an outage returns errors immediately; coldfailures are cached only as `off` and never as policy.+## Issue count limit++The `issue_count` gate limits the total number of rows in a workspace's+`issue` table. It does not use `workspace.issue_counter`: that counter only+allocates monotonically increasing display numbers, while deleting an issue+must release one unit of capacity.++Issue creation resolves the Cloud instruction before opening a transaction.+Inside the transaction, incrementing the workspace issue counter locks the+workspace row, serializing concurrent admission; a bounded `CountIssuesUpTo`+read then admits only when the current row count is below Cloud's limit. A+blocked create rolls back the counter increment with the rest of the+transaction. The usage read is also bounded and samples at most `limit + 1`+rows, with overflow protection for the maximum integer limit.++Entitlement lookup, refresh, expiry, and policy-validation failures are+fail-open: the consumer skips the count and issue creation proceeds. The local+`observe` degradation is likewise normalized to `off` by this consumer; the+shared entitlement decision metric still records the stale observation. Once+a valid `enforce` instruction enters the transaction, ordinary database errors+still abort that transaction rather than creating a partially persisted issue.+The client itself has no background goroutine and introduces no startupdependency; the autopilot consumer owns its policy-neutral accounting andrecovery lifecycle separately. Cloud remains the only place that determines@@ -58,33 +79,3 @@ the effective policy from subscription facts and authoritative limits.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/entitlement/client.go b/server/internal/entitlement/client.goindex 904e60e59a..cf5770de74 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -276,7 +276,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {return fetchedPolicy{}, ErrInvalidPolicy}gates := make(map[GateName]Gate, 2)- for _, name := range []GateName{GateIssueWindow, GateAutopilotRuns} {+ for _, name := range []GateName{GateIssueCount, GateAutopilotRuns} {wireGate, ok := wire.Gates[string(name)]if !ok {return fetchedPolicy{}, ErrInvalidPolicydiff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.goindex 85eda6fe6b..38e6458bf0 100644--- a/server/internal/entitlement/client_test.go+++ b/server/internal/entitlement/client_test.go@@ -34,7 +34,7 @@ func TestDefaultConfigIsDisabledAndPerformsNoIO(t *testing.T) {if client.Enabled() {t.Fatal("zero Config must be disabled")}- decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)+ decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)if decision.Gate.Action != ActionOff || decision.Reason != ReasonDisabled || calls.Load() != 0 {t.Fatalf("decision = %+v, calls = %d", decision, calls.Load())}@@ -81,7 +81,7 @@ func TestGateFetchesMachinePolicyWithoutHumanIdentity(t *testing.T) {defer server.Close()client := newTestClient(t, server.URL, nil)- decision := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ decision := client.Gate(context.Background(), workspaceID, GateIssueCount)if decision.Gate.Action != ActionEnforce || decision.Gate.Limit == nil || *decision.Gate.Limit != testIssueLimit ||decision.Reason != ReasonRefreshed || decision.PolicyRevision != 7 || decision.SubscriptionVersion != 3 {t.Fatalf("decision = %+v", decision)@@ -98,9 +98,9 @@ func TestGateCachesByWorkspaceAndClonesResults(t *testing.T) {client := newTestClient(t, server.URL, nil)workspaceID := uuid.New()- first := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ first := client.Gate(context.Background(), workspaceID, GateIssueCount)*first.Gate.Limit = 999- second := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ second := client.Gate(context.Background(), workspaceID, GateIssueCount)autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if second.Reason != ReasonCacheFresh || second.Gate.Limit == nil || *second.Gate.Limit != testIssueLimit {t.Fatalf("cached decision = %+v", second)@@ -134,7 +134,7 @@ func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {go func() {defer wg.Done()<-start- results <- client.Gate(context.Background(), workspaceID, GateIssueWindow)+ results <- client.Gate(context.Background(), workspaceID, GateIssueCount)}()}close(start)@@ -181,14 +181,14 @@ func TestCancelledLeaderDoesNotCancelSharedRefresh(t *testing.T) {leaderCtx, cancelLeader := context.WithCancel(context.Background())leaderResult := make(chan Decision, 1)go func() {- leaderResult <- client.Gate(leaderCtx, workspaceID, GateIssueWindow)+ leaderResult <- client.Gate(leaderCtx, workspaceID, GateIssueCount)}()<-requestStartedcancelLeader()followerResult := make(chan Decision, 1)go func() {- followerResult <- client.Gate(context.Background(), workspaceID, GateIssueWindow)+ followerResult <- client.Gate(context.Background(), workspaceID, GateIssueCount)}()close(release)@@ -210,7 +210,7 @@ func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {workspaceID := strings.TrimPrefix(r.URL.Path, "/api/v1/internal/entitlement-policies/")policy := samplePolicy(1, 0, 60, ActionEnforce)limit := limits[workspaceID]- policy.Gates[string(GateIssueWindow)] = wireGate{Action: string(ActionEnforce), Limit: &limit}+ policy.Gates[string(GateIssueCount)] = wireGate{Action: string(ActionEnforce), Limit: &limit}writePolicy(t, w, policy)}))defer server.Close()@@ -220,7 +220,7 @@ func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {workspaceID uuid.UUIDwantLimit int}{{workspaceA, 11}, {workspaceB, 22}, {workspaceA, 11}} {- decision := client.Gate(context.Background(), tc.workspaceID, GateIssueWindow)+ decision := client.Gate(context.Background(), tc.workspaceID, GateIssueCount)if decision.Gate.Limit == nil || *decision.Gate.Limit != tc.wantLimit {t.Fatalf("workspace %s decision = %+v", tc.workspaceID, decision)}@@ -243,14 +243,14 @@ func TestColdFailuresFailOpen(t *testing.T) {{"oversized response", bodyHandler(http.StatusOK, strings.Repeat("x", maxResponseBodySize+1)), ReasonInvalidPolicy},{"unknown schema", policyHandler(func(p *wirePolicy) { p.SchemaVersion = 2 }), ReasonInvalidPolicy},{"unknown action", policyHandler(func(p *wirePolicy) {- gate := p.Gates[string(GateIssueWindow)]+ gate := p.Gates[string(GateIssueCount)]gate.Action = "future"- p.Gates[string(GateIssueWindow)] = gate+ p.Gates[string(GateIssueCount)] = gate}), ReasonInvalidPolicy},{"cloud observe action", policyHandler(func(p *wirePolicy) {- gate := p.Gates[string(GateIssueWindow)]+ gate := p.Gates[string(GateIssueCount)]gate.Action = string(ActionObserve)- p.Gates[string(GateIssueWindow)] = gate+ p.Gates[string(GateIssueCount)] = gate}), ReasonInvalidPolicy},{"missing gate", policyHandler(func(p *wirePolicy) { delete(p.Gates, string(GateAutopilotRuns)) }), ReasonInvalidPolicy},{"excessive TTL", policyHandler(func(p *wirePolicy) { p.ValidForSeconds = 301 }), ReasonInvalidPolicy},@@ -270,7 +270,7 @@ func TestColdFailuresFailOpen(t *testing.T) {server := httptest.NewServer(tt.handler)defer server.Close()client := newTestClient(t, server.URL, nil)- decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)+ decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)if decision.Gate.Action != ActionOff || decision.Reason != tt.wantReason {t.Fatalf("decision = %+v", decision)}@@ -301,7 +301,7 @@ func TestTimeoutFailsOpenWithinIndependentBound(t *testing.T) {client.timeout = 20 * time.Millisecondstarted := time.Now()- decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)+ decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -323,7 +323,7 @@ func TestInternalPolicyClientDoesNotFollowRedirect(t *testing.T) {defer origin.Close()client := newTestClient(t, origin.URL, nil)- decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)+ decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -345,7 +345,7 @@ func TestFastFailuresAreRateLimitedPerWorkspace(t *testing.T) {workspaceID := uuid.New()for range 2 {- decision := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ decision := client.Gate(context.Background(), workspaceID, GateIssueCount)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -354,7 +354,7 @@ func TestFastFailuresAreRateLimitedPerWorkspace(t *testing.T) {t.Fatalf("HTTP calls during retry suppression = %d, want 1", calls.Load())}clock = clock.Add(defaultFailureRetry + time.Millisecond)- _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)+ _ = client.Gate(context.Background(), workspaceID, GateIssueCount)if calls.Load() != 2 {t.Fatalf("HTTP calls after retry suppression = %d, want 2", calls.Load())}@@ -376,11 +376,11 @@ func TestObserverRecordsCacheRefreshDecisionAndDegradation(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)- _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)+ _ = client.Gate(context.Background(), workspaceID, GateIssueCount)+ _ = client.Gate(context.Background(), workspaceID, GateIssueCount)fail.Store(true)clock = clock.Add(6 * time.Second)- _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)+ _ = client.Gate(context.Background(), workspaceID, GateIssueCount)cache, refresh, decisions, _ := observer.snapshot()if strings.Join(cache, ",") != "miss,hit,expired" {@@ -389,7 +389,7 @@ func TestObserverRecordsCacheRefreshDecisionAndDegradation(t *testing.T) {if strings.Join(refresh, ",") != "ok,5xx" {t.Fatalf("refresh observations = %v", refresh)}- if strings.Join(decisions, ",") != "issue_window/enforce/refreshed,issue_window/enforce/cache_fresh,issue_window/observe/stale" {+ if strings.Join(decisions, ",") != "issue_count/enforce/refreshed,issue_count/enforce/cache_fresh,issue_count/observe/stale" {t.Fatalf("decision observations = %v", decisions)}}@@ -414,18 +414,18 @@ func TestExpiredPolicyNeverEnforcesAndIgnoresCloudClock(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- fresh := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ fresh := client.Gate(context.Background(), workspaceID, GateIssueCount)if fresh.Gate.Action != ActionEnforce {t.Fatalf("fresh = %+v", fresh)}fail.Store(true)clock = clock.Add(6 * time.Second)- stale := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ stale := client.Gate(context.Background(), workspaceID, GateIssueCount)if stale.Gate.Action != ActionObserve || stale.Gate.Limit == nil || *stale.Gate.Limit != testIssueLimit || stale.Reason != ReasonStale {t.Fatalf("stale = %+v", stale)}clock = clock.Add(10 * time.Second)- expired := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ expired := client.Gate(context.Background(), workspaceID, GateIssueCount)if expired.Gate.Action != ActionOff || expired.Reason != ReasonUnavailable {t.Fatalf("expired = %+v", expired)}@@ -450,12 +450,12 @@ func TestSubscriptionVersionSwitchReplacesExpiredSnapshot(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionEnforce {+ if got := client.Gate(context.Background(), workspaceID, GateIssueCount); got.Gate.Action != ActionEnforce {t.Fatalf("initial = %+v", got)}subscriptionVersion.Store(2)clock = clock.Add(6 * time.Second)- got := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ got := client.Gate(context.Background(), workspaceID, GateIssueCount)if got.Gate.Action != ActionOff || got.PolicyRevision != 1 || got.SubscriptionVersion != 2 || got.Reason != ReasonRefreshed {t.Fatalf("switched = %+v", got)}@@ -476,7 +476,7 @@ func TestSubscriptionVersionRegressionCannotOverwriteWorkspaceCache(t *testing.Tclient.now = func() time.Time { return clock }workspaceID := uuid.New()- initial := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ initial := client.Gate(context.Background(), workspaceID, GateIssueCount)if initial.Gate.Action != ActionEnforce {t.Fatalf("initial = %+v", initial)}@@ -484,7 +484,7 @@ func TestSubscriptionVersionRegressionCannotOverwriteWorkspaceCache(t *testing.Tpolicy = samplePolicy(1, 3, 5, ActionOff)mu.Unlock()clock = clock.Add(6 * time.Second)- regressed := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ regressed := client.Gate(context.Background(), workspaceID, GateIssueCount)if regressed.Gate.Action != ActionObserve || regressed.PolicyRevision != 1 || regressed.SubscriptionVersion != 4 {t.Fatalf("regressed = %+v", regressed)}@@ -508,19 +508,19 @@ func TestSubscriptionVersionRegressionIsAcceptedAfterStaleGrace(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- initial := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ initial := client.Gate(context.Background(), workspaceID, GateIssueCount)if initial.SubscriptionVersion != 2 || initial.Reason != ReasonRefreshed {t.Fatalf("initial = %+v", initial)}subscriptionVersion.Store(1)clock = clock.Add(71 * time.Second)- recovered := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ recovered := client.Gate(context.Background(), workspaceID, GateIssueCount)if recovered.SubscriptionVersion != 1 || recovered.Reason != ReasonRefreshed {t.Fatalf("recovered = %+v", recovered)}clock = clock.Add(defaultFailureRetry + time.Millisecond)- cached := client.Gate(context.Background(), workspaceID, GateIssueWindow)+ cached := client.Gate(context.Background(), workspaceID, GateIssueCount)if cached.SubscriptionVersion != 1 || cached.Reason != ReasonCacheFresh || calls.Load() != 2 {t.Fatalf("cached = %+v, HTTP calls = %d", cached, calls.Load())}@@ -538,7 +538,7 @@ func TestInvalidWorkspaceAndUnknownGateDoNotFetch(t *testing.T) {workspaceID uuid.UUIDgate GateNamereason Reason- }{{uuid.Nil, GateIssueWindow, ReasonInvalidWorkspace}, {uuid.New(), GateName("future_gate"), ReasonUnknownGate}}+ }{{uuid.Nil, GateIssueCount, ReasonInvalidWorkspace}, {uuid.New(), GateName("future_gate"), ReasonUnknownGate}}for _, tt := range tests {decision := client.Gate(context.Background(), tt.workspaceID, tt.gate)if decision.Gate.Action != ActionOff || decision.Reason != tt.reason {@@ -582,7 +582,7 @@ func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, isValidUntil: time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC),ValidForSeconds: validForSeconds,Gates: map[string]wireGate{- string(GateIssueWindow): issueGate,+ string(GateIssueCount): issueGate,string(GateAutopilotRuns): {Action: string(ActionEnforce), Limit: &autopilotLimit,PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,diff --git a/server/internal/entitlement/entitlementtest/stub_test.go b/server/internal/entitlement/entitlementtest/stub_test.goindex 3f45daa9e0..30400ed5f4 100644--- a/server/internal/entitlement/entitlementtest/stub_test.go+++ b/server/internal/entitlement/entitlementtest/stub_test.go@@ -12,20 +12,20 @@ func TestStubIsWorkspaceScopedAndDefaultsOff(t *testing.T) {stub := New()workspaceA, workspaceB := uuid.New(), uuid.New()limit := 7- stub.Set(workspaceA, entitlement.GateIssueWindow, entitlement.Decision{+ stub.Set(workspaceA, entitlement.GateIssueCount, entitlement.Decision{Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},})- first := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueWindow)+ first := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueCount)if first.Gate.Action != entitlement.ActionEnforce || first.Gate.Limit == nil || *first.Gate.Limit != 7 || first.Reason != entitlement.ReasonStub {t.Fatalf("configured = %+v", first)}*first.Gate.Limit = 99- second := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueWindow)+ second := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueCount)if second.Gate.Limit == nil || *second.Gate.Limit != 7 {t.Fatalf("stub leaked mutable decision: %+v", second)}- missing := stub.Gate(context.Background(), workspaceB, entitlement.GateIssueWindow)+ missing := stub.Gate(context.Background(), workspaceB, entitlement.GateIssueCount)if missing.Gate.Action != entitlement.ActionOff || missing.Reason != entitlement.ReasonStub {t.Fatalf("missing = %+v", missing)}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex 73ff6655ba..af59c2ec84 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -12,13 +12,13 @@ const SchemaVersion = 1type GateName stringconst (- GateIssueWindow GateName = "issue_window"+ GateIssueCount GateName = "issue_count"GateAutopilotRuns GateName = "autopilot_runs")func (n GateName) valid() bool {switch n {- case GateIssueWindow, GateAutopilotRuns:+ case GateIssueCount, GateAutopilotRuns:return truedefault:return false@@ -68,7 +68,7 @@ type Decision struct {CloudValidUntil time.Time}-// Provider is the only interface future issue-window and autopilot consumers+// Provider is the only interface issue-count and autopilot consumers// need. It deliberately has no error return: every failure is represented by a// fail-open Decision with ActionOff (or ActionObserve for a bounded stale// snapshot that can no longer enforce).diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex de25909287..2ffd5c7d32 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -83,7 +83,9 @@ type AutopilotQuotaUsageResponse struct {Action string `json:"action"`Used *int64 `json:"used"`Reserved *int64 `json:"reserved"`+ Total *int64 `json:"total"`Limit *int64 `json:"limit"`+ Reached *bool `json:"reached"`PeriodStart *string `json:"period_start"`PeriodEnd *string `json:"period_end"`ResetAt *string `json:"reset_at"`@@ -2246,7 +2248,8 @@ func (h *Handler) GetAutopilotQuotaUsage(w http.ResponseWriter, r *http.Request)resp := AutopilotQuotaUsageResponse{Action: "off"}if usage.Enabled {resp.Action = usage.Action- resp.Used, resp.Reserved, resp.Limit = usage.Used, usage.Reserved, usage.Limit+ resp.Used, resp.Reserved, resp.Total = usage.Used, usage.Reserved, usage.Total+ resp.Limit, resp.Reached = usage.Limit, usage.Reachedresp.BlockedCounts = usage.BlockedCountsif usage.PeriodStart != nil {v := usage.PeriodStart.UTC().Format(time.RFC3339)diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.goindex edda4265e3..da1f3208d7 100644--- a/server/internal/handler/cloud_billing.go+++ b/server/internal/handler/cloud_billing.go@@ -49,7 +49,6 @@ const stripeSignatureHeader = "Stripe-Signature"const idempotencyKeyHeader = "Idempotency-Key"const maxCloudSubscriptionIdempotencyKeyLength = 255const maxCloudSubscriptionSeatPurchaseIdempotencyKeyLength = 200-const maxCloudSubscriptionSeats = 10_000type cloudSubscriptionCheckoutRequest struct {Interval string `json:"interval"`@@ -79,9 +78,9 @@ type cloudSubscriptionSeatPurchaseRequest struct {}// requireCloudSubscriptionWorkspace is the handler-level backstop behind the-// router's RequireWorkspaceMember / RequireWorkspaceRole middleware. Keeping-// the check here makes a future route refactor fail closed instead of exposing-// a workspace billing write without its tenant/role guard.+// router's membership and role middleware. Local roles are a cheap+// defense-in-depth guard; Cloud still performs the authoritative authorization+// before every billing mutation.func (h *Handler) requireCloudSubscriptionWorkspace(w http.ResponseWriter, r *http.Request, roles ...string) (string, string, bool) {if isMachineCredentialActor(r) {writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")@@ -159,18 +158,6 @@ func requireCloudSubscriptionIdempotencyKey(w http.ResponseWriter, r *http.Requereturn key, true}-// GetCloudWorkspaceEntitlements forwards the active workspace to cloud's-// resolved entitlement endpoint. Any workspace member may read this snapshot;-// cloud independently verifies the stamped X-User-ID against its read-only-// product database.-func (h *Handler) GetCloudWorkspaceEntitlements(w http.ResponseWriter, r *http.Request) {- workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r)- if !ok {- return- }- h.proxyCloudSubscription(w, r, http.MethodGet, "/api/v1/entitlements/"+workspaceID, userID, nil, nil)-}-// GetCloudWorkspaceSubscriptionSummary forwards cloud's Billing-page read:// the resolved entitlement plus local subscription facts (seats, interval,// cancellation and grace state, Portal availability). Member-readable like@@ -284,8 +271,8 @@ func (h *Handler) PreviewCloudWorkspaceSubscriptionSeatPurchase(w http.ResponseWwriteError(w, http.StatusBadRequest, "invalid request body")return}- if in.AdditionalSeats < 1 || in.AdditionalSeats > maxCloudSubscriptionSeats {- writeError(w, http.StatusBadRequest, "additional_seats must be within 1..10000")+ if in.AdditionalSeats < 1 {+ writeError(w, http.StatusBadRequest, "additional_seats must be positive")return}upstreamBody, err := json.Marshal(in)@@ -315,8 +302,6 @@ func (h *Handler) PurchaseCloudWorkspaceSubscriptionSeats(w http.ResponseWriter,return}if in.AdditionalSeats < 1 || in.ExpectedCurrentSeats < 1 ||- in.AdditionalSeats > maxCloudSubscriptionSeats ||- in.ExpectedCurrentSeats > maxCloudSubscriptionSeats-in.AdditionalSeats ||in.ExpectedPurchaseVersion < 1 || in.AcceptedProrationAmount < 0 || !isASCIICurrency(in.Currency) {writeError(w, http.StatusBadRequest, "invalid seat purchase confirmation")returndiff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.goindex 566e552728..5c6d065416 100644--- a/server/internal/handler/cloud_billing_test.go+++ b/server/internal/handler/cloud_billing_test.go@@ -257,9 +257,8 @@ func TestCloudWorkspaceSubscriptionsDisabledByDefault(t *testing.T) {withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, false)reads := map[string]func(http.ResponseWriter, *http.Request){- "/api/cloud-subscriptions/entitlements": testHandler.GetCloudWorkspaceEntitlements,- "/api/cloud-subscriptions/summary": testHandler.GetCloudWorkspaceSubscriptionSummary,- "/api/cloud-subscriptions/prices": testHandler.GetCloudWorkspaceSubscriptionPrices,+ "/api/cloud-subscriptions/summary": testHandler.GetCloudWorkspaceSubscriptionSummary,+ "/api/cloud-subscriptions/prices": testHandler.GetCloudWorkspaceSubscriptionPrices,}for path, invoke := range reads {t.Run(path, func(t *testing.T) {@@ -292,15 +291,6 @@ func TestCloudWorkspaceSubscriptionReadAndWritesUseScopedPaths(t *testing.T) {wantPath stringinvoke func(http.ResponseWriter, *http.Request)}{- {- name: "member reads entitlements",- method: http.MethodGet,- path: "/api/cloud-subscriptions/entitlements",- role: "member",- wantStatus: http.StatusOK,- wantPath: "/api/v1/entitlements/" + testWorkspaceID,- invoke: testHandler.GetCloudWorkspaceEntitlements,- },{name: "member reads billing summary",method: http.MethodGet,@@ -561,7 +551,7 @@ func TestCloudWorkspaceSeatPurchasePreviewUsesAuthoritativePath(t *testing.T) {proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: []byte(`{"resulting_seats":7}`)}}useCloudRuntimeProxy(t, proxy)req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/seats/purchase-preview", map[string]any{- "additional_seats": 2, "workspace_id": "00000000-0000-0000-0000-000000000002", "target_seats": 999,+ "additional_seats": 10_001, "workspace_id": "00000000-0000-0000-0000-000000000002", "target_seats": 999,}), "owner")w := httptest.NewRecorder()testHandler.PreviewCloudWorkspaceSubscriptionSeatPurchase(w, req)@@ -569,12 +559,12 @@ func TestCloudWorkspaceSeatPurchasePreviewUsesAuthoritativePath(t *testing.T) {if w.Code != http.StatusOK || proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/seats/purchase-preview" {t.Fatalf("status=%d path=%s body=%s", w.Code, proxy.req.Path, w.Body.String())}- if string(proxy.req.Body) != `{"additional_seats":2}` {+ if string(proxy.req.Body) != `{"additional_seats":10001}` {t.Fatalf("upstream body=%s", proxy.req.Body)}}-func TestCloudWorkspaceSeatPurchaseRejectsInvalidOrUnauthorizedRequests(t *testing.T) {+func TestCloudWorkspaceSeatPurchaseRejectsInvalidRequests(t *testing.T) {withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)tests := []struct {name string@@ -582,8 +572,8 @@ func TestCloudWorkspaceSeatPurchaseRejectsInvalidOrUnauthorizedRequests(t *testibody map[string]anyheader string}{- {name: "member", role: "member", body: map[string]any{"additional_seats": 1}},- {name: "absolute overflow", role: "owner", body: map[string]any{"additional_seats": 2, "expected_current_seats": 9999, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "usd", "idempotency_key": "key"}},+ {name: "missing confirmation fields", role: "owner", body: map[string]any{"additional_seats": 1}},+ {name: "non-positive current seats", role: "owner", body: map[string]any{"additional_seats": 2, "expected_current_seats": 0, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "usd", "idempotency_key": "key"}},{name: "bad currency", role: "owner", body: map[string]any{"additional_seats": 1, "expected_current_seats": 5, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "u$d", "idempotency_key": "key"}},{name: "long key", role: "owner", body: map[string]any{"additional_seats": 1, "expected_current_seats": 5, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "usd"}, header: strings.Repeat("a", 201)},}@@ -597,10 +587,7 @@ func TestCloudWorkspaceSeatPurchaseRejectsInvalidOrUnauthorizedRequests(t *testi}w := httptest.NewRecorder()testHandler.PurchaseCloudWorkspaceSubscriptionSeats(w, req)- if tc.role == "member" && w.Code != http.StatusForbidden {- t.Fatalf("status=%d body=%s", w.Code, w.Body.String())- }- if tc.role != "member" && w.Code != http.StatusBadRequest {+ if w.Code != http.StatusBadRequest {t.Fatalf("status=%d body=%s", w.Code, w.Body.String())}if proxy.called {diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 8d5a2fbbb2..fe60d3ad68 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -22,7 +22,6 @@ 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"@@ -1980,36 +1979,6 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu// Build response with fresh agent data (name + skills + custom_env + custom_args).resp = taskToResponse(*task, runtimeWorkspaceID)var issueNumber int32- 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 4cf31b692c..cafc9e289c 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -173,13 +173,9 @@ type DaemonPendingWorkNotifier interface {}type Handler struct {- 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 *issueTableWindowCache+ Queries *db.Queries+ DB dbExecutor+ TxStarter txStarterHub *realtime.HubDaemonHub *daemonws.HubDaemonProfileRefresh RuntimeProfileRefreshNotifier@@ -190,7 +186,7 @@ type Handler struct {IssueService *service.IssueServiceAutopilotService *service.AutopilotService// Entitlements supplies workspace-scoped commercial gates. A nil provider- // preserves the self-hosted and pre-rollout behavior without extra reads.+ // preserves self-hosted behavior without extra reads.Entitlements entitlement.Provider// SeatCapacity executes Cloud's pre-purchased human-seat protocol. Nil or// disabled preserves self-hosted behavior.@@ -986,9 +982,6 @@ 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}@@ -1012,9 +1005,6 @@ 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}@@ -1186,8 +1176,5 @@ 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 a0f73e3d69..f527b2f5f7 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -3,13 +3,11 @@ 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"@@ -120,31 +118,9 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {return}- 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))+ resp := make([]InboxItemResponse, len(items))+ for i, item := range items {+ resp[i] = inboxRowToResponse(item)}writeJSON(w, http.StatusOK, resp)@@ -180,31 +156,9 @@ func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {return}- 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))+ resp := make([]InboxItemResponse, len(items))+ for i, item := range items {+ resp[i] = archivedInboxRowToResponse(item)}writeJSON(w, http.StatusOK, resp)@@ -349,33 +303,15 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {return}- 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),- })- }+ 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})}@@ -405,122 +341,17 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {return}- 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{+ resp := make([]InboxWorkspaceUnreadResponse, len(rows))+ for i, row := range rows {+ resp[i] = InboxWorkspaceUnreadResponse{WorkspaceID: uuidToString(row.WorkspaceID),- Count: count,- })+ Count: row.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 bf781e47af..62d7b8c05d 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -21,7 +21,6 @@ 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"@@ -600,7 +599,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, creationWindowLimit *int64) (string, []any) {+func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool) (string, []any) {// Lowercase in Go so SQL only needs LOWER() on the column side.phrase = strings.ToLower(phrase)for i, t := range terms {@@ -684,10 +683,6 @@ 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.@@ -897,13 +892,8 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {}terms := splitSearchTerms(q)queryNum, hasNum := parseQueryNumber(q)- policy, windowEnabled := h.issueWindowPolicy(ctx, wsUUID)- var creationWindowLimit *int64- if windowEnabled && policy.action == entitlement.ActionEnforce {- creationWindowLimit = &policy.limit- }- sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, creationWindowLimit)+ sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed)// Fill placeholder args: $4 = workspace_id, last two = limit, offsetargs[3] = wsUUIDargs[len(args)-2] = limit@@ -969,13 +959,6 @@ 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)@@ -1040,7 +1023,6 @@ 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@@ -1140,26 +1122,6 @@ 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))@@ -1471,9 +1433,6 @@ 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 ")@@ -1571,9 +1530,6 @@ 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 {@@ -1768,7 +1724,6 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {if !ok {return}- windowPolicy, windowEnabled := h.issueWindowPolicy(ctx, wsUUID)limit := 50offset := 0@@ -2015,9 +1970,6 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {))}}- if windowEnabled {- where = appendIssueWindow(where, addArg, windowPolicy, "$1", "i")- }sortCol := "position"sortIsExpr := false@@ -2181,9 +2133,6 @@ 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@@ -2282,27 +2231,6 @@ 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 {@@ -2389,27 +2317,6 @@ 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 {@@ -2444,66 +2351,23 @@ 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"`- 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,- })+ }+ resp := make([]progressEntry, len(rows))+ for i, row := range rows {+ resp[i] = progressEntry{+ ParentIssueID: uuidToString(row.ParentIssueID),+ Total: row.Total,+ Done: row.Done,}}writeJSON(w, http.StatusOK, map[string]any{@@ -3174,6 +3038,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {"the target status was archived while this request was in flight; reload the status list and retry")return}+ if writeIssueLimitReached(w, err) {+ return+ }if err != nil {slog.Warn("create issue failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)writeError(w, http.StatusInternalServerError, "failed to create issue: "+err.Error())diff --git a/server/internal/handler/issue_limit.go b/server/internal/handler/issue_limit.gonew file mode 100644index 0000000000..75547488c1--- /dev/null+++ b/server/internal/handler/issue_limit.go@@ -0,0 +1,49 @@+package handler++import (+ "errors"+ "net/http"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/service"+)++type IssueLimitUsageResponse struct {+ Used int64 `json:"used"`+ Limit int64 `json:"limit"`+}++// GetIssueLimitUsage returns local usage for a currently enforced Cloud limit.+// Limit mode comes only from Cloud's subscription summary; this endpoint never+// infers unlimited access from cache or refresh reasons.+func (h *Handler) GetIssueLimitUsage(w http.ResponseWriter, r *http.Request) {+ workspaceID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")+ if !ok {+ return+ }+ policy := service.ResolveIssueCountPolicy(r.Context(), h.Entitlements, workspaceID)+ if policy.Action != entitlement.ActionEnforce {+ w.WriteHeader(http.StatusNoContent)+ return+ }+ used, err := service.CountIssueUsage(r.Context(), h.Queries, workspaceID, policy)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load issue limit usage")+ return+ }+ writeJSON(w, http.StatusOK, IssueLimitUsageResponse{Used: used, Limit: policy.Limit})+}++func writeIssueLimitReached(w http.ResponseWriter, err error) bool {+ var limitErr *service.IssueLimitReachedError+ if !errors.As(err, &limitErr) {+ return false+ }+ writeJSON(w, http.StatusPaymentRequired, map[string]any{+ "code": "issue_limit_reached",+ "error": "workspace has reached its issue limit",+ "limit": limitErr.Limit,+ "policy_revision": limitErr.PolicyRevision,+ })+ return true+}diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 5a20e1fa30..8e5259892d 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -9,7 +9,6 @@ import ("errors""fmt""io"- "log/slog""net/http""sort""strconv"@@ -18,8 +17,6 @@ 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")@@ -28,9 +25,6 @@ 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) {@@ -53,44 +47,9 @@ 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{@@ -446,13 +405,6 @@ 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}@@ -681,21 +633,6 @@ 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 3da54a0bc7..6bda9b8ab9 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -479,9 +479,6 @@ 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.godeleted file mode 100644index 83daa4b1ed..0000000000--- a/server/internal/handler/issue_window.go+++ /dev/null@@ -1,271 +0,0 @@-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.godeleted file mode 100644index 00b64e9226..0000000000--- a/server/internal/handler/issue_window_test.go+++ /dev/null@@ -1,454 +0,0 @@-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/onboarding_shim.go b/server/internal/handler/onboarding_shim.goindex 3fc66b4883..b68ece8894 100644--- a/server/internal/handler/onboarding_shim.go+++ b/server/internal/handler/onboarding_shim.go@@ -34,6 +34,7 @@ import ("github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid""github.com/multica-ai/multica/server/pkg/protocol"@@ -163,6 +164,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requreturn}req.WorkspaceID = uuidToString(wsUUID)+ issueCountPolicy := service.ResolveIssueCountPolicy(r.Context(), h.Entitlements, wsUUID)tx, err := h.TxStarter.Begin(r.Context())if err != nil {@@ -246,8 +248,11 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requ}issueCreated := falseif !foundIssue {- issueNumber, err := qtx.IncrementIssueCounter(r.Context(), wsUUID)+ issueNumber, err := service.AllocateIssueNumber(r.Context(), qtx, wsUUID, issueCountPolicy)if err != nil {+ if writeIssueLimitReached(w, err) {+ return+ }writeError(w, http.StatusInternalServerError, "failed to allocate issue number")return}@@ -372,6 +377,7 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Rereturn}req.WorkspaceID = uuidToString(wsUUID)+ issueCountPolicy := service.ResolveIssueCountPolicy(r.Context(), h.Entitlements, wsUUID)tx, err := h.TxStarter.Begin(r.Context())if err != nil {@@ -410,8 +416,11 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Reif foundIssue {issue = existing} else {- issueNumber, err := qtx.IncrementIssueCounter(r.Context(), wsUUID)+ issueNumber, err := service.AllocateIssueNumber(r.Context(), qtx, wsUUID, issueCountPolicy)if err != nil {+ if writeIssueLimitReached(w, err) {+ return+ }writeError(w, http.StatusInternalServerError, "failed to allocate issue number")return}diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex 63798640a8..b920eaaab7 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -240,9 +240,6 @@ func (h *Handler) pluginIssueForUser(w http.ResponseWriter, r *http.Request, calpublicapiv1.WriteProblem(w, r, http.StatusNotFound, "not_found", "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 5967f19209..a3947d2736 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, nil)+ query, args := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false)// 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, nil)+ query, args := buildSearchQuery("Foo Bar", []string{"Foo", "Bar"}, 0, false, false)// 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, nil)+ query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false)_ = 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, nil)+ query, _ := buildSearchQuery("test", []string{"test"}, 0, false, true)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, nil)+ query, args := buildSearchQuery("100%", []string{"100%"}, 0, false, false)_ = 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, nil)+ query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false)// 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, nil)+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)// 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, nil)+ query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)// 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, nil)+ singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)// 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, nil)+ multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)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, nil)+ query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed)return query}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 0b91f0618d..18ca775a79 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -833,6 +833,9 @@ func (h *Handler) createAgentCommentSubIssue(w http.ResponseWriter, r *http.Requ}func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limits service.SourceContextLimitUsage) {+ if writeIssueLimitReached(w, err) {+ return+ }status := http.StatusInternalServerErrorcode := "source_context_capture_failed"message := "failed to capture source context"diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex a3e67dc721..6e52e2ecba 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -49,7 +49,6 @@ type BusinessMetrics struct {entitlementDecision *prometheus.CounterVecentitlementVersionRegression prometheus.CounterautopilotQuotaDecision *prometheus.CounterVec- issueWindowDecision *prometheus.CounterVecactiveMu sync.MutexactiveTasks map[string]activeTaskLabels@@ -233,10 +232,6 @@ 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(),}@@ -276,7 +271,6 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.entitlementDecision,m.entitlementVersionRegression,m.autopilotQuotaDecision,- m.issueWindowDecision,}, m.events.collectors()...)}@@ -324,18 +318,6 @@ 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 2444144cc7..70fbe8ee7d 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -182,7 +182,6 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")m.RecordEntitlementVersionRegression()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 18bce2d528..3694cf4f21 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -34,7 +34,6 @@ const (labelOp = "op"labelGate = "gate"labelOutcome = "outcome"- labelSurface = "surface")var businessMetricLabels = map[string][]string{@@ -99,7 +98,6 @@ var businessMetricLabels = map[string][]string{"multica_entitlement_decision_total": {labelGate, labelAction, labelReason},"multica_entitlement_version_regression_total": {},"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/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 0da3484b11..427beba85a 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -643,6 +643,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopiif err != nil {return fmt.Errorf("resolve leader: %w", err)}+ issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, ap.WorkspaceID)tx, err := s.TxStarter.Begin(ctx)if err != nil {@@ -674,9 +675,16 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopireturn &errDispatchSkipped{reason: "recent duplicate autopilot issue: " + util.UUIDToString(duplicate.ID), code: dispatch.ReasonAlreadyActive}}- issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)+ issueNumber, err := AllocateIssueNumber(ctx, qtx, ap.WorkspaceID, issueCountPolicy)if err != nil {- return fmt.Errorf("increment issue counter: %w", err)+ var limitErr *IssueLimitReachedError+ if errors.As(err, &limitErr) {+ return &errDispatchSkipped{+ reason: "workspace has reached its issue limit",+ code: dispatch.ReasonIssueLimitReached,+ }+ }+ return fmt.Errorf("allocate issue number: %w", err)}newPosition, err := issueposition.NextTopPosition(ctx, tx, ap.WorkspaceID, "todo")diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.goindex 017a0b5b04..1caa43e86b 100644--- a/server/internal/service/autopilot_quota.go+++ b/server/internal/service/autopilot_quota.go@@ -37,11 +37,14 @@ func (e *AutopilotQuotaExceededError) Error() string {// AutopilotQuotaUsage is the workspace-scoped, policy-neutral API model.// A disabled/malformed decision returns Enabled=false and leaves all facts nil.type AutopilotQuotaUsage struct {- Enabled bool- Action string- Used *int64- Reserved *int64- Limit *int64+ Enabled bool+ Action string+ Used *int64+ Reserved *int64+ Total *int64+ Limit *int64+ // Reached is nil while observing because observe never rejects a run.+ Reached *boolPeriodStart *time.TimePeriodEnd *time.TimeResetAt *time.Time@@ -314,9 +317,16 @@ func (s *AutopilotService) AutopilotQuotaUsage(ctx context.Context, workspaceIDblockedCounts = make(map[string]int64)}}+ total := period.UsedCount + period.ReservedCount+ var reached *bool+ if policy.action == entitlement.ActionEnforce {+ value := total >= policy.limit+ reached = &value+ }return AutopilotQuotaUsage{Enabled: true, Action: string(policy.action),- Used: &period.UsedCount, Reserved: &period.ReservedCount, Limit: &policy.limit,+ Used: &period.UsedCount, Reserved: &period.ReservedCount, Total: &total,+ Limit: &policy.limit, Reached: reached,PeriodStart: &policy.periodStart, PeriodEnd: &policy.periodEnd, ResetAt: &policy.resetAt,BlockedCounts: blockedCounts,}, nildiff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.goindex 00f25b0d73..321e05b554 100644--- a/server/internal/service/autopilot_quota_test.go+++ b/server/internal/service/autopilot_quota_test.go@@ -282,7 +282,7 @@ func TestAutopilotQuotaObserveToEnforceAndOffFinalization(t *testing.T) {runs = append(runs, run)}usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)- if err != nil || usage.Action != string(entitlement.ActionObserve) || *usage.Reserved != 2 {+ if err != nil || usage.Action != string(entitlement.ActionObserve) || *usage.Reserved != 2 || usage.Reached != nil {t.Fatalf("observe usage = %+v, %v; want two reservations", usage, err)}if got := metrics.count("observe", "api", "would_block"); got != 1 {diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 7224b5652a..2494e2ae78 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/dispatch"+ "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition"@@ -40,6 +41,9 @@ type IssueService struct {// Metrics as "PostHog only", so leaving it unset is safe.Metrics *obsmetrics.BusinessMetricsTaskService *TaskService+ // Entitlements supplies Cloud's effective issue-count instruction. Nil is+ // the self-hosted unlimited path.+ Entitlements entitlement.Provider}func NewIssueService(q *db.Queries, tx TxStarter, bus *events.Bus, ac analytics.Client, ts *TaskService) *IssueService {@@ -208,6 +212,7 @@ type IssueCreateResult struct {// Caller-owned validation is limited to transport-shaped checks: title// required, RFC3339 date format, assignee pair sanity.func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {+ issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, p.WorkspaceID)tx, err := s.TxStarter.Begin(ctx)if err != nil {return IssueCreateResult{}, fmt.Errorf("begin tx: %w", err)@@ -310,9 +315,9 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Issreturn IssueCreateResult{DuplicateIssue: &dup}, ErrActiveDuplicate}- issueNumber, err := qtx.IncrementIssueCounter(ctx, p.WorkspaceID)+ issueNumber, err := AllocateIssueNumber(ctx, qtx, p.WorkspaceID, issueCountPolicy)if err != nil {- return IssueCreateResult{}, fmt.Errorf("increment counter: %w", err)+ return IssueCreateResult{}, fmt.Errorf("allocate issue number: %w", err)}// New issues sort to the top of their (workspace, status) column fordiff --git a/server/internal/service/issue_limit.go b/server/internal/service/issue_limit.gonew file mode 100644index 0000000000..1153638cf2--- /dev/null+++ b/server/internal/service/issue_limit.go@@ -0,0 +1,110 @@+package service++import (+ "context"+ "fmt"+ "math"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// IssueLimitReachedError carries Cloud's effective limit and policy revision+// to transport adapters. It never includes a plan name or subscription state.+type IssueLimitReachedError struct {+ Limit int64+ PolicyRevision int64+}++func (e *IssueLimitReachedError) Error() string {+ return fmt.Sprintf("workspace issue limit reached: limit %d", e.Limit)+}++// IssueCountPolicy is the validated mechanical instruction received from+// Cloud. Resolve it before opening a database transaction so a network call+// never holds product-database locks.+type IssueCountPolicy struct {+ Action entitlement.Action+ Limit int64+ PolicyRevision int64+}++func ResolveIssueCountPolicy(ctx context.Context, provider entitlement.Provider, workspaceID pgtype.UUID) IssueCountPolicy {+ if provider == nil || !workspaceID.Valid {+ return IssueCountPolicy{Action: entitlement.ActionOff}+ }+ decision := provider.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateIssueCount)+ policy := IssueCountPolicy{+ Action: decision.Gate.Action,+ PolicyRevision: decision.PolicyRevision,+ }+ if decision.Gate.Limit != nil {+ policy.Limit = int64(*decision.Gate.Limit)+ }+ switch policy.Action {+ case entitlement.ActionOff:+ policy.Limit = 0+ case entitlement.ActionEnforce:+ if policy.Limit > 0 {+ return policy+ }+ policy.Action = entitlement.ActionOff+ policy.Limit = 0+ default:+ policy.Action = entitlement.ActionOff+ policy.Limit = 0+ }+ return policy+}++// AllocateIssueNumber serializes creates on the workspace row, then checks the+// current number of issue rows inside the same transaction. The caller must+// roll the transaction back on IssueLimitReachedError; that also rolls back+// the counter increment. Deleting an issue frees capacity because+// issue_counter is deliberately not used as quota usage.+func AllocateIssueNumber(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, policy IssueCountPolicy) (int32, error) {+ number, err := q.IncrementIssueCounter(ctx, workspaceID)+ if err != nil {+ return 0, err+ }+ if policy.Action != entitlement.ActionEnforce {+ return number, nil+ }+ used, err := q.CountIssuesUpTo(ctx, db.CountIssuesUpToParams{+ WorkspaceID: workspaceID,+ Limit: policy.Limit,+ })+ if err != nil {+ return 0, err+ }+ if used >= policy.Limit {+ return 0, &IssueLimitReachedError{Limit: policy.Limit, PolicyRevision: policy.PolicyRevision}+ }+ return number, nil+}++// CountIssueUsage performs a bounded read for a limited policy. The returned+// value is exact while below the limit and capped at the limit once the+// workspace is full.+func CountIssueUsage(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, policy IssueCountPolicy) (int64, error) {+ if policy.Action != entitlement.ActionEnforce {+ return 0, nil+ }+ sampleLimit := policy.Limit+ if sampleLimit < math.MaxInt64 {+ sampleLimit+++ }+ sampled, err := q.CountIssuesUpTo(ctx, db.CountIssuesUpToParams{+ WorkspaceID: workspaceID,+ Limit: sampleLimit,+ })+ if err != nil {+ return 0, err+ }+ if sampled > policy.Limit {+ return policy.Limit, nil+ }+ return sampled, nil+}diff --git a/server/internal/service/issue_limit_test.go b/server/internal/service/issue_limit_test.gonew file mode 100644index 0000000000..02ab6c66f2--- /dev/null+++ b/server/internal/service/issue_limit_test.go@@ -0,0 +1,160 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "sync"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type issueLimitProviderFunc func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision++func (f issueLimitProviderFunc) Gate(ctx context.Context, workspaceID uuid.UUID, gate entitlement.GateName) entitlement.Decision {+ return f(ctx, workspaceID, gate)+}++func TestResolveIssueCountPolicyUsesOnlyCloudInstruction(t *testing.T) {+ workspace := uuid.New()+ workspaceID := pgtype.UUID{Bytes: workspace, Valid: true}+ limit := 17++ valid := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(+ func(_ context.Context, gotWorkspace uuid.UUID, gate entitlement.GateName) entitlement.Decision {+ if gotWorkspace != workspace || gate != entitlement.GateIssueCount {+ t.Fatalf("gate request = %s %s", gotWorkspace, gate)+ }+ return entitlement.Decision{+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},+ PolicyRevision: 9,+ Reason: entitlement.ReasonRefreshed,+ }+ }), workspaceID)+ if valid.Action != entitlement.ActionEnforce || valid.Limit != int64(limit) || valid.PolicyRevision != 9 {+ t.Fatalf("valid policy = %+v", valid)+ }++ malformed := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(+ func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return entitlement.Decision{+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce},+ Reason: entitlement.ReasonCacheFresh,+ }+ }), workspaceID)+ if malformed.Action != entitlement.ActionOff {+ t.Fatalf("malformed policy = %+v", malformed)+ }++ observe := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(+ func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return entitlement.Decision{+ Gate: entitlement.Gate{Action: entitlement.ActionObserve, Limit: &limit},+ }+ }), workspaceID)+ if observe.Action != entitlement.ActionOff || observe.Limit != 0 {+ t.Fatalf("observe policy = %+v, want fail-open off", observe)+ }++ disabled := ResolveIssueCountPolicy(context.Background(), nil, workspaceID)+ if disabled.Action != entitlement.ActionOff {+ t.Fatalf("disabled policy = %+v", disabled)+ }+}++func TestIssueCountLimitSerializesConcurrentCreatesAndDeleteFreesCapacity(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ queries := db.New(pool)+ workspaceIDString, userIDString, _, _ := seedAttributionFixture(t, pool)+ workspaceID := util.MustParseUUID(workspaceIDString)+ userID := util.MustParseUUID(userIDString)++ var initialCount int64+ if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`, workspaceID).Scan(&initialCount); err != nil {+ t.Fatalf("count initial issues: %v", err)+ }+ limit := int(initialCount + 1)+ stub := entitlementtest.New()+ stub.Set(uuid.UUID(workspaceID.Bytes), entitlement.GateIssueCount, entitlement.Decision{+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},+ PolicyRevision: 13,+ })+ svc := NewIssueService(queries, pool, nil, nil, nil)+ svc.Entitlements = stub++ create := func(title string) (db.Issue, error) {+ result, err := svc.Create(ctx, IssueCreateParams{+ WorkspaceID: workspaceID,+ Title: title,+ Status: "todo",+ Priority: "none",+ CreatorType: "member",+ CreatorID: userID,+ AllowDuplicate: true,+ }, IssueCreateOpts{})+ return result.Issue, err+ }++ start := make(chan struct{})+ type createResult struct {+ issue db.Issue+ err error+ }+ results := make(chan createResult, 2)+ var wg sync.WaitGroup+ for i := range 2 {+ wg.Add(1)+ go func(index int) {+ defer wg.Done()+ <-start+ issue, err := create(fmt.Sprintf("issue-limit-race-%d", index))+ results <- createResult{issue: issue, err: err}+ }(i)+ }+ close(start)+ wg.Wait()+ close(results)++ var created db.Issue+ createdCount, blockedCount := 0, 0+ for result := range results {+ switch {+ case result.err == nil:+ created = result.issue+ createdCount+++ default:+ var limitErr *IssueLimitReachedError+ if !errors.As(result.err, &limitErr) {+ t.Fatalf("concurrent create: %v", result.err)+ }+ if limitErr.Limit != int64(limit) || limitErr.PolicyRevision != 13 {+ t.Fatalf("limit error = %v", result.err)+ }+ blockedCount+++ }+ }+ if createdCount != 1 || blockedCount != 1 {+ t.Fatalf("created = %d, blocked = %d; want 1 and 1", createdCount, blockedCount)+ }++ var countAtLimit int64+ if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`, workspaceID).Scan(&countAtLimit); err != nil {+ t.Fatalf("count issues at limit: %v", err)+ }+ if countAtLimit != int64(limit) {+ t.Fatalf("issue count = %d, want %d", countAtLimit, limit)+ }+ if err := queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: created.ID, WorkspaceID: workspaceID}); err != nil {+ t.Fatalf("delete admitted issue: %v", err)+ }+ if _, err := create("issue-limit-after-delete"); err != nil {+ t.Fatalf("create after delete: %v", err)+ }+}diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 77f1536248..d8ae97145e 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -170,6 +170,31 @@ func (q *Queries) CountIssues(ctx context.Context, arg CountIssuesParams) (int64return count, err}+const countIssuesUpTo = `-- name: CountIssuesUpTo :one+SELECT COUNT(*)::bigint+FROM (+ SELECT 1+ FROM issue+ WHERE workspace_id = $1+ LIMIT $2::bigint+) bounded_issues+`++type CountIssuesUpToParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Limit int64 `json:"limit"`+}++// Bounded count for issue-limit admission and display. Callers pass only the+// threshold needed for their decision, avoiding a full scan in an oversized+// workspace.+func (q *Queries) CountIssuesUpTo(ctx context.Context, arg CountIssuesUpToParams) (int64, error) {+ row := q.db.QueryRow(ctx, countIssuesUpTo, arg.WorkspaceID, arg.Limit)+ var column_1 int64+ err := row.Scan(&column_1)+ return column_1, err+}+const createIssue = `-- name: CreateIssue :oneINSERT INTO issue (workspace_id, title, description, status, priority,diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 398a06fdc6..247a50d58b 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -558,3 +558,15 @@ UPDATE issueSET first_executed_at = now()WHERE id = $1 AND first_executed_at IS NULLRETURNING id, workspace_id, creator_type, creator_id, first_executed_at;++-- name: CountIssuesUpTo :one+-- Bounded count for issue-limit admission and display. Callers pass only the+-- threshold needed for their decision, avoiding a full scan in an oversized+-- workspace.+SELECT COUNT(*)::bigint+FROM (+ SELECT 1+ FROM issue+ WHERE workspace_id = $1+ LIMIT sqlc.arg('limit')::bigint+) bounded_issues;diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex f006dc7342..e24acc71c6 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, issue_window_restricted+// runtime_cli_timeout, invalid_task_identity//// - 14 agent-side values (with `agent_error.` prefix) produced by// Classify(rawError) when the agent process surfaced an error string.@@ -138,12 +138,6 @@ 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@@ -219,7 +213,7 @@ const (ReasonAgentUnknown Reason = "agent_error.unknown")-// allReasons is the canonical ordered list of the 26 reasons. Order is+// allReasons is the canonical ordered list of the 25 reasons. Order is// stable so callers (e.g. Prometheus collectors that pre-warm series via// AllReasons) can build deterministic label sets across restarts.//@@ -241,7 +235,6 @@ 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 2d4a8720a3..2a5f0eed0c 100644--- a/server/pkg/taskfailure/failure_test.go+++ b/server/pkg/taskfailure/failure_test.go@@ -30,7 +30,6 @@ 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"},@@ -48,7 +47,7 @@ func TestReasonStringWireValues(t *testing.T) {{ReasonAgentUnknown, "agent_error.unknown"},}- if got, want := len(cases), 26; got != want {+ if got, want := len(cases), 25; got != want {t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)}@@ -79,7 +78,6 @@ func TestIsAgentError(t *testing.T) {ReasonSkillBundleUnavailable,ReasonRuntimeCLITimeout,ReasonInvalidTaskIdentity,- ReasonIssueWindowRestricted,}for _, r := range platformSide {if r.IsAgentError() {@@ -120,8 +118,8 @@ func TestAllReasonsContents(t *testing.T) {t.Parallel()got := AllReasons()- if len(got) != 26 {- t.Fatalf("AllReasons() returned %d entries, want 26", len(got))+ if len(got) != 25 {+ t.Fatalf("AllReasons() returned %d entries, want 25", len(got))}seen := make(map[Reason]bool, len(got))@@ -138,8 +136,8 @@ func TestAllReasonsContents(t *testing.T) {}}- if platformCount != 12 {- t.Errorf("AllReasons(): platform-side count = %d, want 12", platformCount)+ if platformCount != 11 {+ t.Errorf("AllReasons(): platform-side count = %d, want 11", platformCount)}if agentCount != 14 {t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)@@ -154,7 +152,7 @@ func TestAllReasonsContents(t *testing.T) {ReasonRuntimeRecovery,ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,- ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity, ReasonIssueWindowRestricted,+ ReasonRuntimeCLITimeout, ReasonInvalidTaskIdentity,ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,ReasonAgentProviderNetwork, ReasonAgentProcessFailure,