Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: Squad-level usage analytics and unified execution avatars (MUL-10009) (#11346)
Jiayuan Zhangc7d0c100a1f6
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex cb6a3bd4d2..ec8c75f079 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -114,10 +114,13 @@ import type {RuntimeUsageByHour,DashboardUsageDaily,DashboardUsageByAgent,+ DashboardUsageBySquad,DashboardAgentRunTime,+ DashboardSquadRunTime,DashboardRunTimeDaily,DashboardFailureDaily,DashboardFailureByAgent,+ DashboardFailureBySquad,RuntimeUpdate,RuntimeModelListRequest,RuntimeLocalSkillListRequest,@@ -360,10 +363,13 @@ import {EMPTY_AGENT_BUILDER_SESSION_LIST,agentBuilderRuntimeSwitchFallback,DashboardAgentRunTimeListSchema,+ DashboardSquadRunTimeListSchema,DashboardRunTimeDailyListSchema,DashboardFailureDailyListSchema,DashboardFailureByAgentListSchema,+ DashboardFailureBySquadListSchema,DashboardUsageByAgentListSchema,+ DashboardUsageBySquadListSchema,DashboardUsageDailyListSchema,EMPTY_APP_CONFIG,EMPTY_ATTACHMENT,@@ -696,6 +702,7 @@ export function parseDashboardHistoryLimit(value: string | null): number | nullexport interface DashboardRequestParams {days?: number;project_id?: string | null;+ squad_id?: string | null;tz?: string;onHistoryLimit?: (limitDays: number | null) => void;}@@ -3154,6 +3161,7 @@ export class ApiClient {const search = new URLSearchParams();if (params.days) search.set("days", String(params.days));if (params.project_id) search.set("project_id", params.project_id);+ if (params.squad_id) search.set("squad_id", params.squad_id);if (params.tz) search.set("tz", params.tz);const res = await this.fetchRaw(`${path}?${search}`, {extraHeaders: { "Content-Type": "application/json" },@@ -3219,6 +3227,33 @@ export class ApiClient {);}+ async getDashboardUsageBySquad(params: DashboardRequestParams): Promise<DashboardUsageBySquad[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/usage/by-squad",+ params,+ DashboardUsageBySquadListSchema,+ "GET /api/dashboard/usage/by-squad",+ );+ }++ async getDashboardSquadRunTime(params: DashboardRequestParams): Promise<DashboardSquadRunTime[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/squad-runtime",+ params,+ DashboardSquadRunTimeListSchema,+ "GET /api/dashboard/squad-runtime",+ );+ }++ async getDashboardFailuresBySquad(params: DashboardRequestParams): Promise<DashboardFailureBySquad[]> {+ return this.fetchDashboardRows(+ "/api/dashboard/failures/by-squad",+ params,+ DashboardFailureBySquadListSchema,+ "GET /api/dashboard/failures/by-squad",+ );+ }+// queue_when_busy: a busy daemon holds the update and installs it once// idle, instead of failing it; this UI can show and cancel the queue.async initiateUpdate(diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex c044f85213..a81fb6c25e 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2269,6 +2269,12 @@ const DashboardUsageByAgentSchema = z.object({export const DashboardUsageByAgentListSchema = z.array(DashboardUsageByAgentSchema);+const DashboardUsageBySquadSchema = DashboardUsageByAgentSchema.extend({+ squad_id: z.string().default(""),+}).loose();++export const DashboardUsageBySquadListSchema = z.array(DashboardUsageBySquadSchema);+// `cancelled_count` defaults to 0 so an installed client pointed at a// backend that predates it still renders: those rows simply carry no// cancelled segment, which is exactly what that backend measured.@@ -2283,6 +2289,12 @@ const DashboardAgentRunTimeSchema = z.object({export const DashboardAgentRunTimeListSchema = z.array(DashboardAgentRunTimeSchema);+const DashboardSquadRunTimeSchema = DashboardAgentRunTimeSchema.extend({+ squad_id: z.string().default(""),+}).loose();++export const DashboardSquadRunTimeListSchema = z.array(DashboardSquadRunTimeSchema);+const DashboardRunTimeDailySchema = z.object({date: z.string().default(""),total_seconds: z.number().default(0),@@ -2319,6 +2331,14 @@ export const DashboardFailureByAgentListSchema = z.array(DashboardFailureByAgentSchema,);+const DashboardFailureBySquadSchema = DashboardFailureByAgentSchema.extend({+ squad_id: z.string().default(""),+}).loose();++export const DashboardFailureBySquadListSchema = z.array(+ DashboardFailureBySquadSchema,+);+// Runtime usage schemas — the runtime-detail page's four usage endpoints// (`/api/runtimes/:id/usage*`). Same leniency rules as the dashboard// schemas above: numbers default to 0, strings to "", `.loose()` passes@@ -2512,6 +2532,8 @@ export const AgentTaskSchema = z.object({created_at: z.string().default(""),chat_session_id: z.string().optional(),autopilot_run_id: z.string().optional(),+ squad_id: z.string().optional().catch(undefined),+ is_leader_task: z.boolean().optional().catch(undefined),parent_task_id: z.string().optional(),attempt: z.number().optional(),trigger_comment_id: z.string().optional(),diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.tsindex 3ca35e3671..e4c7d251e1 100644--- a/packages/core/dashboard/queries.ts+++ b/packages/core/dashboard/queries.ts@@ -19,10 +19,13 @@ export type DashboardHistoryLimitParam = number | null | undefined;type DashboardKeyPart =| "daily"| "by-agent"+ | "by-squad"| "agent-runtime"+ | "squad-runtime"| "runtime-daily"| "failures-daily"- | "failures-by-agent";+ | "failures-by-agent"+ | "failures-by-squad";const dashboardKey = (wsId: string,@@ -31,7 +34,11 @@ const dashboardKey = (projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam = null,-) => ["dashboard", wsId, part, days, projectId, tz, historyLimit ?? null] as const;+ squadId: string | null = null,+) =>+ squadId === null+ ? (["dashboard", wsId, part, days, projectId, tz, historyLimit ?? null] as const)+ : (["dashboard", wsId, part, days, projectId, tz, historyLimit ?? null, squadId] as const);export const dashboardKeys = {all: (wsId: string) => ["dashboard", wsId] as const,@@ -41,42 +48,72 @@ export const dashboardKeys = {projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "daily", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "daily", days, projectId, tz, historyLimit, squadId),byAgent: (wsId: string,days: number,projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "by-agent", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "by-agent", days, projectId, tz, historyLimit, squadId),+ bySquad: (+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit?: DashboardHistoryLimitParam,+ squadId: string | null = null,+ ) => dashboardKey(wsId, "by-squad", days, projectId, tz, historyLimit, squadId),agentRuntime: (wsId: string,days: number,projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "agent-runtime", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "agent-runtime", days, projectId, tz, historyLimit, squadId),+ squadRuntime: (+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit?: DashboardHistoryLimitParam,+ squadId: string | null = null,+ ) => dashboardKey(wsId, "squad-runtime", days, projectId, tz, historyLimit, squadId),runTimeDaily: (wsId: string,days: number,projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "runtime-daily", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "runtime-daily", days, projectId, tz, historyLimit, squadId),failuresDaily: (wsId: string,days: number,projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "failures-daily", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "failures-daily", days, projectId, tz, historyLimit, squadId),failuresByAgent: (wsId: string,days: number,projectId: string | null,tz: string,historyLimit?: DashboardHistoryLimitParam,- ) => dashboardKey(wsId, "failures-by-agent", days, projectId, tz, historyLimit),+ squadId: string | null = null,+ ) => dashboardKey(wsId, "failures-by-agent", days, projectId, tz, historyLimit, squadId),+ failuresBySquad: (+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit?: DashboardHistoryLimitParam,+ squadId: string | null = null,+ ) => dashboardKey(wsId, "failures-by-squad", days, projectId, tz, historyLimit, squadId),};// The server materializes these rollups on a 5-minute cadence, so a mounted@@ -124,8 +161,9 @@ function dashboardOptions<T>(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {- const queryKey = dashboardKey(wsId, part, days, projectId, tz, historyLimit);+ const queryKey = dashboardKey(wsId, part, days, projectId, tz, historyLimit, squadId);return queryOptions({queryKey,queryFn: async ({ client }: { client: QueryClient }) => {@@ -134,6 +172,7 @@ function dashboardOptions<T>(const rows = await fetcher({days,project_id: projectId ?? undefined,+ squad_id: squadId ?? undefined,tz,onHistoryLimit: (limit) => {served = limit;@@ -169,6 +208,7 @@ export function dashboardUsageDailyOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("daily",@@ -178,6 +218,7 @@ export function dashboardUsageDailyOptions(projectId,tz,historyLimit,+ squadId,);}@@ -187,6 +228,7 @@ export function dashboardUsageByAgentOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("by-agent",@@ -196,6 +238,27 @@ export function dashboardUsageByAgentOptions(projectId,tz,historyLimit,+ squadId,+ );+}++export function dashboardUsageBySquadOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,+) {+ return dashboardOptions(+ "by-squad",+ (params) => api.getDashboardUsageBySquad(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ squadId,);}@@ -205,6 +268,7 @@ export function dashboardAgentRunTimeOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("agent-runtime",@@ -214,6 +278,27 @@ export function dashboardAgentRunTimeOptions(projectId,tz,historyLimit,+ squadId,+ );+}++export function dashboardSquadRunTimeOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,+) {+ return dashboardOptions(+ "squad-runtime",+ (params) => api.getDashboardSquadRunTime(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ squadId,);}@@ -223,6 +308,7 @@ export function dashboardRunTimeDailyOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("runtime-daily",@@ -232,6 +318,7 @@ export function dashboardRunTimeDailyOptions(projectId,tz,historyLimit,+ squadId,);}@@ -241,6 +328,7 @@ export function dashboardFailuresDailyOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("failures-daily",@@ -250,6 +338,7 @@ export function dashboardFailuresDailyOptions(projectId,tz,historyLimit,+ squadId,);}@@ -259,6 +348,7 @@ export function dashboardFailuresByAgentOptions(projectId: string | null,tz: string,historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,) {return dashboardOptions("failures-by-agent",@@ -268,5 +358,26 @@ export function dashboardFailuresByAgentOptions(projectId,tz,historyLimit,+ squadId,+ );+}++export function dashboardFailuresBySquadOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ historyLimit: DashboardHistoryLimitParam,+ squadId: string | null = null,+) {+ return dashboardOptions(+ "failures-by-squad",+ (params) => api.getDashboardFailuresBySquad(params),+ wsId,+ days,+ projectId,+ tz,+ historyLimit,+ squadId,);}diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex d496babc8d..71b6028fa8 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -364,6 +364,10 @@ export interface AgentTask {chat_session_id?: string;/** Non-empty when the task was spawned by an autopilot run. */autopilot_run_id?: string;+ /** Non-empty when this task belongs to a squad execution chain (leader or delegated member). */+ squad_id?: string;+ /** True when this task runs the agent as a squad leader. */+ is_leader_task?: boolean;/** Set when this task was created as an auto-retry of a parent task. */parent_task_id?: string;/** 1-based attempt counter; >1 means this is a retry. */@@ -1181,6 +1185,27 @@ export interface DashboardUsageByAgent {task_count: number;}+// Per-(squad, agent, model) token totals for the workspace dashboard.+// squad_id is "" for standalone (non-squad-triggered) agent runs.+export interface DashboardUsageBySquad extends DashboardUsageByAgent {+ squad_id: string;+}++// Per-(squad, agent) terminal-task run-time + counts for the workspace dashboard.+// squad_id is "" for standalone (non-squad-triggered) agent runs.+export interface DashboardSquadRunTime extends DashboardAgentRunTime {+ squad_id: string;+}++// Per-(squad, agent, failure_reason) terminal-task counts for the Errors tab.+// squad_id is "" for standalone (non-squad-triggered) agent runs.+export interface DashboardFailureBySquad {+ squad_id: string;+ agent_id: string;+ failure_reason: string;+ task_count: number;+}+// Per-agent total terminal-task run-time + counts. Powers the workspace// dashboard's "time by agent" list. failed_count is a subset of// task_count (failed tasks still contribute to total_seconds becausediff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex e5a6c66c57..9186ea9d88 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -93,10 +93,13 @@ export type {RuntimeUsageByHour,DashboardUsageDaily,DashboardUsageByAgent,+ DashboardUsageBySquad,DashboardAgentRunTime,+ DashboardSquadRunTime,DashboardRunTimeDaily,DashboardFailureDaily,DashboardFailureByAgent,+ DashboardFailureBySquad,RuntimeUpdate,RuntimeUpdateStatus,RuntimeModel,diff --git a/packages/views/agents/components/agent-activity-hover-content.tsx b/packages/views/agents/components/agent-activity-hover-content.tsxindex c554f2cffd..fd03087070 100644--- a/packages/views/agents/components/agent-activity-hover-content.tsx+++ b/packages/views/agents/components/agent-activity-hover-content.tsx@@ -10,6 +10,7 @@ import { runtimeListOptions } from "@multica/core/runtimes/queries";import { agentListOptions } from "@multica/core/workspace/queries";import { deriveAgentPresenceDetail } from "@multica/core/agents/derive-presence";import type { AgentTask, Issue } from "@multica/core/types";+import { groupExecutionTasksByActor } from "../../issues/surface/execution-actors";import { workloadConfig } from "../presence";import { useT } from "../../i18n";@@ -141,9 +142,17 @@ export function AgentActivityHoverContent({const { t } = useT("issues");const now = useActivityNow();const { agentById, runtimeById } = useActivityLookups();+ const { getActorName, getActorInitials, getActorAvatarUrl, hasActor } =+ useActorName();+ const isKnownSquad = hasActor+ ? (id: string) => hasActor("squad", id) !== false+ : null;if (tasks.length === 0) return null;+ const groups = groupExecutionTasksByActor(tasks, isKnownSquad);+ const hasSquadGroup = groups.some((g) => g.type === "squad");+return (<div className="flex flex-col gap-2"><div className="text-caption font-medium text-muted-foreground">@@ -152,17 +161,66 @@ export function AgentActivityHoverContent({disagree with the row count below. */}{t(($) => $.agent_activity.hover_header_tasks, { count: tasks.length })}</div>- <div className="flex flex-col gap-1.5">- {tasks.map((task) => (- <AgentActivityTaskRow- key={task.id}- task={task}- now={now}- agentById={agentById}- runtimeById={runtimeById}- />- ))}- </div>+ {hasSquadGroup ? (+ <div className="flex flex-col gap-2">+ {groups.map((group) =>+ group.type === "squad" ? (+ <div+ key={`squad:${group.id}`}+ className="flex flex-col gap-1.5 rounded-md border border-border/70 bg-muted/20 p-2"+ >+ <div className="flex items-center gap-1.5 text-caption">+ <ActorAvatarBase+ name={getActorName("squad", group.id)}+ initials={getActorInitials("squad", group.id)}+ avatarUrl={getActorAvatarUrl("squad", group.id)}+ isSquad+ size="xs"+ />+ <span className="min-w-0 flex-1 truncate font-medium">+ {getActorName("squad", group.id)}+ </span>+ </div>+ <div className="flex flex-col gap-1.5 pl-1">+ {group.tasks.map((task) => (+ <AgentActivityTaskRow+ key={task.id}+ task={task}+ now={now}+ agentById={agentById}+ runtimeById={runtimeById}+ />+ ))}+ </div>+ </div>+ ) : (+ <div key={`agent:${group.id}`} className="flex flex-col gap-1.5">+ {group.tasks.map((task) => (+ <AgentActivityTaskRow+ key={task.id}+ task={task}+ now={now}+ agentById={agentById}+ runtimeById={runtimeById}+ />+ ))}+ </div>+ ),+ )}+ </div>+ ) : (+ <div className="flex flex-col gap-1.5">+ {tasks.map((task) => (+ <AgentActivityTaskRow+ key={task.id}+ task={task}+ now={now}+ agentById={agentById}+ runtimeById={runtimeById}+ />+ ))}+ </div>+ )}</div>);}diff --git a/packages/views/agents/components/agent-avatar-stack.tsx b/packages/views/agents/components/agent-avatar-stack.tsxindex b9ce160131..c8dabea592 100644--- a/packages/views/agents/components/agent-avatar-stack.tsx+++ b/packages/views/agents/components/agent-avatar-stack.tsx@@ -5,11 +5,16 @@ import { AVATAR_SIZE_PX, type AvatarSize } from "@multica/ui/lib/avatar-size";import { useActorName } from "@multica/core/workspace/hooks";import { cn } from "@multica/ui/lib/utils";import { useT } from "../../i18n";+import type { ExecutionActorRef } from "../../issues/surface/execution-actors";interface AgentAvatarStackProps {// Agent ids to render, in display order. The component does NOT dedupe —// callers are expected to pass a unique list (`new Set(...)` upstream).- agentIds: readonly string[];+ agentIds?: readonly string[];+ // Mixed execution actors (squads + standalone agents). Takes precedence over+ // `agentIds` when supplied so surfaces can collapse squad runs into a single+ // squad avatar without duplicating stack geometry.+ actors?: readonly ExecutionActorRef[];// Semantic avatar tier. Avatars overlap by ~30% so the visible spacing// scales naturally with size. Defaults match a compact toolbar / card-corner// density (sm / 20 px).@@ -25,17 +30,14 @@ interface AgentAvatarStackProps {}/**- * Overlapping avatar group for agents. Pure presentational — no data- * fetching, no hover handling. Wrap it in a HoverCardTrigger upstream- * (IssueAgentActivityIndicator / WorkspaceAgentWorkingChip) to surface- * per-agent detail.- *- * `agentIds` is the full input list. We render up to `max` heads; if the- * input is longer, we drop the tail and append a `+N` overflow chip styled- * to match the avatar dimensions.+ * Overlapping avatar group for execution actors (agents and/or squads). Pure+ * presentational — no data fetching, no hover handling. Wrap it in a+ * HoverCardTrigger upstream (IssueAgentActivityIndicator /+ * WorkspaceAgentWorkingChip) to surface per-actor detail.*/export function AgentAvatarStack({- agentIds,+ agentIds = [],+ actors,size = "sm",max = 3,opacity = "full",@@ -43,10 +45,12 @@ export function AgentAvatarStack({}: AgentAvatarStackProps) {const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();const { t } = useT("agents");- if (agentIds.length === 0) return null;+ const resolvedActors: readonly ExecutionActorRef[] =+ actors ?? agentIds.map((id) => ({ type: "agent" as const, id }));+ if (resolvedActors.length === 0) return null;- const visible = agentIds.slice(0, max);- const overflow = agentIds.length - visible.length;+ const visible = resolvedActors.slice(0, max);+ const overflow = resolvedActors.length - visible.length;const px = AVATAR_SIZE_PX[size];// 30% overlap reads as "stacked" without obscuring the next avatar's icon.const overlap = Math.round(px * 0.3);@@ -60,19 +64,20 @@ export function AgentAvatarStack({)}style={{ paddingLeft: 0 }}>- {visible.map((id, i) => (+ {visible.map((actor, i) => (<span- key={id}+ key={`${actor.type}:${actor.id}`}// Each subsequent head sits negative-margin over the previous so// the stack collapses horizontally instead of growing linearly.style={{ marginLeft: i === 0 ? 0 : -overlap }}className="ring-2 ring-background rounded-full inline-flex"><ActorAvatarBase- name={getActorName("agent", id)}- initials={getActorInitials("agent", id)}- avatarUrl={getActorAvatarUrl("agent", id)}- isAgent+ name={getActorName(actor.type, actor.id)}+ initials={getActorInitials(actor.type, actor.id)}+ avatarUrl={getActorAvatarUrl(actor.type, actor.id)}+ isAgent={actor.type === "agent"}+ isSquad={actor.type === "squad"}size={size}/></span>diff --git a/packages/views/dashboard/components/dashboard-filters.tsx b/packages/views/dashboard/components/dashboard-filters.tsxindex 4b34a4bebf..cbf22508fa 100644--- a/packages/views/dashboard/components/dashboard-filters.tsx+++ b/packages/views/dashboard/components/dashboard-filters.tsx@@ -1,11 +1,15 @@"use client";-import { CalendarDays, ChevronDown, FolderKanban, Lock } from "@multica/ui/icons";+import { Bot, CalendarDays, ChevronDown, FolderKanban, Lock, Users } from "@multica/ui/icons";import { Button } from "@multica/ui/components/ui/button";+import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import {DropdownMenu,DropdownMenuTrigger,DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,DropdownMenuSeparator,@@ -14,6 +18,8 @@ import { ProjectIcon } from "../../projects/components/project-icon";import { useT } from "../../i18n";import {ALL_PROJECTS,+ ALL_SQUADS,+ STANDALONE_SQUAD,TIME_RANGES,type TimeRange,type TimeRangeOption,@@ -21,6 +27,7 @@ import {import { isRangeAllowed, type UpgradePlan } from "../history-range";type DashboardProject = { id: string; title: string; icon: string | null };+type DashboardSquad = { id: string; name: string; avatar_url: string | null; archived_at?: string | null };/*** Page-scoped time range.@@ -197,3 +204,97 @@ export function ProjectFilter({</DropdownMenu>);}++/**+ * Page-scoped attribution filter (all / standalone agents / specific squad).+ * Mirrors ProjectFilter's ghost button grammar: quiet until narrowed, showing+ * the selected squad's own avatar + name when active.+ */+export function SquadFilter({+ squads,+ squadValue,+ onSquadChange,+}: {+ squads: DashboardSquad[];+ squadValue: string;+ onSquadChange: (value: string) => void;+}) {+ const { t } = useT("usage");+ const allLabel = t(($) => $.filter.all_attribution);+ const standaloneLabel = t(($) => $.filter.standalone_only);+ const liveSquads = squads.filter((s) => !s.archived_at);+ const isStandalone = squadValue === STANDALONE_SQUAD;+ const selected = !isStandalone && squadValue !== ALL_SQUADS+ ? squads.find((s) => s.id === squadValue)+ : undefined;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="sm"+ aria-label={t(($) => $.filter.attribution_label)}+ className="h-7 gap-1.5 px-2 text-body"+ >+ {selected ? (+ <ActorAvatarBase+ name={selected.name}+ initials={selected.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(selected.avatar_url)}+ isSquad+ size="xs"+ />+ ) : isStandalone ? (+ <Bot className="size-3.5 text-muted-foreground" />+ ) : (+ <Users className="size-3.5 text-muted-foreground" />+ )}+ <span className="max-w-40 truncate">+ {selected ? selected.name : isStandalone ? standaloneLabel : allLabel}+ </span>+ <ChevronDown className="size-3 text-muted-foreground" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="max-h-72 w-auto min-w-52">+ <DropdownMenuRadioGroup+ value={selected ? selected.id : isStandalone ? STANDALONE_SQUAD : ALL_SQUADS}+ onValueChange={(value) => onSquadChange(value ?? ALL_SQUADS)}+ >+ <DropdownMenuRadioItem value={ALL_SQUADS}>+ <Users className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate">{allLabel}</span>+ </DropdownMenuRadioItem>+ <DropdownMenuRadioItem value={STANDALONE_SQUAD}>+ <Bot className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate">{standaloneLabel}</span>+ </DropdownMenuRadioItem>+ {liveSquads.length > 0 ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuLabel className="text-micro font-medium text-muted-foreground">+ {t(($) => $.filter.squads_group)}+ </DropdownMenuLabel>+ {liveSquads.map((squad) => (+ <DropdownMenuRadioItem key={squad.id} value={squad.id}>+ <ActorAvatarBase+ name={squad.name}+ initials={squad.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(squad.avatar_url)}+ isSquad+ size="xs"+ />+ <span className="truncate">{squad.name}</span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuGroup>+ </>+ ) : null}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex f59c6b30c2..dd835dfd33 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -19,17 +19,20 @@ import {} from "@multica/core/feature-flags";import { workspaceSubscriptionPricesOptions } from "@multica/core/billing";import { useWorkspacePaths } from "@multica/core/paths";-import type { Agent } from "@multica/core/types";-import { agentListOptions } from "@multica/core/workspace/queries";+import type { Agent, Squad } from "@multica/core/types";+import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";import { projectListOptions } from "@multica/core/projects/queries";import {dashboardKeys,dashboardUsageDailyOptions,dashboardUsageByAgentOptions,+ dashboardUsageBySquadOptions,dashboardAgentRunTimeOptions,+ dashboardSquadRunTimeOptions,dashboardRunTimeDailyOptions,dashboardFailuresDailyOptions,dashboardFailuresByAgentOptions,+ dashboardFailuresBySquadOptions,useDashboardHistoryLimit,} from "@multica/core/dashboard";import { toast } from "sonner";@@ -57,6 +60,8 @@ import {aggregateDailyTokens,aggregateFailureClasses,aggregateFailureReasons,+ aggregateSquadDashboardRows,+ aggregateSquadFailures,aggregateWeeklyErrors,aggregateWeeklyTasks,aggregateWeeklyTime,@@ -65,17 +70,20 @@ import {computeDailyTotals,computeFailureTotals,isSyntheticAgentRow,+ isSyntheticSquadRow,mergeAgentDashboardRows,} from "../utils";import {ALL_PROJECTS,+ ALL_SQUADS,+ STANDALONE_SQUAD,DurationNumberFlow,dimsForDays,type TimeRange,} from "./dashboard-shared";-import { ProjectFilter, TimeRangeFilter } from "./dashboard-filters";+import { ProjectFilter, SquadFilter, TimeRangeFilter } from "./dashboard-filters";import { UsageTrendCard } from "./usage-trend-card";-import { Leaderboard } from "./leaderboard";+import { Leaderboard, type LeaderboardGroupBy } from "./leaderboard";import { ErrorsTab } from "./errors-tab";import {earliestReadableDay,@@ -90,12 +98,17 @@ import { dashboardTimeRanges } from "./dashboard-shared";// reference-equality dep check and trips the exhaustive-deps lint rule.const EMPTY_DAILY: import("@multica/core/types").DashboardUsageDaily[] = [];const EMPTY_BY_AGENT: import("@multica/core/types").DashboardUsageByAgent[] = [];+const EMPTY_BY_SQUAD: import("@multica/core/types").DashboardUsageBySquad[] = [];const EMPTY_RUNTIME: import("@multica/core/types").DashboardAgentRunTime[] = [];+const EMPTY_SQUAD_RUNTIME: import("@multica/core/types").DashboardSquadRunTime[] = [];const EMPTY_RUNTIME_DAILY: import("@multica/core/types").DashboardRunTimeDaily[] = [];const EMPTY_FAILURE_DAILY: import("@multica/core/types").DashboardFailureDaily[] = [];const EMPTY_FAILURE_BY_AGENT: import("@multica/core/types").DashboardFailureByAgent[] =[];+const EMPTY_FAILURE_BY_SQUAD: import("@multica/core/types").DashboardFailureBySquad[] =+ [];const EMPTY_AGENTS: Agent[] = [];+const EMPTY_SQUADS: Squad[] = [];type DashboardTab = "usage" | "errors";const TAB_QUERY_KEY = "tab";@@ -212,6 +225,9 @@ export function DashboardPage() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [history.ready, history.maxDays]);const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);+ const [squadValue, setSquadValue] = useState<string>(ALL_SQUADS);+ const [leaderboardGroupBy, setLeaderboardGroupBy] =+ useState<LeaderboardGroupBy>("agent");// One scroller for both tabs: the offset restored is the shown tab's.const restoreScrollRef = useRestoredScrollRef("dashboard");@@ -237,77 +253,152 @@ export function DashboardPage() {const { data: projects = [] } = useQuery(projectListOptions(wsId));const agentsQuery = useQuery(agentListOptions(wsId));const agents = agentsQuery.data ?? EMPTY_AGENTS;+ const squadsQuery = useQuery(squadListOptions(wsId));+ const squads = squadsQuery.data ?? EMPTY_SQUADS;- // Validate the picked project against the current workspace's list. A- // stale UUID — left over from a project that's been deleted, or from the- // previous workspace after a switch — would silently filter every query to- // empty rows while the header still reads "All projects". Derive the- // effective filter so the API call matches the user-visible selection.const projectId = useMemo(() => {if (projectValue === ALL_PROJECTS) return null;return projects.some((p) => p.id === projectValue) ? projectValue : null;}, [projectValue, projects]);- // The weekly charts paint `ceil(days / 7)` trailing calendar weeks anchored- // at today-in-UTC. In the worst case (today = Sunday) the leftmost Monday- // sits `weekCount * 7 - 1` days back, so a vanilla `days=30` request would- // silently truncate the leftmost bucket. Over-fetch the per-date queries to- // cover the full first week.- //- // Unconditionally, not only when a chart is weekly: the dimension is now a- // card-level control, so the page cannot know which grain is on screen — and- // fetching for the wider of the two means flipping a card between Daily and- // Weekly never refetches. Daily aggregations trim back to exactly `days`- // client-side via `dailyCutoffIso` below, so the extra rows change nothing- // they show. The per-agent rollups stay at `days` so KPI/leaderboard labels- // (e.g. "Tasks · 30D") keep their advertised window.+ const squadFilterParam = useMemo(() => {+ if (squadValue === ALL_SQUADS) return null;+ if (squadValue === STANDALONE_SQUAD) return STANDALONE_SQUAD;+ return squads.some((s) => s.id === squadValue) ? squadValue : null;+ }, [squadValue, squads]);++ const selectedSquad = useMemo(() => {+ if (!squadFilterParam || squadFilterParam === STANDALONE_SQUAD) return null;+ return squads.find((s) => s.id === squadFilterParam) ?? null;+ }, [squadFilterParam, squads]);+const weekCount = Math.max(1, Math.ceil(days / 7));const chartFetchDays = weekCount * 7;const dailyQuery = useQuery(- dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),- );- // The three per-agent rollups carry no date, so `dailyCutoffIso` below- // cannot trim them — their window is closed server-side at exactly `days`- // calendar buckets (parseExactSinceParamInTZ). Anything derived from these- // three is therefore already on the same span as the trimmed daily series;- // do NOT put a per-agent rollup back on the N+1 cutoff, or the leaderboard- // and the Run time / Tasks KPIs silently widen by one day while the chart- // and the Cost / Tokens KPIs beside them do not (MUL-5551).- const byAgentQuery = useQuery(- dashboardUsageByAgentOptions(wsId, days, projectId, viewTZ, historyLimit),+ dashboardUsageDailyOptions(+ wsId,+ chartFetchDays,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),);+ const byAgentQuery = useQuery(+ dashboardUsageByAgentOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ );+ const bySquadQuery = useQuery({+ ...dashboardUsageBySquadOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ enabled:+ !!wsId &&+ historyLimit !== undefined &&+ squadFilterParam === null,+ });const runTimeQuery = useQuery(- dashboardAgentRunTimeOptions(wsId, days, projectId, viewTZ, historyLimit),- );+ dashboardAgentRunTimeOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ );+ const squadRunTimeQuery = useQuery({+ ...dashboardSquadRunTimeOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ enabled:+ !!wsId &&+ historyLimit !== undefined &&+ squadFilterParam === null,+ });const runTimeDailyQuery = useQuery(- dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),+ dashboardRunTimeDailyOptions(+ wsId,+ chartFetchDays,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),);const failuresDailyQuery = useQuery(- dashboardFailuresDailyOptions(wsId, chartFetchDays, projectId, viewTZ, historyLimit),+ dashboardFailuresDailyOptions(+ wsId,+ chartFetchDays,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),);const failuresByAgentQuery = useQuery(- dashboardFailuresByAgentOptions(wsId, days, projectId, viewTZ, historyLimit),- );+ dashboardFailuresByAgentOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ );+ const failuresBySquadQuery = useQuery({+ ...dashboardFailuresBySquadOptions(+ wsId,+ days,+ projectId,+ viewTZ,+ historyLimit,+ squadFilterParam,+ ),+ enabled:+ !!wsId &&+ historyLimit !== undefined &&+ squadFilterParam === null,+ });const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;const byAgentUsage = byAgentQuery.data ?? EMPTY_BY_AGENT;+ const bySquadUsage = bySquadQuery.data ?? EMPTY_BY_SQUAD;const runTimeRows = runTimeQuery.data ?? EMPTY_RUNTIME;+ const squadRunTimeRows = squadRunTimeQuery.data ?? EMPTY_SQUAD_RUNTIME;const runTimeDailyRows = runTimeDailyQuery.data ?? EMPTY_RUNTIME_DAILY;const failureDailyRows = failuresDailyQuery.data ?? EMPTY_FAILURE_DAILY;const failureByAgentRows = failuresByAgentQuery.data ?? EMPTY_FAILURE_BY_AGENT;+ const failureBySquadRows = failuresBySquadQuery.data ?? EMPTY_FAILURE_BY_SQUAD;const queryClient = useQueryClient();- // "Refreshing" covers any of the six rollups being in flight, whichever- // trigger started it (button, interval, mount) — the header spinner and the- // timestamp describe the same set of queries.const isRefreshing =dailyQuery.isFetching ||byAgentQuery.isFetching ||+ bySquadQuery.isFetching ||runTimeQuery.isFetching ||+ squadRunTimeQuery.isFetching ||runTimeDailyQuery.isFetching ||failuresDailyQuery.isFetching ||- failuresByAgentQuery.isFetching;+ failuresByAgentQuery.isFetching ||+ failuresBySquadQuery.isFetching;const handleRefresh = () => {void queryClient.invalidateQueries({ queryKey: dashboardKeys.all(wsId) });};@@ -422,15 +513,11 @@ export function DashboardPage() {() => (agentsQuery.isSuccess ? new Set(agents.map((a) => a.id)) : null),[agentsQuery.isSuccess, agents],);+ const knownSquadIds = useMemo(+ () => (squadsQuery.isSuccess ? new Set(squads.map((s) => s.id)) : null),+ [squadsQuery.isSuccess, squads],+ );- // The per-agent split has no date to trim on, so its window is closed- // server-side instead — GetDashboardFailuresByAgent uses the exact N-day- // cutoff rather than the N+1 one.- //- // Anonymize BEFORE aggregating: the sentinel then behaves like any other- // agent id, so the bucket's failure classes are summed from real- // per-(agent, reason) rows instead of being reconstructed from rows that- // have already collapsed to a single dominant class.const agentFailureRows = useMemo(() =>aggregateAgentFailures(@@ -438,6 +525,10 @@ export function DashboardPage() {),[failureByAgentRows, knownAgentIds],);+ const squadFailureRows = useMemo(+ () => aggregateSquadFailures(failureBySquadRows, knownSquadIds),+ [failureBySquadRows, knownSquadIds],+ );// Weekly aggregates — built from the over-fetched per-date queries so the// leftmost trailing week always has data even when the user-selected `days`@@ -506,6 +597,25 @@ export function DashboardPage() {() => bucketUnknownAgentRows(agentRows, knownAgentIds),[agentRows, knownAgentIds],);+ const squadDashboardRows = useMemo(+ () =>+ aggregateSquadDashboardRows(+ bySquadUsage,+ squadRunTimeRows,+ knownAgentIds,+ knownSquadIds,+ ),+ [bySquadUsage, squadRunTimeRows, knownAgentIds, knownSquadIds],+ );+ const squadCostSummary = useMemo(() => {+ if (squadFilterParam !== null || totals.cost <= 0) return null;+ const squadCost = squadDashboardRows+ .filter((r) => !isSyntheticSquadRow(r.squadId))+ .reduce((sum, r) => sum + r.cost, 0);+ if (squadCost <= 0) return null;+ const pct = Math.min(100, Math.round((squadCost / totals.cost) * 100));+ return { cost: `$${squadCost.toFixed(2)}`, pct };+ }, [squadFilterParam, squadDashboardRows, totals.cost]);// Distinct hard-deleted agents folded into the bucket — drives the caption's// "· N deleted" suffix (the bucket itself is a single row). The server's// restricted bucket is not in `knownAgentIds` either but is not a deletion,@@ -578,6 +688,13 @@ export function DashboardPage() {projectValue={projectValue}onProjectChange={setProjectValue}/>+ {squads.length > 0 ? (+ <SquadFilter+ squads={squads}+ squadValue={squadValue}+ onSquadChange={setSquadValue}+ />+ ) : null}<IconButtonlabel={t(($) => $.header.refresh)}tooltipSide="bottom"@@ -609,6 +726,16 @@ export function DashboardPage() {<KpiCardlabel={t(($) => $.kpi.cost_label, { days })}value={<CurrencyNumberFlow value={totals.cost} locales={locales} />}+ hint={+ selectedSquad+ ? t(($) => $.kpi.cost_squad_hint, { name: selectedSquad.name })+ : squadCostSummary+ ? t(($) => $.kpi.cost_squad_share_hint, {+ cost: squadCostSummary.cost,+ pct: squadCostSummary.pct,+ })+ : undefined+ }/><KpiCardlabel={t(($) => $.kpi.tokens_label, { days })}@@ -681,6 +808,15 @@ export function DashboardPage() {agents={agents}deletedAgentCount={deletedAgentCount}lessThanMinuteLabel={lessThanMinuteLabel}+ squadRows={squadDashboardRows}+ squads={squads}+ groupBy={leaderboardGroupBy}+ onGroupByChange={+ squadFilterParam === null && squads.length > 0+ ? setLeaderboardGroupBy+ : undefined+ }+ selectedSquad={selectedSquad}/></>)}@@ -697,9 +833,12 @@ export function DashboardPage() {classRows={failureClassRows}reasonRows={failureReasonRows}agentRows={agentFailureRows}+ squadRows={squadFailureRows}dailyErrors={dailyErrors}weeklyErrors={weeklyErrors}agents={agents}+ squads={squads}+ allowSquadGrouping={squadFilterParam === null && squads.length > 0}locales={locales}/>)}diff --git a/packages/views/dashboard/components/dashboard-shared.tsx b/packages/views/dashboard/components/dashboard-shared.tsxindex fdb52886f2..76533c65c8 100644--- a/packages/views/dashboard/components/dashboard-shared.tsx+++ b/packages/views/dashboard/components/dashboard-shared.tsx@@ -61,6 +61,10 @@ export function dimsForDays(days: TimeRange): readonly Dim[] {* it survives a refactor that ever lets a project be slug-keyed. */export const ALL_PROJECTS = "__all__";+/** Sentinels for the dashboard's attribution (Squad / standalone) filter. */+export const ALL_SQUADS = "__all__";+export const STANDALONE_SQUAD = "__standalone__";+/*** Card-local segmented control — the pill toggle used *inside* a card to pick* what that card shows. The page header deliberately uses outline Buttonsdiff --git a/packages/views/dashboard/components/errors-tab.tsx b/packages/views/dashboard/components/errors-tab.tsxindex 659437c9c4..3ed3fcf08f 100644--- a/packages/views/dashboard/components/errors-tab.tsx+++ b/packages/views/dashboard/components/errors-tab.tsx@@ -18,15 +18,19 @@ import { CollectionPageState } from "../../layout/collection-page";import {aggregateDailyErrors,aggregateWeeklyErrors,+ DELETED_SQUADS_ROW_ID,hasRateSample,MIN_RATE_SAMPLE,OFFENDER_METRIC,sortAgentFailures,+ sortSquadFailures,+ STANDALONE_SQUAD_ROW_ID,type AgentFailureRow,type FailureClassRow,type FailureReasonRow,type FailureTotals,type OffenderSort,+ type SquadFailureRow,} from "../utils";import { type Dim } from "./dashboard-shared";import { Segmented } from "./dashboard-shared";@@ -84,9 +88,12 @@ export function ErrorsTab({classRows,reasonRows,agentRows,+ squadRows = [],dailyErrors,weeklyErrors,agents,+ squads = [],+ allowSquadGrouping = false,locales,}: {days: number;@@ -95,9 +102,12 @@ export function ErrorsTab({classRows: FailureClassRow[];reasonRows: FailureReasonRow[];agentRows: AgentFailureRow[];+ squadRows?: SquadFailureRow[];dailyErrors: ReturnType<typeof aggregateDailyErrors>;weeklyErrors: ReturnType<typeof aggregateWeeklyErrors>;agents: { id: string; name: string }[];+ squads?: { id: string; name: string }[];+ allowSquadGrouping?: boolean;locales?: Intl.LocalesArgument;}) {const { t } = useT("usage");@@ -182,7 +192,10 @@ export function ErrorsTab({/><OffendersCardagentRows={agentRows}+ squadRows={squadRows}agents={agents}+ squads={squads}+ allowSquadGrouping={allowSquadGrouping}classLabel={classLabel}/></>@@ -275,16 +288,26 @@ function FailureMixCard({/** Who it broke for. */function OffendersCard({agentRows,+ squadRows,agents,+ squads,+ allowSquadGrouping,classLabel,}: {agentRows: AgentFailureRow[];+ squadRows: SquadFailureRow[];agents: { id: string; name: string }[];+ squads: { id: string; name: string }[];+ allowSquadGrouping: boolean;classLabel: (c: FailureClass) => string;}) {const { t } = useT("usage");+ const wsPaths = useWorkspacePaths();const [showAllAgents, setShowAllAgents] = useState(false);const [sortBy, setSortBy] = useState<OffenderSort>("failed");+ const [groupBy, setGroupBy] = useState<"agent" | "squad">("agent");++ const effectiveGroupBy = allowSquadGrouping ? groupBy : "agent";const sortOptions = useMemo(() => [@@ -294,27 +317,64 @@ function OffendersCard({[t],);+ const groupOptions = useMemo(+ () => [+ { value: "agent" as const, label: t(($) => $.leaderboard.group_agent) },+ { value: "squad" as const, label: t(($) => $.leaderboard.group_squad) },+ ],+ [t],+ );+const sortedAgents = useMemo(() => sortAgentFailures(agentRows, sortBy),[agentRows, sortBy],);- // The leader fills the track, measured over every row rather than the- // visible ones so a bar means the same thing collapsed and expanded. Reading- // it off the leader (instead of a max over the raw rows) also keeps the Rate- // scale usable: a demoted small-sample row can out-rate the leader, and- // scaling to it would squash every meaningful bar to a sliver.- const leader = sortedAgents[0];- const maxValue = leader ? OFFENDER_METRIC[sortBy](leader) : 0;+ const sortedSquads = useMemo(+ () => sortSquadFailures(squadRows, sortBy),+ [squadRows, sortBy],+ );++ const activeCount =+ effectiveGroupBy === "squad" ? sortedSquads.length : sortedAgents.length;++ const leader =+ effectiveGroupBy === "squad" ? sortedSquads[0] : sortedAgents[0];+ const maxValue = leader+ ? sortBy === "failed"+ ? leader.failed+ : leader.rate+ : 0;const visibleAgents = showAllAgents? sortedAgents: sortedAgents.slice(0, TOP_OFFENDER_LIMIT);+ const visibleSquads = showAllAgents+ ? sortedSquads+ : sortedSquads.slice(0, TOP_OFFENDER_LIMIT);+return (<div className="rounded-lg border bg-card"><div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">- <h4 className="text-body font-semibold">{t(($) => $.errors.by_agent)}</h4>+ <div className="flex flex-wrap items-center gap-2.5">+ <h4 className="text-body font-semibold">+ {effectiveGroupBy === "squad"+ ? t(($) => $.errors.by_squad)+ : t(($) => $.errors.by_agent)}+ </h4>+ {allowSquadGrouping ? (+ <Segmented+ label={t(($) => $.leaderboard.group_label)}+ value={effectiveGroupBy}+ onChange={(next) => {+ setShowAllAgents(false);+ setGroupBy(next);+ }}+ options={groupOptions}+ />+ ) : null}+ </div><div className="flex flex-wrap items-center justify-end gap-3"><Segmentedlabel={t(($) => $.errors.sort_label)}@@ -322,7 +382,7 @@ function OffendersCard({onChange={setSortBy}options={sortOptions}/>- {sortedAgents.length > TOP_OFFENDER_LIMIT ? (+ {activeCount > TOP_OFFENDER_LIMIT ? (<buttontype="button"onClick={() => setShowAllAgents((v) => !v)}@@ -330,21 +390,21 @@ function OffendersCard({>{showAllAgents? t(($) => $.errors.show_less, { count: TOP_OFFENDER_LIMIT })- : t(($) => $.errors.show_all, { count: sortedAgents.length })}+ : t(($) => $.errors.show_all, { count: activeCount })}</button>) : null}</div></div><div className="p-4 pt-0">- {/* Column headers, as on the leaderboard: `4 / 10 · 40%` was one- unlabelled blob and the reader had to guess which number was- which. The active metric's column is emphasised so it is- obvious what the ranking and the bars measure. */}- {sortedAgents.length > 0 ? (+ {activeCount > 0 ? (<divclassName={`${OFFENDER_GRID} border-b py-2 text-caption font-medium text-muted-foreground`}>- <span>{t(($) => $.errors.header_agent)}</span>+ <span>+ {effectiveGroupBy === "squad"+ ? t(($) => $.leaderboard.header_squad)+ : t(($) => $.errors.header_agent)}+ </span><span /><spanclassName={`text-right ${sortBy === "failed" ? "text-foreground" : ""}`}@@ -359,17 +419,53 @@ function OffendersCard({</span></div>) : null}- <ul aria-label={t(($) => $.errors.by_agent)} className="divide-y">- {visibleAgents.map((row) => (- <AgentFailureItem- key={row.agentId}- row={row}- name={agents.find((a) => a.id === row.agentId)?.name ?? null}- maxValue={maxValue}- sortBy={sortBy}- classLabel={classLabel}- />- ))}+ <ul+ aria-label={+ effectiveGroupBy === "squad"+ ? t(($) => $.errors.by_squad)+ : t(($) => $.errors.by_agent)+ }+ className="divide-y"+ >+ {effectiveGroupBy === "squad"+ ? visibleSquads.map((row) => {+ const isStandalone = row.squadId === STANDALONE_SQUAD_ROW_ID;+ const isDeleted = row.squadId === DELETED_SQUADS_ROW_ID;+ const squad = squads.find((s) => s.id === row.squadId);+ const labelText = isStandalone+ ? t(($) => $.leaderboard.standalone_agents)+ : isDeleted+ ? t(($) => $.leaderboard.deleted_squads)+ : squad?.name ?? null;+ return (+ <AgentFailureItem+ key={row.squadId}+ row={{+ agentId: row.squadId,+ failed: row.failed,+ total: row.total,+ rate: row.rate,+ classes: row.classes,+ }}+ name={labelText}+ href={squad ? wsPaths.squadDetail(squad.id) : null}+ italic={isStandalone || isDeleted || !labelText}+ maxValue={maxValue}+ sortBy={sortBy}+ classLabel={classLabel}+ />+ );+ })+ : visibleAgents.map((row) => (+ <AgentFailureItem+ key={row.agentId}+ row={row}+ name={agents.find((a) => a.id === row.agentId)?.name ?? null}+ maxValue={maxValue}+ sortBy={sortBy}+ classLabel={classLabel}+ />+ ))}</ul></div></div>@@ -477,12 +573,16 @@ function ReasonList({ rows }: { rows: FailureReasonRow[] }) {function AgentFailureItem({row,name,+ href,+ italic,maxValue,sortBy,classLabel,}: {row: AgentFailureRow;name: string | null;+ href?: string | null;+ italic?: boolean;maxValue: number;sortBy: OffenderSort;classLabel: (c: FailureClass) => string;@@ -491,37 +591,24 @@ function AgentFailureItem({const wsPaths = useWorkspacePaths();const segments = FAILURE_CLASSES.filter((c) => row.classes[c] > 0);- // Text equivalent of the stacked bar. The bar is the only place the class- // split is rendered, so it has to carry a name for screen readers as well as- // a hover affordance for everyone else.const composition = segments.map((c) => `${classLabel(c)} ${row.classes[c]}`).join(" · ");- // Clamped, not just scaled: under the Rate ranking a small-sample row is- // demoted below the leader while still able to carry a higher rate, and an- // unclamped width would overflow the track.const value = OFFENDER_METRIC[sortBy](row);const pct = maxValue > 0 ? Math.min(100, (value / maxValue) * 100) : 0;- // Below MIN_RATE_SAMPLE runs the rate is arithmetic, not signal (1/1 is- // 100%). Those rows sort last under Rate and never take the emphasis that- // marks the active column, but they keep rendering and say why on hover.const weakSample = !hasRateSample(row);+ const resolvedHref =+ href !== undefined+ ? href+ : name+ ? `${wsPaths.agentDetail(row.agentId)}?view=overview`+ : null;- // The row links into the agent's Overview, whose ActivityTab lists recent- // runs with each failure's reason — the drill-down from "this agent is the- // problem" to the actual failed runs. NOT the Work tab: that one lists the- // issues assigned to the agent, which is a different question entirely.- //- // An agent with no resolvable name is either hard-deleted or private to- // someone else; either way there is no page to open and no name to show,- // so the row degrades to a neutral placeholder. Rendering `row.agentId`- // here would leak a bare UUID — and, for a private agent, leak its- // existence and failure profile to a member who cannot see it.const label = (<span- className={`block truncate text-caption${name ? "" : " italic text-muted-foreground"}`}+ className={`block truncate text-caption${italic || !name ? " italic text-muted-foreground" : ""}`}>{name ?? t(($) => $.errors.other_agents)}</span>@@ -529,9 +616,9 @@ function AgentFailureItem({return (<li className={`${OFFENDER_GRID} py-2`}>- {name ? (+ {resolvedHref && name ? (<AppLink- href={`${wsPaths.agentDetail(row.agentId)}?view=overview`}+ href={resolvedHref}newTabTitle={name}className="min-w-0 hover:underline">diff --git a/packages/views/dashboard/components/leaderboard.tsx b/packages/views/dashboard/components/leaderboard.tsxindex c6fbf63711..5a3cd49387 100644--- a/packages/views/dashboard/components/leaderboard.tsx+++ b/packages/views/dashboard/components/leaderboard.tsx@@ -1,16 +1,22 @@"use client";-import { useMemo, useState, type CSSProperties } from "react";-import { EyeOff, Trash2 } from "@multica/ui/icons";+import { Fragment, useMemo, useState, type CSSProperties } from "react";+import { Bot, ChevronDown, ChevronRight, EyeOff, Trash2 } from "@multica/ui/icons";+import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { ActorAvatar } from "../../common/actor-avatar";import { formatTokens } from "../../runtimes/utils";import { useT } from "../../i18n";import {DELETED_AGENTS_ROW_ID,+ DELETED_SQUADS_ROW_ID,formatDuration,isSyntheticAgentRow,+ isSyntheticSquadRow,RESTRICTED_AGENTS_ROW_ID,+ STANDALONE_SQUAD_ROW_ID,type AgentDashboardRow,+ type SquadDashboardRow,} from "../utils";import { Segmented } from "./dashboard-shared";import "./leaderboard.css";@@ -20,27 +26,22 @@ import { TruncatedTooltip } from "@multica/ui/components/common/truncated-toolti// width, and which column header is emphasised — keeping the three in// lockstep so the user always sees what the ranking actually measures.type LeaderboardSort = "tokens" | "cost" | "time" | "tasks";+export type LeaderboardGroupBy = "agent" | "squad";-const SORT_METRIC: Record<LeaderboardSort, (r: AgentDashboardRow) => number> = {+const SORT_METRIC: Record<+ LeaderboardSort,+ (r: { tokens: number; cost: number; seconds: number; taskCount: number }) => number+> = {tokens: (r) => r.tokens,cost: (r) => r.cost,time: (r) => r.seconds,tasks: (r) => r.taskCount,};-// How many agents the leaderboard ranks before collapsing the tail behind a-// toggle, mirroring the offender list's cap. A workspace with dozens of agents-// rendered every one of them, which pushed everything below it a full screen or-// more down the page (MUL-5388). Ten answers "who is spending the most" — the-// tail is reachable via the toggle.+// How many entities the leaderboard ranks before collapsing the tail behind a+// toggle, mirroring the offender list's cap.const LEADERBOARD_LIMIT = 10;-// The flexible columns own the readability constraints they protect instead-// of deriving them from a detached total width. Agent keeps a 24px avatar, an-// 8px gap, and 128px of readable name; Progress keeps its 8px bar at a 12:1-// comparison length. `fit-content` lets those floors plus the fixed tracks,-// gaps, and row padding form the intrinsic scroll width while the fr tracks-// still expand on wider cards.const LEADERBOARD_GRID_STYLE = {minWidth: "fit-content",gridTemplateColumns:@@ -49,20 +50,45 @@ const LEADERBOARD_GRID_STYLE = {const LEADERBOARD_GRID = "grid items-center gap-3";+type LeaderboardSquad = {+ id: string;+ name: string;+ avatar_url: string | null;+ leader_id: string;+};+export function Leaderboard({rows,agents,deletedAgentCount,lessThanMinuteLabel,+ squadRows = [],+ squads = [],+ groupBy = "agent",+ onGroupByChange,+ selectedSquad = null,}: {rows: AgentDashboardRow[];agents: { id: string; name: string }[];deletedAgentCount: number;lessThanMinuteLabel: string;+ squadRows?: SquadDashboardRow[];+ squads?: LeaderboardSquad[];+ groupBy?: LeaderboardGroupBy;+ onGroupByChange?: (next: LeaderboardGroupBy) => void;+ /** When the page is filtered to a single Squad, the leaderboard renders that+ * Squad's member breakdown directly (no redundant Squad grouping toggle). */+ selectedSquad?: LeaderboardSquad | null;}) {const { t } = useT("usage");+ const { t: tSquads } = useT("squads");const [sortBy, setSortBy] = useState<LeaderboardSort>("tokens");const [showAll, setShowAll] = useState(false);+ const [expandedSquads, setExpandedSquads] = useState<Record<string, boolean>>({});++ const effectiveGroupBy: LeaderboardGroupBy =+ selectedSquad || !onGroupByChange ? "agent" : groupBy;+ const showGroupSwitch = !selectedSquad && !!onGroupByChange;const sortOptions = useMemo(() => [@@ -74,36 +100,62 @@ export function Leaderboard({[t],);- // Re-rank when the metric changes; keep the merged input untouched so- // upstream `mergeAgentDashboardRows`'s tiebreaker (run time desc) still- // applies inside an equal-bucket.+ const groupOptions = useMemo(+ () => [+ { value: "agent" as const, label: t(($) => $.leaderboard.group_agent) },+ { value: "squad" as const, label: t(($) => $.leaderboard.group_squad) },+ ],+ [t],+ );+const sortedRows = useMemo(() => {const metric = SORT_METRIC[sortBy];return rows.toSorted((a, b) => metric(b) - metric(a));}, [rows, sortBy]);- // Measured across every row, not just the visible ones, so a bar's width- // means the same thing collapsed and expanded — the leader always fills the- // track and nothing re-scales when the tail comes into view.+ // Keep real squads ranked at the top by the active metric and pin the+ // standalone (non-squad) reconciliation bucket at the bottom so the reader+ // compares squads cleanly while all rows still sum to 100% of top KPIs.+ const sortedSquadRows = useMemo(() => {+ const metric = SORT_METRIC[sortBy];+ return squadRows.toSorted((a, b) => {+ const aStandalone = a.squadId === STANDALONE_SQUAD_ROW_ID ? 1 : 0;+ const bStandalone = b.squadId === STANDALONE_SQUAD_ROW_ID ? 1 : 0;+ if (aStandalone !== bStandalone) return aStandalone - bStandalone;+ return metric(b) - metric(a);+ });+ }, [squadRows, sortBy]);++ const activeRows = effectiveGroupBy === "squad" ? sortedSquadRows : sortedRows;+const maxValue = useMemo(() => {const metric = SORT_METRIC[sortBy];- return sortedRows.reduce((m, r) => Math.max(m, metric(r)), 0);- }, [sortedRows, sortBy]);+ return activeRows.reduce((m, r) => Math.max(m, metric(r)), 0);+ }, [activeRows, sortBy]);- const visibleRows = showAll+ const visibleAgentRows = showAll? sortedRows: sortedRows.slice(0, LEADERBOARD_LIMIT);- // "N agents" counts the rows that actually name an agent. Up to two of the- // rows are synthetic buckets (deleted, restricted), and subtracting a fixed 1- // reported one agent too many whenever both were present.+ const visibleSquadRows = showAll+ ? sortedSquadRows+ : sortedSquadRows.slice(0, LEADERBOARD_LIMIT);+const namedAgentCount = useMemo(() => rows.filter((r) => !isSyntheticAgentRow(r.agentId)).length,[rows],);- // Active column gets foreground text; others stay muted. Helps the user- // see "this is what the bar is measuring" at a glance.+ const namedSquadCount = useMemo(+ () => squadRows.filter((r) => !isSyntheticSquadRow(r.squadId)).length,+ [squadRows],+ );++ const hasStandaloneSquadRow = useMemo(+ () => squadRows.some((r) => r.squadId === STANDALONE_SQUAD_ROW_ID),+ [squadRows],+ );+const colClass = (key: LeaderboardSort) =>`text-right ${sortBy === key ? "text-foreground" : "text-muted-foreground"}`;@@ -123,10 +175,174 @@ export function Leaderboard({return totalsPending ? t(($) => $.leaderboard.usage_totals_pending) : null;};+ const toggleSquad = (squadId: string) => {+ setExpandedSquads((prev) => ({ ...prev, [squadId]: !prev[squadId] }));+ };++ const renderAgentRow = (+ row: AgentDashboardRow,+ opts?: {+ indented?: boolean;+ parentMaxValue?: number;+ leaderId?: string;+ keyPrefix?: string;+ },+ ) => {+ const isDeletedBucket = row.agentId === DELETED_AGENTS_ROW_ID;+ const isRestrictedBucket = row.agentId === RESTRICTED_AGENTS_ROW_ID;+ const isBucket = isDeletedBucket || isRestrictedBucket;+ const agent = agents.find((a) => a.id === row.agentId);+ const value = SORT_METRIC[sortBy](row);+ const denom = opts?.parentMaxValue ?? maxValue;+ const pct = denom > 0 ? Math.min(100, (value / denom) * 100) : 0;+ const usageUnavailable = !row.hasUsageTotals;+ const usageIncomplete = row.unreportedTaskCount > 0;+ const usageTotalsPending = row.hasReportedUsage && !row.hasUsageTotals;+ const tokenText = usageUnavailable+ ? "—"+ : `${usageIncomplete ? "≥" : ""}${formatTokens(row.tokens)}`;+ const costText = usageUnavailable+ ? "—"+ : `${usageIncomplete ? "≥" : ""}$${row.cost.toFixed(2)}`;+ const coverageText = getCoverageText(+ row.unreportedTaskCount,+ usageTotalsPending,+ );+ const isLeader = !!opts?.leaderId && row.agentId === opts.leaderId;++ return (+ <li+ key={opts?.keyPrefix ? `${opts.keyPrefix}:${row.agentId}` : row.agentId}+ className={`${LEADERBOARD_GRID} px-4 ${opts?.indented ? "bg-muted/25 py-1.5" : "py-2"}`}+ style={LEADERBOARD_GRID_STYLE}+ >+ <div+ className={`flex min-w-0 items-center gap-2 ${opts?.indented ? "pl-7" : ""}`}+ >+ {isBucket ? (+ <>+ <span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">+ {isDeletedBucket ? (+ <Trash2 className="h-3 w-3" />+ ) : (+ <EyeOff className="h-3 w-3" />+ )}+ </span>+ <span className="min-w-0">+ <span className="block truncate text-body font-medium italic text-muted-foreground">+ {isDeletedBucket+ ? t(($) => $.leaderboard.deleted_agents)+ : t(($) => $.leaderboard.other_agents)}+ </span>+ {coverageText ? (+ <TruncatedTooltip content={coverageText}>+ <span className="block truncate text-caption text-muted-foreground">+ {coverageText}+ </span>+ </TruncatedTooltip>+ ) : null}+ </span>+ </>+ ) : (+ <>+ <ActorAvatar+ actorType="agent"+ actorId={row.agentId}+ size={opts?.indented ? "sm" : "md"}+ enableHoverCard+ />+ <span className="min-w-0">+ <span className="flex min-w-0 items-center gap-1.5">+ <span+ className={`block cursor-pointer truncate font-medium ${opts?.indented ? "text-label" : "text-body"}`}+ >+ {agent?.name ?? row.agentId}+ </span>+ {isLeader ? (+ <span className="shrink-0 rounded-md bg-amber-100 px-1 py-0.5 text-micro font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">+ {tSquads(($) => $.members_tab.leader_chip)}+ </span>+ ) : null}+ </span>+ {coverageText ? (+ <TruncatedTooltip content={coverageText}>+ <span className="block truncate text-caption text-muted-foreground">+ {coverageText}+ </span>+ </TruncatedTooltip>+ ) : null}+ </span>+ </>+ )}+ </div>+ <div className="relative h-2 overflow-hidden rounded-full bg-muted">+ <div+ className={`h-full rounded-full transition-[width] duration-300 ease-out ${+ opts?.indented ? "bg-chart-3" : "bg-chart-1"+ }`}+ style={{ width: `${pct}%` }}+ />+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "tokens" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {tokenText}+ </div>+ <div+ className={`text-right tabular-nums ${sortBy === "cost" ? "text-body font-medium" : "text-caption text-muted-foreground"}`}+ >+ {costText}+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "time" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {isDeletedBucket+ ? "—"+ : formatDuration(row.seconds, lessThanMinuteLabel)}+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "tasks" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {isDeletedBucket ? "—" : row.taskCount}+ </div>+ </li>+ );+ };+return (<div className="rounded-lg border bg-card"><div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">- <h4 className="text-body font-semibold">{t(($) => $.leaderboard.title)}</h4>+ <div className="flex flex-wrap items-center gap-2.5">+ {selectedSquad ? (+ <div className="flex items-center gap-2">+ <ActorAvatarBase+ name={selectedSquad.name}+ initials={selectedSquad.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(selectedSquad.avatar_url)}+ isSquad+ size="sm"+ />+ <h4 className="text-body font-semibold">+ {t(($) => $.leaderboard.squad_members_title, {+ name: selectedSquad.name,+ })}+ </h4>+ </div>+ ) : (+ <h4 className="text-body font-semibold">{t(($) => $.leaderboard.title)}</h4>+ )}+ {showGroupSwitch ? (+ <Segmented+ label={t(($) => $.leaderboard.group_label)}+ value={effectiveGroupBy}+ onChange={(next) => {+ setShowAll(false);+ onGroupByChange(next);+ }}+ options={groupOptions}+ />+ ) : null}+ </div><div className="flex flex-wrap items-center justify-end gap-3"><Segmentedlabel={t(($) => $.leaderboard.sort_label)}@@ -135,18 +351,22 @@ export function Leaderboard({options={sortOptions}/><span className="text-caption text-muted-foreground">- {deletedAgentCount > 0- ? t(($) => $.leaderboard.caption_with_deleted, {- count: namedAgentCount,- deleted: deletedAgentCount,- })- : t(($) => $.leaderboard.caption, { count: namedAgentCount })}+ {effectiveGroupBy === "squad"+ ? hasStandaloneSquadRow+ ? t(($) => $.leaderboard.squad_caption_with_standalone, {+ count: namedSquadCount,+ })+ : t(($) => $.leaderboard.squad_caption, {+ count: namedSquadCount,+ })+ : deletedAgentCount > 0+ ? t(($) => $.leaderboard.caption_with_deleted, {+ count: namedAgentCount,+ deleted: deletedAgentCount,+ })+ : t(($) => $.leaderboard.caption, { count: namedAgentCount })}</span>- {/* The caption right beside this already states how many agents the- window covers, so the toggle carries a count only when- collapsing — spelling the total out twice reads as two different- numbers once the deleted-agents bucket splits the caption. */}- {sortedRows.length > LEADERBOARD_LIMIT ? (+ {activeRows.length > LEADERBOARD_LIMIT ? (<buttontype="button"onClick={() => setShowAll((v) => !v)}@@ -159,7 +379,7 @@ export function Leaderboard({) : null}</div></div>- {sortedRows.length === 0 ? (+ {activeRows.length === 0 ? (<p className="px-4 py-8 text-center text-caption text-muted-foreground">{t(($) => $.leaderboard.no_data)}</p>@@ -175,7 +395,11 @@ export function Leaderboard({className={`${LEADERBOARD_GRID} border-b px-4 py-2 text-caption font-medium text-muted-foreground`}style={LEADERBOARD_GRID_STYLE}>- <span>{t(($) => $.leaderboard.header_agent)}</span>+ <span>+ {effectiveGroupBy === "squad"+ ? t(($) => $.leaderboard.header_squad)+ : t(($) => $.leaderboard.header_agent)}+ </span><span /><span className={colClass("tokens")}>{t(($) => $.leaderboard.header_tokens)}@@ -190,136 +414,161 @@ export function Leaderboard({{t(($) => $.leaderboard.header_tasks)}</span></div>- {/* A real list, like the offender list on the Errors tab: the rows are- a truncated ranking, so screen readers need the count and the- item boundaries rather than a bag of divs. */}<ul aria-label={t(($) => $.leaderboard.title)} className="divide-y">- {visibleRows.map((row) => {- // Two synthetic rows, neither a real agent: both render a neutral- // placeholder (no avatar fetch / hover card / UUID) instead of- // looking the id up in the agent list.- //- // Only the deleted bucket dashes out Time/Tasks — it genuinely- // never carries them (see bucketUnknownAgentRows). The server's- // bucket does: those agents are alive and ran, the server just- // merged them (MUL-5409), so zeroing their columns would- // under-report the workspace's run time.- //- // Its copy is the neutral "Other agents" rather than anything- // about permissions, because it covers two populations: agents- // this viewer may not see, and the hidden system carriers behind- // agent-builder sessions, which nobody can name — including the- // admin who owns them.- const isDeletedBucket = row.agentId === DELETED_AGENTS_ROW_ID;- const isRestrictedBucket =- row.agentId === RESTRICTED_AGENTS_ROW_ID;- const isBucket = isDeletedBucket || isRestrictedBucket;- const agent = agents.find((a) => a.id === row.agentId);- const value = SORT_METRIC[sortBy](row);- const pct = maxValue > 0 ? (value / maxValue) * 100 : 0;- const usageUnavailable = !row.hasUsageTotals;- const usageIncomplete = row.unreportedTaskCount > 0;- const usageTotalsPending =- row.hasReportedUsage && !row.hasUsageTotals;- const tokenText = usageUnavailable- ? "—"- : `${usageIncomplete ? "≥" : ""}${formatTokens(row.tokens)}`;- const costText = usageUnavailable- ? "—"- : `${usageIncomplete ? "≥" : ""}$${row.cost.toFixed(2)}`;- const coverageText = getCoverageText(- row.unreportedTaskCount,- usageTotalsPending,- );- return (- <li- key={row.agentId}- className={`${LEADERBOARD_GRID} px-4 py-2`}- style={LEADERBOARD_GRID_STYLE}- >- <div className="flex min-w-0 items-center gap-2">- {isBucket ? (- <>- <span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">- {isDeletedBucket ? (- <Trash2 className="h-3 w-3" />+ {effectiveGroupBy === "agent"+ ? visibleAgentRows.map((row) =>+ renderAgentRow(row, {+ leaderId: selectedSquad?.leader_id,+ }),+ )+ : visibleSquadRows.map((row) => {+ const isStandalone = row.squadId === STANDALONE_SQUAD_ROW_ID;+ const isDeleted = row.squadId === DELETED_SQUADS_ROW_ID;+ const isSynthetic = isStandalone || isDeleted;+ const squad = squads.find((s) => s.id === row.squadId);+ const value = SORT_METRIC[sortBy](row);+ const pct = maxValue > 0 ? (value / maxValue) * 100 : 0;+ const usageUnavailable = !row.hasUsageTotals;+ const usageIncomplete = row.unreportedTaskCount > 0;+ const usageTotalsPending =+ row.hasReportedUsage && !row.hasUsageTotals;+ const tokenText = usageUnavailable+ ? "—"+ : `${usageIncomplete ? "≥" : ""}${formatTokens(row.tokens)}`;+ const costText = usageUnavailable+ ? "—"+ : `${usageIncomplete ? "≥" : ""}$${row.cost.toFixed(2)}`;+ const coverageText = getCoverageText(+ row.unreportedTaskCount,+ usageTotalsPending,+ );+ const canExpand = row.members.length > 0;+ const expanded = canExpand && !!expandedSquads[row.squadId];+ const sortedMembers = expanded+ ? row.members.toSorted(+ (a, b) => SORT_METRIC[sortBy](b) - SORT_METRIC[sortBy](a),+ )+ : [];+ const namedMembersCount = row.members.filter(+ (m) => !isSyntheticAgentRow(m.agentId),+ ).length;++ return (+ <Fragment key={row.squadId}>+ <li+ className={`${LEADERBOARD_GRID} px-4 py-2 ${expanded ? "bg-muted/40" : ""}`}+ style={LEADERBOARD_GRID_STYLE}+ >+ <div className="flex min-w-0 items-center gap-2">+ {canExpand ? (+ <button+ type="button"+ onClick={() => toggleSquad(row.squadId)}+ aria-expanded={expanded}+ aria-label={t(($) => $.leaderboard.toggle_squad_members, {+ name: isStandalone+ ? t(($) => $.leaderboard.standalone_agents)+ : isDeleted+ ? t(($) => $.leaderboard.deleted_squads)+ : squad?.name ?? row.squadId,+ })}+ className="flex size-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ {expanded ? (+ <ChevronDown className="size-3.5" />+ ) : (+ <ChevronRight className="size-3.5" />+ )}+ </button>) : (- <EyeOff className="h-3 w-3" />+ <span className="size-5 shrink-0" aria-hidden="true" />)}- </span>- <span className="min-w-0">- <span className="block truncate text-body font-medium italic text-muted-foreground">- {isDeletedBucket- ? t(($) => $.leaderboard.deleted_agents)- : t(($) => $.leaderboard.other_agents)}- </span>- {coverageText ? (- <TruncatedTooltip content={coverageText}>- <span- className="block truncate text-caption text-muted-foreground"- >- {coverageText}- </span>- </TruncatedTooltip>- ) : null}- </span>- </>- ) : (- <>- <ActorAvatar- actorType="agent"- actorId={row.agentId}- size="md"- enableHoverCard- />- <span className="min-w-0">- <span className="block cursor-pointer truncate text-body font-medium">- {agent?.name ?? row.agentId}+ {isSynthetic ? (+ <span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">+ {isStandalone ? (+ <Bot className="h-3 w-3" />+ ) : (+ <Trash2 className="h-3 w-3" />+ )}+ </span>+ ) : (+ <ActorAvatar+ actorType="squad"+ actorId={row.squadId}+ size="md"+ enableHoverCard+ />+ )}+ <span className="min-w-0">+ <button+ type="button"+ onClick={() => canExpand && toggleSquad(row.squadId)}+ className={`block max-w-full truncate text-left text-body font-medium ${+ isSynthetic+ ? "italic text-muted-foreground"+ : "text-foreground"+ } ${canExpand ? "cursor-pointer hover:underline" : "cursor-default"}`}+ >+ {isStandalone+ ? t(($) => $.leaderboard.standalone_agents)+ : isDeleted+ ? t(($) => $.leaderboard.deleted_squads)+ : squad?.name ?? row.squadId}+ </button>+ <span className="block truncate text-caption text-muted-foreground">+ {coverageText ??+ (isStandalone+ ? t(($) => $.leaderboard.standalone_agents_hint, {+ count: namedMembersCount,+ })+ : t(($) => $.leaderboard.squad_members_count, {+ count: namedMembersCount,+ }))}+ </span></span>- {coverageText ? (- <TruncatedTooltip content={coverageText}>- <span- className="block truncate text-caption text-muted-foreground"- >- {coverageText}- </span>- </TruncatedTooltip>- ) : null}- </span>- </>- )}- </div>- <div className="relative h-2 overflow-hidden rounded-full bg-muted">- <div- className="h-full rounded-full bg-chart-1 transition-[width] duration-300 ease-out"- style={{ width: `${pct}%` }}- />- </div>- <div- className={`text-right text-caption tabular-nums ${sortBy === "tokens" ? "font-medium text-foreground" : "text-muted-foreground"}`}- >- {tokenText}- </div>- <div- className={`text-right tabular-nums ${sortBy === "cost" ? "text-body font-medium" : "text-caption text-muted-foreground"}`}- >- {costText}- </div>- <div- className={`text-right text-caption tabular-nums ${sortBy === "time" ? "font-medium text-foreground" : "text-muted-foreground"}`}- >- {isDeletedBucket- ? "—"- : formatDuration(row.seconds, lessThanMinuteLabel)}- </div>- <div- className={`text-right text-caption tabular-nums ${sortBy === "tasks" ? "font-medium text-foreground" : "text-muted-foreground"}`}- >- {isDeletedBucket ? "—" : row.taskCount}- </div>- </li>- );- })}+ </div>+ <div className="relative h-2 overflow-hidden rounded-full bg-muted">+ <div+ className={`h-full rounded-full transition-[width] duration-300 ease-out ${+ isStandalone ? "bg-chart-4" : "bg-chart-1"+ }`}+ style={{ width: `${pct}%` }}+ />+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "tokens" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {tokenText}+ </div>+ <div+ className={`text-right tabular-nums ${sortBy === "cost" ? "text-body font-medium" : "text-caption text-muted-foreground"}`}+ >+ {costText}+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "time" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {formatDuration(row.seconds, lessThanMinuteLabel)}+ </div>+ <div+ className={`text-right text-caption tabular-nums ${sortBy === "tasks" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {row.taskCount}+ </div>+ </li>+ {expanded+ ? sortedMembers.map((member) =>+ renderAgentRow(member, {+ indented: true,+ parentMaxValue: Math.max(value, 1),+ leaderId: squad?.leader_id,+ keyPrefix: row.squadId,+ }),+ )+ : null}+ </Fragment>+ );+ })}</ul></div></div>diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex f242dbb088..c48c7292e6 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -1,6 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {aggregateAgentFailures,+ aggregateSquadDashboardRows,+ aggregateSquadFailures,anonymizeUnresolvedAgentRows,UNRESOLVED_AGENTS_ROW_ID,aggregateAgentTokens,@@ -16,12 +18,16 @@ import {computeDailyTotals,computeFailureTotals,DELETED_AGENTS_ROW_ID,+ DELETED_SQUADS_ROW_ID,formatDuration,hasRateSample,isSyntheticAgentRow,+ isSyntheticSquadRow,mergeAgentDashboardRows,RESTRICTED_AGENTS_ROW_ID,sortAgentFailures,+ sortSquadFailures,+ STANDALONE_SQUAD_ROW_ID,} from "./utils";describe("aggregateDailyCost", () => {@@ -914,3 +920,109 @@ describe("anonymizeUnresolvedAgentRows", () => {expect(anonymizeUnresolvedAgentRows(rows, known)).toBe(rows);});});++describe("aggregateSquadDashboardRows", () => {+ it("groups leader + delegated member usage under each squad and preserves standalone reconciliation row", () => {+ const rows = aggregateSquadDashboardRows(+ [+ {+ squad_id: "squad-jsquad",+ agent_id: "xeon",+ provider: "claude",+ model: "claude-sonnet-4-6",+ input_tokens: 1_000_000,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ task_count: 2,+ },+ {+ squad_id: "squad-jsquad",+ agent_id: "emacs",+ provider: "claude",+ model: "claude-sonnet-4-6",+ input_tokens: 2_000_000,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ task_count: 3,+ },+ {+ squad_id: "",+ agent_id: "emacs",+ provider: "claude",+ model: "claude-sonnet-4-6",+ input_tokens: 500_000,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ task_count: 1,+ },+ ],+ [+ { squad_id: "squad-jsquad", agent_id: "xeon", total_seconds: 120, task_count: 2, failed_count: 0, cancelled_count: 0 },+ { squad_id: "squad-jsquad", agent_id: "emacs", total_seconds: 300, task_count: 3, failed_count: 1, cancelled_count: 0 },+ { squad_id: "", agent_id: "emacs", total_seconds: 60, task_count: 1, failed_count: 0, cancelled_count: 0 },+ ],+ new Set(["xeon", "emacs"]),+ new Set(["squad-jsquad"]),+ );++ expect(rows.map((r) => r.squadId)).toEqual(["squad-jsquad", STANDALONE_SQUAD_ROW_ID]);+ const jsquad = rows[0]!;+ expect(jsquad.tokens).toBe(3_000_000);+ expect(jsquad.cost).toBeCloseTo(9, 2);+ expect(jsquad.seconds).toBe(420);+ expect(jsquad.taskCount).toBe(5);+ expect(jsquad.members.map((m) => m.agentId)).toEqual(["emacs", "xeon"]);++ const standalone = rows[1]!;+ expect(isSyntheticSquadRow(standalone.squadId)).toBe(true);+ expect(standalone.tokens).toBe(500_000);+ expect(standalone.taskCount).toBe(1);+ expect(standalone.members.map((m) => m.agentId)).toEqual(["emacs"]);+ });++ it("buckets unknown/deleted squad IDs and unknown agents cleanly", () => {+ const rows = aggregateSquadDashboardRows(+ [],+ [+ { squad_id: "gone-squad", agent_id: "gone-agent", total_seconds: 180, task_count: 2, failed_count: 0, cancelled_count: 0 },+ ],+ new Set(["xeon"]),+ new Set(["squad-jsquad"]),+ );++ expect(rows).toHaveLength(1);+ expect(rows[0]!.squadId).toBe(DELETED_SQUADS_ROW_ID);+ expect(isSyntheticSquadRow(rows[0]!.squadId)).toBe(true);+ expect(rows[0]!.members.map((m) => m.agentId)).toEqual([DELETED_AGENTS_ROW_ID]);+ });+});++describe("aggregateSquadFailures & sortSquadFailures", () => {+ it("computes per-squad error rates and demotes small-sample squads on rate sort", () => {+ const rows = aggregateSquadFailures(+ [+ { squad_id: "squad-a", agent_id: "a1", failure_reason: "", task_count: 16 },+ { squad_id: "squad-a", agent_id: "a1", failure_reason: "timeout", task_count: 4 },+ { squad_id: "squad-b", agent_id: "a2", failure_reason: "timeout", task_count: 2 },+ { squad_id: "", agent_id: "a3", failure_reason: "", task_count: 10 },+ { squad_id: "", agent_id: "a3", failure_reason: "agent_error.provider_auth_or_access", task_count: 5 },+ ],+ new Set(["squad-a", "squad-b"]),+ );++ expect(sortSquadFailures(rows, "failed").map((r) => r.squadId)).toEqual([+ STANDALONE_SQUAD_ROW_ID,+ "squad-a",+ "squad-b",+ ]);+ // squad-b is 100% failed but only 2 runs (< MIN_RATE_SAMPLE=10), so demoted below squad-a (20%) & standalone (33.3%).+ expect(sortSquadFailures(rows, "rate").map((r) => r.squadId)).toEqual([+ STANDALONE_SQUAD_ROW_ID,+ "squad-a",+ "squad-b",+ ]);+ });+});diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex d80f075701..59502f00f4 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -1,10 +1,13 @@import type {DashboardUsageDaily,DashboardUsageByAgent,+ DashboardUsageBySquad,DashboardAgentRunTime,+ DashboardSquadRunTime,DashboardRunTimeDaily,DashboardFailureDaily,DashboardFailureByAgent,+ DashboardFailureBySquad,} from "@multica/core/types";import {FAILURE_CLASSES,@@ -837,3 +840,187 @@ export function anonymizeUnresolvedAgentRows(: { ...r, agent_id: UNRESOLVED_AGENTS_ROW_ID },);}++// Synthetic squadId sentinels for the Squad-grouped leaderboard & Errors tab.+export const STANDALONE_SQUAD_ROW_ID = "__standalone_squad__";+export const DELETED_SQUADS_ROW_ID = "__deleted_squads__";++export function isSyntheticSquadRow(squadId: string): boolean {+ return squadId === STANDALONE_SQUAD_ROW_ID || squadId === DELETED_SQUADS_ROW_ID;+}++export interface SquadDashboardRow {+ squadId: string;+ tokens: number;+ cost: number;+ seconds: number;+ taskCount: number;+ unreportedTaskCount: number;+ hasReportedUsage: boolean;+ hasUsageTotals: boolean;+ members: AgentDashboardRow[];+}++function normalizeSquadBucketId(+ rawSquadId: string,+ knownSquadIds: ReadonlySet<string> | null,+): string {+ if (!rawSquadId) return STANDALONE_SQUAD_ROW_ID;+ if (knownSquadIds && !knownSquadIds.has(rawSquadId)) {+ return DELETED_SQUADS_ROW_ID;+ }+ return rawSquadId;+}++/**+ * Aggregate per-(squad, agent, model) usage and per-(squad, agent) runtime+ * rows into squad-overall rows, each carrying its per-member breakdown so the+ * Leaderboard can expand any squad inline without an extra fetch.+ *+ * Non-squad-triggered runs (`squad_id === ""`) collect under+ * STANDALONE_SQUAD_ROW_ID so every metric reconciles 100% with the top KPIs.+ */+export function aggregateSquadDashboardRows(+ usageRows: DashboardUsageBySquad[],+ runTimeRows: DashboardSquadRunTime[],+ knownAgentIds: ReadonlySet<string> | null,+ knownSquadIds: ReadonlySet<string> | null,+): SquadDashboardRow[] {+ const usageBySquad = new Map<string, DashboardUsageByAgent[]>();+ for (const r of usageRows) {+ const key = normalizeSquadBucketId(r.squad_id, knownSquadIds);+ const list = usageBySquad.get(key) ?? [];+ list.push(r);+ usageBySquad.set(key, list);+ }++ const runTimeBySquad = new Map<string, Map<string, DashboardAgentRunTime>>();+ for (const r of runTimeRows) {+ const key = normalizeSquadBucketId(r.squad_id, knownSquadIds);+ let agentMap = runTimeBySquad.get(key);+ if (!agentMap) {+ agentMap = new Map();+ runTimeBySquad.set(key, agentMap);+ }+ const existing = agentMap.get(r.agent_id);+ if (existing) {+ existing.total_seconds += r.total_seconds;+ existing.task_count += r.task_count;+ existing.failed_count += r.failed_count;+ existing.cancelled_count += r.cancelled_count;+ if (existing.metered_task_count !== undefined || r.metered_task_count !== undefined) {+ existing.metered_task_count =+ (existing.metered_task_count ?? 0) + (r.metered_task_count ?? 0);+ }+ } else {+ agentMap.set(r.agent_id, {+ agent_id: r.agent_id,+ total_seconds: r.total_seconds,+ task_count: r.task_count,+ metered_task_count: r.metered_task_count,+ failed_count: r.failed_count,+ cancelled_count: r.cancelled_count,+ });+ }+ }++ const allSquadKeys = new Set<string>([+ ...usageBySquad.keys(),+ ...runTimeBySquad.keys(),+ ]);++ const rows: SquadDashboardRow[] = [];+ for (const squadId of allSquadKeys) {+ const tokenRows = aggregateAgentTokens(usageBySquad.get(squadId) ?? []);+ const rtRows = Array.from(runTimeBySquad.get(squadId)?.values() ?? []);+ const mergedMembers = mergeAgentDashboardRows(tokenRows, rtRows);+ const members = bucketUnknownAgentRows(mergedMembers, knownAgentIds);++ let tokens = 0;+ let cost = 0;+ let seconds = 0;+ let taskCount = 0;+ let unreportedTaskCount = 0;+ let hasReportedUsage = false;+ let hasUsageTotals = false;+ for (const m of members) {+ tokens += m.tokens;+ cost += m.cost;+ seconds += m.seconds;+ taskCount += m.taskCount;+ unreportedTaskCount += m.unreportedTaskCount;+ hasReportedUsage ||= m.hasReportedUsage;+ hasUsageTotals ||= m.hasUsageTotals;+ }++ rows.push({+ squadId,+ tokens,+ cost,+ seconds,+ taskCount,+ unreportedTaskCount,+ hasReportedUsage,+ hasUsageTotals,+ members,+ });+ }++ return rows.toSorted((a, b) => {+ if (b.cost !== a.cost) return b.cost - a.cost;+ return b.seconds - a.seconds;+ });+}++export interface SquadFailureRow {+ squadId: string;+ failed: number;+ total: number;+ rate: number;+ classes: FailureClassCounts;+}++export function aggregateSquadFailures(+ rows: DashboardFailureBySquad[],+ knownSquadIds: ReadonlySet<string> | null,+): SquadFailureRow[] {+ const map = new Map<+ string,+ { failed: number; total: number; classes: FailureClassCounts }+ >();+ for (const r of rows) {+ const key = normalizeSquadBucketId(r.squad_id, knownSquadIds);+ let entry = map.get(key);+ if (!entry) {+ entry = { failed: 0, total: 0, classes: emptyClassCounts() };+ map.set(key, entry);+ }+ entry.total += r.task_count;+ if (r.failure_reason === "") continue;+ entry.failed += r.task_count;+ entry.classes[failureClassOf(r.failure_reason)] += r.task_count;+ }+ return Array.from(map.entries())+ .filter(([, v]) => v.failed > 0)+ .map(([squadId, v]) => ({+ squadId,+ failed: v.failed,+ total: v.total,+ rate: v.total > 0 ? v.failed / v.total : 0,+ classes: v.classes,+ }))+ .toSorted((a, b) => b.failed - a.failed || b.rate - a.rate);+}++export function sortSquadFailures(+ rows: SquadFailureRow[],+ sortBy: OffenderSort,+): SquadFailureRow[] {+ if (sortBy === "failed") {+ return rows.toSorted((a, b) => b.failed - a.failed || b.rate - a.rate);+ }+ const sample = (r: SquadFailureRow) => (r.total >= MIN_RATE_SAMPLE ? 0 : 1);+ return rows.toSorted(+ (a, b) => sample(a) - sample(b) || b.rate - a.rate || b.failed - a.failed,+ );+}diff --git a/packages/views/issues/components/issue-agent-activity-indicator.tsx b/packages/views/issues/components/issue-agent-activity-indicator.tsxindex fd0f05260b..5e2e5b31c4 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.tsx@@ -11,6 +11,7 @@ import {} from "@multica/ui/components/ui/hover-card";import { useWorkspaceId } from "@multica/core/hooks";import { agentTaskSnapshotOptions } from "@multica/core/agents";+import { squadListOptions } from "@multica/core/workspace/queries";import type { AgentTask, IssueWakeupSummaryRow, PausedWakeup } from "@multica/core/types";import { pausedWakeupsOptions, workspaceWakeupSummariesOptions } from "@multica/core/issues/wakeups";import { cn } from "@multica/ui/lib/utils";@@ -18,6 +19,7 @@ import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { AgentActivityHoverContent } from "../../agents/components/agent-activity-hover-content";import { selectIssueTasks, type IssueTaskGroups } from "../surface/activity";+import { groupExecutionTasksByActor } from "../surface/execution-actors";import { useT } from "../../i18n";import { useWakeupText } from "./wakeup-presentation";@@ -126,20 +128,28 @@ export const IssueAgentActivityIndicator = memo(select,});- const { agentIds, opacity } = useMemo(() => {+ const { data: squads } = useQuery(squadListOptions(wsId));+ const knownSquadIds = useMemo(+ () => (squads ? new Set(squads.map((s) => s.id)) : null),+ [squads],+ );++ const { agentIds, actors, opacity } = useMemo(() => {// Stack heads: prefer running. If 0 running, fall back to queued.// Each case is visually distinct (running gets shimmer, queued gets// muted text) so the indicator always offers a face to hover.const primary =groups.running.length > 0 ? groups.running : groups.queued;const uniqueAgents = [...new Set(primary.map((t) => t.agent_id))];+ const grouped = groupExecutionTasksByActor(primary, knownSquadIds);return {agentIds: uniqueAgents,+ actors: grouped.map(({ type, id }) => ({ type, id })),opacity: (groups.running.length > 0 ? "full" : "half") as| "full"| "half",};- }, [groups]);+ }, [groups, knownSquadIds]);const wakeupCount = wakeups[0]?.active_count ?? 0;const hasTasks = agentIds.length > 0;@@ -164,6 +174,7 @@ export const IssueAgentActivityIndicator = memo(<><AgentAvatarStackagentIds={agentIds}+ actors={actors}size={size}opacity={opacity}max={3}diff --git a/packages/views/issues/components/issue-agent-header-chip.test.tsx b/packages/views/issues/components/issue-agent-header-chip.test.tsxindex b85c18a79c..3c8f41a0f9 100644--- a/packages/views/issues/components/issue-agent-header-chip.test.tsx+++ b/packages/views/issues/components/issue-agent-header-chip.test.tsx@@ -25,17 +25,23 @@ vi.mock("@multica/core/api", () => ({vi.mock("@multica/core/workspace/hooks", () => ({useActorName: () => ({- getActorName: (_type: string, id: string) =>- ({- "agent-1": "Walt",- "agent-2": "Gus",- })[id] ?? "Unknown Agent",- getActorInitials: (_type: string, id: string) =>- ({- "agent-1": "WA",- "agent-2": "GU",- })[id] ?? "UA",+ getActorName: (type: string, id: string) =>+ type === "squad"+ ? ({ "squad-1": "JSquad" }[id] ?? "Unknown Squad")+ : ({+ "agent-1": "Walt",+ "agent-2": "Gus",+ }[id] ?? "Unknown Agent"),+ getActorInitials: (type: string, id: string) =>+ type === "squad"+ ? ({ "squad-1": "JS" }[id] ?? "US")+ : ({+ "agent-1": "WA",+ "agent-2": "GU",+ }[id] ?? "UA"),getActorAvatarUrl: () => null,+ hasActor: (type: string, id: string) =>+ type === "squad" ? id === "squad-1" : true,}),}));@@ -407,4 +413,36 @@ describe("IssueAgentHeaderChip", () => {expect(screen.queryByRole("button")).not.toBeInTheDocument();});++ it("collapses multiple members of the same squad into one squad chip and groups them in the popover", () => {+ mockState.tasks = [+ makeTask({ id: "task-1", agent_id: "agent-1", squad_id: "squad-1", is_leader_task: true }),+ makeTask({ id: "task-2", agent_id: "agent-2", squad_id: "squad-1", is_leader_task: false }),+ ];++ renderWithI18n(<IssueAgentHeaderChip issueId="issue-1" />, {+ locale: "zh-Hans",+ });++ expect(+ screen.getByRole("button", { name: "JSquad 在工作" }),+ ).toBeInTheDocument();+ // Both underlying member tasks remain visible inside the grouped popover.+ expect(screen.getAllByTestId("active-task-row")).toHaveLength(2);+ expect(+ screen.getByTestId("agent-popover-content").textContent,+ ).toContain("JSquad");+ });++ it("falls back to the underlying agent when a task references a deleted squad", () => {+ mockState.tasks = [+ makeTask({ id: "task-1", agent_id: "agent-1", squad_id: "deleted-squad" }),+ ];++ renderWithI18n(<IssueAgentHeaderChip issueId="issue-1" />);++ expect(+ screen.getByRole("button", { name: "Walt is working" }),+ ).toBeInTheDocument();+ });});diff --git a/packages/views/issues/components/issue-agent-header-chip.tsx b/packages/views/issues/components/issue-agent-header-chip.tsxindex 12b3a81ae1..40fc58b4d6 100644--- a/packages/views/issues/components/issue-agent-header-chip.tsx+++ b/packages/views/issues/components/issue-agent-header-chip.tsx@@ -8,6 +8,7 @@ import {PopoverTrigger,} from "@multica/ui/components/ui/popover";import { useActorName } from "@multica/core/workspace/hooks";+import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";import { cn } from "@multica/ui/lib/utils";import { BorderBeam } from "@multica/ui/components/common/border-beam";import { issueTasksOptions } from "@multica/core/issues/queries";@@ -17,6 +18,7 @@ import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { ActiveTaskRow } from "./execution-log-section";import { useT } from "../../i18n";import { compareActiveIssueTasks } from "./active-task-order";+import { groupExecutionTasksByActor } from "../surface/execution-actors";// Per-issue "is an agent working on this right now?" chip for the issue// detail header. Lives in the header (not the scrollable body) so the live@@ -140,41 +142,65 @@ function ActiveChip({onTranscriptOpenChange,}: ActiveChipProps) {const { t } = useT("issues");- const { getActorName } = useActorName();+ const { getActorName, getActorInitials, getActorAvatarUrl, hasActor } =+ useActorName();+ const isKnownSquad = useMemo(+ () => (hasActor ? (id: string) => hasActor("squad", id) !== false : null),+ [hasActor],+ );const [open, setOpen] = useState(false);const activeTasks = [...running, ...queued];const agentIds = [...new Set(activeTasks.map((task) => task.agent_id))];+ const groupedActors = useMemo(+ () => groupExecutionTasksByActor(activeTasks, isKnownSquad),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [running, queued, isKnownSquad],+ );+ const actors = groupedActors.map(({ type, id }) => ({ type, id }));+ const hasSquadGroup = groupedActors.some((group) => group.type === "squad");const anyRunning = running.length > 0;- const isSingle = agentIds.length === 1;+ const isSingle = groupedActors.length === 1;+ const singleActor = groupedActors[0];// Copy must follow the actual state: "is working" only when something is// truly running. With nothing running (queued / dispatched / parked on a- // path lock) the chip reads "is queued" so a not-yet-started agent isn't- // mislabelled as working.- const label = isSingle+ // path lock) the chip reads "is queued" so a not-yet-started agent or squad+ // isn't mislabelled as working.+ const label = isSingle && singleActor? t(($) =>anyRunning ? $.agent_live.is_working : $.agent_live.is_queued,- { name: getActorName("agent", agentIds[0] ?? "") },+ { name: getActorName(singleActor.type, singleActor.id) },): t(($) =>anyRunning? $.agent_activity.hover_header: $.agent_activity.hover_header_queued,- { count: agentIds.length },+ { count: groupedActors.length },);+ const renderTaskRow = (task: AgentTask) => (+ <ActiveTaskRow+ key={task.id}+ task={task}+ issueId={issueId}+ onJump={+ onJumpToRun+ ? () => {+ setOpen(false);+ onJumpToRun(task.id);+ }+ : undefined+ }+ onTranscriptOpenChange={(isOpen, fromKeyboard) => {+ onTranscriptOpenChange(task, isOpen, fromKeyboard === true);+ }}+ />+ );+return (<Popover open={open} onOpenChange={setOpen}>- {/* Hover opens the card so the live activity reads as a glanceable- status surface, not a click target. In Base UI the hover config- lives on the Trigger (a popover can have multiple triggers), not- the Root. The trigger stays a real button, so click and keyboard- (Enter/Space) still toggle it for touch and a11y. A short open- delay avoids flicker when the pointer merely passes over the chip;- the close delay keeps it open while the pointer travels across the- hover bridge into the interactive rows. */}<PopoverTriggeropenOnHoverdelay={150}@@ -183,11 +209,6 @@ function ActiveChip({<buttontype="button"aria-label={label}- // While an agent is actively running, the chip wears the- // brand border beam — a highlight sweeping around its rounded- // edge — so a triggered run is unmistakably "alive" in the- // header. Queued-only state stays calm (no beam) to reserve the- // motion for work that is genuinely in flight.className={cn("flex h-9 min-w-9 max-w-[11rem] items-center justify-center gap-1.5 rounded-md px-2 text-muted-foreground outline-none transition-colors hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring md:h-7 md:min-w-0 md:justify-start md:px-1.5",anyRunning && "relative bg-brand/5",@@ -197,6 +218,7 @@ function ActiveChip({><AgentAvatarStackagentIds={agentIds}+ actors={actors}size="sm"max={3}opacity={anyRunning ? "full" : "half"}@@ -213,34 +235,59 @@ function ActiveChip({</PopoverTrigger><PopoverContent align="end" keepMounted className="w-80"><div className="text-caption font-medium text-muted-foreground">- {t(- ($) =>- anyRunning- ? $.agent_activity.hover_header- : $.agent_activity.hover_header_queued,- { count: agentIds.length },- )}- </div>- <div className="flex flex-col gap-0.5">- {activeTasks.map((task) => (- <ActiveTaskRow- key={task.id}- task={task}- issueId={issueId}- onJump={- onJumpToRun- ? () => {- setOpen(false);- onJumpToRun(task.id);- }- : undefined- }- onTranscriptOpenChange={(open, fromKeyboard) => {- onTranscriptOpenChange(task, open, fromKeyboard === true);- }}- />- ))}+ {hasSquadGroup+ ? t(($) => $.agent_activity.hover_header_tasks, {+ count: activeTasks.length,+ })+ : t(+ ($) =>+ anyRunning+ ? $.agent_activity.hover_header+ : $.agent_activity.hover_header_queued,+ { count: agentIds.length },+ )}</div>+ {hasSquadGroup ? (+ <div className="mt-1.5 flex flex-col gap-2">+ {groupedActors.map((group) =>+ group.type === "squad" ? (+ <div+ key={`squad:${group.id}`}+ className="overflow-hidden rounded-lg border border-border/80 bg-surface"+ >+ <div className="flex items-center gap-2 border-b border-border/70 bg-muted/40 px-2.5 py-1.5">+ <ActorAvatarBase+ name={getActorName("squad", group.id)}+ initials={getActorInitials("squad", group.id)}+ avatarUrl={getActorAvatarUrl("squad", group.id)}+ isSquad+ size="sm"+ />+ <span className="min-w-0 flex-1 truncate text-caption font-semibold text-foreground">+ {getActorName("squad", group.id)}+ </span>+ <span className="shrink-0 text-micro tabular-nums text-muted-foreground">+ {t(($) => $.agent_activity.tasks_count, {+ count: group.tasks.length,+ })}+ </span>+ </div>+ <div className="flex flex-col gap-0.5 p-1">+ {group.tasks.map(renderTaskRow)}+ </div>+ </div>+ ) : (+ <div key={`agent:${group.id}`} className="flex flex-col gap-0.5">+ {group.tasks.map(renderTaskRow)}+ </div>+ ),+ )}+ </div>+ ) : (+ <div className="flex flex-col gap-0.5">+ {activeTasks.map(renderTaskRow)}+ </div>+ )}</PopoverContent></Popover>);diff --git a/packages/views/issues/components/sub-issues-agent-working-chip.test.tsx b/packages/views/issues/components/sub-issues-agent-working-chip.test.tsxindex 922451e4ab..461b545dbf 100644--- a/packages/views/issues/components/sub-issues-agent-working-chip.test.tsx+++ b/packages/views/issues/components/sub-issues-agent-working-chip.test.tsx@@ -25,6 +25,15 @@ vi.mock("../../agents/components/agent-avatar-stack", () => ({}));vi.mock("./workspace-agent-working-chip", () => ({+ useWorkingExecutionUnits: (+ agents: readonly WorkspaceWorkingAgent[] | undefined,+ ) =>+ agents?.map((agent) => ({+ type: "agent" as const,+ id: agent.id,+ runningTaskCount: agent.running_task_count,+ memberAgentIds: [agent.id],+ })),WorkingAgentsHoverContent: ({agents,}: {diff --git a/packages/views/issues/components/sub-issues-agent-working-chip.tsx b/packages/views/issues/components/sub-issues-agent-working-chip.tsxindex 4b86a1d847..f02716a8db 100644--- a/packages/views/issues/components/sub-issues-agent-working-chip.tsx+++ b/packages/views/issues/components/sub-issues-agent-working-chip.tsx@@ -11,7 +11,10 @@ import {import { useWorkspaceId } from "@multica/core/hooks";import { workspaceWorkingAgentsOptions } from "@multica/core/agents";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";-import { WorkingAgentsHoverContent } from "./workspace-agent-working-chip";+import {+ useWorkingExecutionUnits,+ WorkingAgentsHoverContent,+} from "./workspace-agent-working-chip";import { useT } from "../../i18n";interface SubIssuesAgentWorkingChipProps {@@ -46,10 +49,13 @@ export const SubIssuesAgentWorkingChip = memo(const { data: agents = [] } = useQuery(workspaceWorkingAgentsOptions(wsId, "issue", undefined, parentIssueId),);+ const units = useWorkingExecutionUnits(agents);if (agents.length === 0) return null;const agentIds = agents.map((agent) => agent.id);+ const actors = units?.map(({ type, id }) => ({ type, id })) ?? [];+ const count = units?.length ?? agentIds.length;return (<HoverCard>@@ -58,15 +64,15 @@ export const SubIssuesAgentWorkingChip = memo(<span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-muted/60 px-2 py-0.5" />}>- <AgentAvatarStack agentIds={agentIds} size="xs" max={3} />+ <AgentAvatarStack agentIds={agentIds} actors={actors} size="xs" max={3} /><ShimmerText className="text-micro font-medium tabular-nums">{t(($) => $.agent_activity.chip_agents_working, {- count: agentIds.length,+ count,})}</ShimmerText></HoverCardTrigger><HoverCardContent align="start" className="w-72">- <WorkingAgentsHoverContent agents={agents} />+ <WorkingAgentsHoverContent agents={agents} units={units} /></HoverCardContent></HoverCard>);diff --git a/packages/views/issues/components/workspace-agent-working-chip.test.tsx b/packages/views/issues/components/workspace-agent-working-chip.test.tsxindex fbdf59a9e9..9140e11f03 100644--- a/packages/views/issues/components/workspace-agent-working-chip.test.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.test.tsx@@ -2,19 +2,37 @@import { cleanup, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import type { WorkingAgentSummary } from "@multica/core/types";+import type { AgentTask, WorkingAgentSummary } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";const mockState = vi.hoisted(() => ({avatarAgentIds: undefined as readonly string[] | undefined,buttonVariant: undefined as string | undefined,+ snapshot: [] as AgentTask[],}));+vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@tanstack/react-query", async () => {+ const actual =+ await vi.importActual<typeof import("@tanstack/react-query")>(+ "@tanstack/react-query",+ );+ return {+ ...actual,+ useQuery: () => ({ data: mockState.snapshot }),+ };+});+vi.mock("@multica/core/workspace/hooks", () => ({useActorName: () => ({- getActorName: (_type: string, id: string) => `Agent ${id}`,+ getActorName: (type: string, id: string) =>+ type === "squad" ? `Squad ${id}` : `Agent ${id}`,getActorInitials: () => "AG",getActorAvatarUrl: () => null,+ hasActor: () => true,}),}));diff --git a/packages/views/issues/components/workspace-agent-working-chip.tsx b/packages/views/issues/components/workspace-agent-working-chip.tsxindex 0c2f467ce5..ba338f7805 100644--- a/packages/views/issues/components/workspace-agent-working-chip.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx@@ -1,5 +1,7 @@"use client";+import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";import {@@ -7,11 +9,38 @@ import {HoverCardContent,HoverCardTrigger,} from "@multica/ui/components/ui/hover-card";+import { useWorkspaceId } from "@multica/core/hooks";+import { agentTaskSnapshotOptions } from "@multica/core/agents";import { useActorName } from "@multica/core/workspace/hooks";-import type { WorkingAgentSummary } from "@multica/core/types";+import type { AgentTask, WorkingAgentSummary } from "@multica/core/types";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";+import {+ collapseWorkingAgentsWithSnapshot,+ type WorkingExecutionUnit,+} from "../surface/execution-actors";import { useT } from "../../i18n";+const EMPTY_SNAPSHOT: AgentTask[] = [];++export function useWorkingExecutionUnits(+ agents: readonly WorkingAgentSummary[] | undefined,+): WorkingExecutionUnit[] | undefined {+ const wsId = useWorkspaceId();+ const { hasActor } = useActorName();+ const { data: snapshot = EMPTY_SNAPSHOT } = useQuery({+ ...agentTaskSnapshotOptions(wsId),+ enabled: Boolean(wsId) && (agents?.length ?? 0) > 0,+ });+ const isKnownSquad = useMemo(+ () => (hasActor ? (id: string) => hasActor("squad", id) !== false : null),+ [hasActor],+ );+ return useMemo(() => {+ if (agents === undefined) return undefined;+ return collapseWorkingAgentsWithSnapshot(agents, snapshot, isKnownSquad);+ }, [agents, snapshot, isKnownSquad]);+}+interface WorkspaceAgentWorkingChipProps {value: boolean;onToggle: () => void;@@ -72,13 +101,17 @@ export function chipAppearance(*/export function WorkingAgentsHoverContent({agents,+ units: unitsProp,}: {agents: readonly WorkingAgentSummary[] | undefined;+ units?: readonly WorkingExecutionUnit[] | undefined;}) {const { t } = useT("issues");const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();+ const derivedUnits = useWorkingExecutionUnits(unitsProp === undefined ? agents : undefined);+ const units = unitsProp ?? derivedUnits;- if (agents === undefined) {+ if (units === undefined) {return (<p className="text-caption text-muted-foreground">{t(($) => $.agent_activity.unknown_hover)}@@ -86,7 +119,7 @@ export function WorkingAgentsHoverContent({);}- if (agents.length === 0) {+ if (units.length === 0) {return (<p className="text-caption text-muted-foreground">{t(($) => $.agent_activity.empty_hover)}@@ -97,28 +130,40 @@ export function WorkingAgentsHoverContent({return (<div className="flex flex-col gap-2"><div className="text-caption font-medium text-muted-foreground">- {t(($) => $.agent_activity.hover_header, { count: agents.length })}+ {t(($) => $.agent_activity.hover_header, { count: units.length })}</div><div className="flex flex-col gap-1.5">- {agents.map((agent) => (- <div key={agent.id} className="flex items-center gap-2 text-caption">- <ActorAvatar- name={getActorName("agent", agent.id)}- initials={getActorInitials("agent", agent.id)}- avatarUrl={getActorAvatarUrl("agent", agent.id) ?? undefined}- isAgent- size="sm"- />- <span className="min-w-0 flex-1 truncate font-medium">- {getActorName("agent", agent.id)}- </span>- <span className="shrink-0 tabular-nums text-muted-foreground">- {t(($) => $.agent_activity.tasks_count, {- count: agent.running_task_count,- })}- </span>- </div>- ))}+ {units.map((unit) => {+ const memberNames =+ unit.type === "squad" && unit.memberAgentIds.length > 0+ ? unit.memberAgentIds+ .map((id) => getActorName("agent", id))+ .join("、")+ : null;+ return (+ <div key={`${unit.type}:${unit.id}`} className="flex items-center gap-2 text-caption">+ <ActorAvatar+ name={getActorName(unit.type, unit.id)}+ initials={getActorInitials(unit.type, unit.id)}+ avatarUrl={getActorAvatarUrl(unit.type, unit.id) ?? undefined}+ isAgent={unit.type === "agent"}+ isSquad={unit.type === "squad"}+ size="sm"+ />+ <span className="min-w-0 flex-1 truncate">+ <span className="font-medium">{getActorName(unit.type, unit.id)}</span>+ {memberNames ? (+ <span className="ml-1 text-muted-foreground">({memberNames})</span>+ ) : null}+ </span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {t(($) => $.agent_activity.tasks_count, {+ count: unit.runningTaskCount,+ })}+ </span>+ </div>+ );+ })}</div></div>);@@ -149,12 +194,15 @@ export function WorkspaceAgentWorkingChip({compact = false,}: WorkspaceAgentWorkingChipProps) {const { t } = useT("issues");+ const units = useWorkingExecutionUnits(agents);const activity = chipActivity(agents);const agentIds = agents?.map((agent) => agent.id) ?? [];+ const actors = units?.map(({ type, id }) => ({ type, id })) ?? [];+ const count = units?.length ?? 0;const label =activity === "unknown"? t(($) => $.agent_activity.chip_agents_working_unknown)- : t(($) => $.agent_activity.chip_agents_working, { count: agentIds.length });+ : t(($) => $.agent_activity.chip_agents_working, { count });const appearance = chipAppearance(value, activity);const trigger = (@@ -167,10 +215,10 @@ export function WorkspaceAgentWorkingChip({aria-label={label}>{activity === "some" && (- <AgentAvatarStack agentIds={agentIds} size="sm" max={3} />+ <AgentAvatarStack agentIds={agentIds} actors={actors} size="sm" max={3} />)}<span className={compact ? "tabular-nums" : "tabular-nums md:hidden @max-3xl/issue-header:inline"}>- {activity === "unknown" ? "—" : agentIds.length}+ {activity === "unknown" ? "—" : count}</span>{!compact && (<span className="hidden tabular-nums md:inline @max-3xl/issue-header:hidden">{label}</span>@@ -182,10 +230,7 @@ export function WorkspaceAgentWorkingChip({<HoverCard><HoverCardTrigger render={trigger} /><HoverCardContent align="end" className="w-72">- {/* Pass the projection through untouched. Defaulting to [] here would- hand the hover card a definite "nobody is working" for a state we- have not resolved. */}- <WorkingAgentsHoverContent agents={agents} />+ <WorkingAgentsHoverContent agents={agents} units={units} /></HoverCardContent></HoverCard>);diff --git a/packages/views/issues/surface/execution-actors.test.ts b/packages/views/issues/surface/execution-actors.test.tsnew file mode 100644index 0000000000..52e29c7be6--- /dev/null+++ b/packages/views/issues/surface/execution-actors.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from "vitest";+import type { AgentTask, WorkingAgentSummary } from "@multica/core/types";+import {+ collapseWorkingAgentsWithSnapshot,+ groupExecutionTasksByActor,+} from "./execution-actors";++function makeTask(overrides: Partial<AgentTask> & { id: string; agent_id: string }): AgentTask {+ return {+ runtime_id: "rt-1",+ issue_id: "issue-1",+ status: "running",+ priority: 0,+ dispatched_at: null,+ started_at: "2026-11-24T00:00:00Z",+ completed_at: null,+ result: null,+ error: null,+ created_at: "2026-11-24T00:00:00Z",+ ...overrides,+ };+}++describe("groupExecutionTasksByActor", () => {+ it("collapses leader and delegated member tasks sharing a squad_id into one squad unit", () => {+ const tasks: AgentTask[] = [+ makeTask({ id: "t1", agent_id: "emacs", squad_id: "jsquad", status: "running" }),+ makeTask({ id: "t2", agent_id: "lambda", squad_id: "jsquad", status: "queued" }),+ makeTask({ id: "t3", agent_id: "codex", status: "running" }),+ ];++ const groups = groupExecutionTasksByActor(tasks, new Set(["jsquad"]));+ expect(groups).toHaveLength(2);+ expect(groups[0]).toMatchObject({+ type: "squad",+ id: "jsquad",+ runningCount: 1,+ queuedCount: 1,+ agentIds: ["emacs", "lambda"],+ });+ expect(groups[0]?.tasks.map((t) => t.id)).toEqual(["t1", "t2"]);+ expect(groups[1]).toMatchObject({+ type: "agent",+ id: "codex",+ runningCount: 1,+ queuedCount: 0,+ agentIds: ["codex"],+ });+ });++ it("falls back to agent when squad_id is not in knownSquadIds", () => {+ const tasks: AgentTask[] = [+ makeTask({ id: "t1", agent_id: "emacs", squad_id: "deleted-squad" }),+ ];++ const groups = groupExecutionTasksByActor(tasks, new Set(["jsquad"]));+ expect(groups).toHaveLength(1);+ expect(groups[0]).toMatchObject({+ type: "agent",+ id: "emacs",+ agentIds: ["emacs"],+ });+ });+});++describe("collapseWorkingAgentsWithSnapshot", () => {+ it("collapses squad members into one squad execution unit and preserves standalone agents", () => {+ const workingAgents: WorkingAgentSummary[] = [+ { id: "emacs", running_task_count: 1 },+ { id: "lambda", running_task_count: 1 },+ { id: "codex", running_task_count: 2 },+ ];+ const snapshot: AgentTask[] = [+ makeTask({ id: "t1", agent_id: "emacs", squad_id: "jsquad", status: "running" }),+ makeTask({ id: "t2", agent_id: "lambda", squad_id: "jsquad", status: "running" }),+ makeTask({ id: "t3", agent_id: "codex", status: "running" }),+ makeTask({ id: "t4", agent_id: "codex", status: "running" }),+ ];++ const units = collapseWorkingAgentsWithSnapshot(+ workingAgents,+ snapshot,+ new Set(["jsquad"]),+ );+ expect(units).toEqual([+ {+ type: "squad",+ id: "jsquad",+ runningTaskCount: 2,+ memberAgentIds: ["emacs", "lambda"],+ },+ {+ type: "agent",+ id: "codex",+ runningTaskCount: 2,+ memberAgentIds: [],+ },+ ]);+ });++ it("caps attributed counts to the surface-projected running_task_count", () => {+ const workingAgents: WorkingAgentSummary[] = [+ { id: "emacs", running_task_count: 1 },+ ];+ const snapshot: AgentTask[] = [+ makeTask({ id: "t1", agent_id: "emacs", squad_id: "jsquad", status: "running" }),+ makeTask({ id: "t2", agent_id: "emacs", squad_id: "jsquad", status: "running" }),+ makeTask({ id: "t3", agent_id: "emacs", status: "running" }),+ ];++ const units = collapseWorkingAgentsWithSnapshot(+ workingAgents,+ snapshot,+ new Set(["jsquad"]),+ );+ expect(units).toEqual([+ {+ type: "squad",+ id: "jsquad",+ runningTaskCount: 1,+ memberAgentIds: ["emacs"],+ },+ ]);+ });++ it("falls back to raw working agents when snapshot has not loaded yet", () => {+ const workingAgents: WorkingAgentSummary[] = [+ { id: "emacs", running_task_count: 2 },+ ];+ expect(collapseWorkingAgentsWithSnapshot(workingAgents, [], null)).toEqual([+ {+ type: "agent",+ id: "emacs",+ runningTaskCount: 2,+ memberAgentIds: [],+ },+ ]);+ });+});diff --git a/packages/views/issues/surface/execution-actors.ts b/packages/views/issues/surface/execution-actors.tsnew file mode 100644index 0000000000..a6fc564420--- /dev/null+++ b/packages/views/issues/surface/execution-actors.ts@@ -0,0 +1,168 @@+import type { AgentTask, WorkingAgentSummary } from "@multica/core/types";++export interface ExecutionActorRef {+ type: "agent" | "squad";+ id: string;+}++export interface GroupedExecutionActor extends ExecutionActorRef {+ tasks: AgentTask[];+ runningCount: number;+ queuedCount: number;+ agentIds: string[];+}++export type KnownSquadLookup =+ | ReadonlySet<string>+ | ((squadId: string) => boolean)+ | null+ | undefined;++function resolvesToKnownSquad(lookup: KnownSquadLookup, squadId: string): boolean {+ if (!lookup) return true;+ if (typeof lookup === "function") return lookup(squadId);+ return lookup.has(squadId);+}++/**+ * Collapse active tasks that belong to a squad execution chain (leader or+ * delegated member carrying `squad_id`) into a single squad execution unit,+ * while keeping standalone agent tasks grouped by `agent_id`.+ *+ * When `knownSquadIds` is provided, tasks whose `squad_id` no longer resolves+ * to a workspace squad fall back to their underlying `agent_id` so the UI+ * never renders a dangling UUID or anonymous placeholder.+ */+export function groupExecutionTasksByActor(+ tasks: readonly AgentTask[],+ knownSquadIds?: KnownSquadLookup,+): GroupedExecutionActor[] {+ const groups = new Map<string, GroupedExecutionActor>();+ for (const task of tasks) {+ const squadId = task.squad_id?.trim() || "";+ const useSquad =+ squadId.length > 0 && resolvesToKnownSquad(knownSquadIds, squadId);+ const type: "agent" | "squad" = useSquad ? "squad" : "agent";+ const id = useSquad ? squadId : task.agent_id;+ if (!id) continue;+ const key = `${type}:${id}`;+ let entry = groups.get(key);+ if (!entry) {+ entry = {+ type,+ id,+ tasks: [],+ runningCount: 0,+ queuedCount: 0,+ agentIds: [],+ };+ groups.set(key, entry);+ }+ entry.tasks.push(task);+ if (task.status === "running") entry.runningCount += 1;+ else entry.queuedCount += 1;+ if (task.agent_id && !entry.agentIds.includes(task.agent_id)) {+ entry.agentIds.push(task.agent_id);+ }+ }+ return Array.from(groups.values());+}++export interface WorkingExecutionUnit extends ExecutionActorRef {+ runningTaskCount: number;+ memberAgentIds: string[];+}++/**+ * Derive squad-collapsed working execution units for header chips+ * (`WorkspaceAgentWorkingChip` / `SubIssuesAgentWorkingChip`).+ *+ * The server-filtered `agents` list remains the authority for which agents are+ * working inside the current surface's scope and active filters. We consult+ * `snapshot` (running tasks) only to map each working agent's active tasks+ * onto their owning `squad_id` when present; if a working agent has no matching+ * squad-attributed task in the snapshot (or snapshot hasn't loaded), it stays+ * a standalone agent unit with its exact projected `running_task_count`.+ */+export function collapseWorkingAgentsWithSnapshot(+ agents: readonly WorkingAgentSummary[],+ snapshot: readonly AgentTask[],+ knownSquadIds?: KnownSquadLookup,+): WorkingExecutionUnit[] {+ if (agents.length === 0) return [];++ const runningByAgent = new Map<string, AgentTask[]>();+ for (const task of snapshot) {+ if (task.status !== "running") continue;+ const list = runningByAgent.get(task.agent_id) ?? [];+ list.push(task);+ runningByAgent.set(task.agent_id, list);+ }++ const units = new Map<string, WorkingExecutionUnit>();+ const addUnit = (+ type: "agent" | "squad",+ id: string,+ taskCount: number,+ memberAgentId?: string,+ ) => {+ const key = `${type}:${id}`;+ let entry = units.get(key);+ if (!entry) {+ entry = { type, id, runningTaskCount: 0, memberAgentIds: [] };+ units.set(key, entry);+ }+ entry.runningTaskCount += taskCount;+ if (memberAgentId && !entry.memberAgentIds.includes(memberAgentId)) {+ entry.memberAgentIds.push(memberAgentId);+ }+ };++ for (const agent of agents) {+ const runningTasks = runningByAgent.get(agent.id) ?? [];+ if (runningTasks.length === 0) {+ addUnit("agent", agent.id, agent.running_task_count);+ continue;+ }++ // Count how many of this agent's running tasks belong to each squad vs standalone.+ const squadCounts = new Map<string, number>();+ let standaloneCount = 0;+ for (const task of runningTasks) {+ const squadId = task.squad_id?.trim() || "";+ const useSquad =+ squadId.length > 0 && resolvesToKnownSquad(knownSquadIds, squadId);+ if (useSquad) {+ squadCounts.set(squadId, (squadCounts.get(squadId) ?? 0) + 1);+ } else {+ standaloneCount += 1;+ }+ }++ if (squadCounts.size === 0) {+ addUnit("agent", agent.id, agent.running_task_count);+ continue;+ }++ // Cap attributed counts to the surface-projected `running_task_count` so a+ // narrowed view (e.g. a single project) never inflates counts with tasks+ // running outside that view.+ let remaining = agent.running_task_count;+ for (const [squadId, count] of squadCounts) {+ if (remaining <= 0) break;+ const take = Math.min(count, remaining);+ addUnit("squad", squadId, take, agent.id);+ remaining -= take;+ }+ if (remaining > 0 && standaloneCount > 0) {+ addUnit("agent", agent.id, remaining);+ } else if (remaining > 0) {+ // Any leftover projected count stays attributed to the first squad rather+ // than dropping tasks from the surface total.+ const firstSquad = squadCounts.keys().next().value;+ if (firstSquad) addUnit("squad", firstSquad, remaining, agent.id);+ }+ }++ return Array.from(units.values());+}diff --git a/packages/views/issues/surface/use-issue-agent-state.ts b/packages/views/issues/surface/use-issue-agent-state.tsindex 29a9b29a18..d87c032260 100644--- a/packages/views/issues/surface/use-issue-agent-state.ts+++ b/packages/views/issues/surface/use-issue-agent-state.ts@@ -1,22 +1,39 @@"use client";-import { useCallback } from "react";+import { useCallback, useMemo } from "react";import { useQuery } from "@tanstack/react-query";import { agentTaskSnapshotOptions } from "@multica/core/agents";+import { squadListOptions } from "@multica/core/workspace/queries";import type { AgentTask } from "@multica/core/types";import { selectIssueTasks } from "./activity";+import {+ groupExecutionTasksByActor,+ type ExecutionActorRef,+} from "./execution-actors";-export type IssueAgentState = { running: boolean; agentIds: string[] } | null;+export type IssueAgentState = {+ running: boolean;+ agentIds: string[];+ actors: ExecutionActorRef[];+} | null;-/** The agents running on an issue, or queued for it when none is running yet. */+/** The execution units (squads / standalone agents) running on an issue, or queued when none is running yet. */export function useIssueAgentState(wsId: string, issueId: string): IssueAgentState {+ const { data: squads } = useQuery({+ ...squadListOptions(wsId),+ enabled: Boolean(wsId && issueId),+ });+ const knownSquadIds = useMemo(+ () => (squads ? new Set(squads.map((s) => s.id)) : null),+ [squads],+ );const select = useCallback(- (snapshot: AgentTask[]): IssueAgentState => {+ (snapshot: AgentTask[]) => {if (!issueId) return null;const { running, queued } = selectIssueTasks(snapshot, issueId);const tasks = running.length > 0 ? running : queued;if (tasks.length === 0) return null;- return { running: running.length > 0, agentIds: [...new Set(tasks.map((task) => task.agent_id))] };+ return { running: running.length > 0, tasks };},[issueId],);@@ -25,5 +42,13 @@ export function useIssueAgentState(wsId: string, issueId: string): IssueAgentStaenabled: Boolean(issueId),select,});- return data;+ return useMemo(() => {+ if (!data) return null;+ const grouped = groupExecutionTasksByActor(data.tasks, knownSquadIds);+ return {+ running: data.running,+ agentIds: [...new Set(data.tasks.map((task) => task.agent_id))],+ actors: grouped.map(({ type, id }) => ({ type, id })),+ };+ }, [data, knownSquadIds]);}diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsxindex a46526860d..e219d70de6 100644--- a/packages/views/layout/panels/sidebar-tree.tsx+++ b/packages/views/layout/panels/sidebar-tree.tsx@@ -455,7 +455,13 @@ export function IssueAgentBadge({ agents }: { agents: NonNullable<IssueAgentStatconst { t } = useT("issues");return (<>- <AgentAvatarStack agentIds={agents.agentIds} size="xs" max={2} opacity={agents.running ? "full" : "half"} />+ <AgentAvatarStack+ agentIds={agents.agentIds}+ actors={agents.actors}+ size="xs"+ max={2}+ opacity={agents.running ? "full" : "half"}+ /><span className="sr-only">{agents.running? t(($) => $.agent_activity.status_running)diff --git a/packages/views/layout/panels/team-panel.test.tsx b/packages/views/layout/panels/team-panel.test.tsxindex 6a202529cd..ca225fded1 100644--- a/packages/views/layout/panels/team-panel.test.tsx+++ b/packages/views/layout/panels/team-panel.test.tsx@@ -214,6 +214,43 @@ describe("TeamPanel agent previews", () => {expect(screen.queryByRole("button", { name: /Show/ })).not.toBeInTheDocument();expect(within(screen.getByRole("region", { name: "Working now" })).getAllByRole("link")).toHaveLength(5);});++ it("folds multiple running tasks belonging to the same squad into a single squad row alongside standalone agents", () => {+ seedAgents(3);+ qc.setQueryData(squadListOptions(WS).queryKey, [+ {+ id: "squad-jsquad",+ workspace_id: WS,+ name: "JSquad",+ description: "",+ instructions: "",+ avatar_url: null,+ leader_id: "running-0",+ creator_id: "user-1",+ member_count: 2,+ created_at: new Date(NOW).toISOString(),+ updated_at: new Date(NOW).toISOString(),+ archived_at: null,+ archived_by: null,+ },+ ]);+ qc.setQueryData<AgentTask[]>(agentTaskSnapshotOptions(WS).queryKey, (current = []) =>+ current.map((task) =>+ task.agent_id === "running-0" || task.agent_id === "running-1"+ ? { ...task, squad_id: "squad-jsquad" }+ : task,+ ),+ );+ renderPanel([runtime()]);++ const working = within(screen.getByRole("region", { name: "Working now" }));+ // 2 squad tasks collapse into 1 JSquad row + 1 standalone agent row = 2 rows.+ expect(working.getByText("2")).toBeInTheDocument();+ expect(working.getAllByRole("link")).toHaveLength(2);+ expect(working.getByText("JSquad")).toBeInTheDocument();+ expect(working.getByText("running agent 3")).toBeInTheDocument();+ expect(working.getByText(/running agent 1.*running agent 2/)).toBeInTheDocument();+ });});describe("TeamPanel agent menu", () => {diff --git a/packages/views/layout/panels/team-panel.tsx b/packages/views/layout/panels/team-panel.tsxindex be7455fa60..07fc45ba49 100644--- a/packages/views/layout/panels/team-panel.tsx+++ b/packages/views/layout/panels/team-panel.tsx@@ -19,14 +19,14 @@ import { useCurrentWorkspace, useWorkspacePaths, issueRouteRef } from "@multica/import { runtimeListOptions } from "@multica/core/runtimes/queries";import { memberListOptions, skillListOptions, squadListOptions } from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import type { Agent, AgentTask } from "@multica/core/types";+import type { Agent, AgentTask, Squad } from "@multica/core/types";import { useNavigation } from "../../navigation";import { isFloatingChatRouteSuppressed } from "../../chat/floating-chat-visibility";import { AgentRowActions } from "../../agents/components/agent-row-actions";import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";import { CollectionRowContext } from "../collection-list/row-context";import { availabilityConfig } from "../../agents/presence";-import { useT } from "../../i18n";+import { useLocale, useT } from "../../i18n";import { buildAppDirectory } from "../../apps/lib/directory";import { useComposioAvailable } from "../../common/use-composio-available";import { useViewerAppsOverview } from "../../common/use-viewer-apps-overview";@@ -246,6 +246,65 @@ function WorkingAgentRow({);}+function WorkingSquadRow({+ squad,+ tasks,+ agentNameById,+ wsId,+ active,+}: {+ squad: Squad;+ tasks: AgentTask[];+ agentNameById: ReadonlyMap<string, string>;+ wsId: string;+ active: boolean;+}) {+ const { t } = useT("layout");+ const locale = useLocale();+ const p = useWorkspacePaths();+ const primaryTask = tasks[0];+ const issue = useRunningIssue(wsId, tasks.length === 1 ? primaryTask : undefined);+ const memberNames = [+ ...new Set(+ tasks+ .map((task) => agentNameById.get(task.agent_id))+ .filter((name): name is string => Boolean(name)),+ ),+ ];+ const memberSeparator =+ locale.startsWith("zh") || locale.startsWith("ja") ? "、" : ", ";+ const singleMember = memberNames[0] ?? null;+ const description =+ tasks.length === 1 && issue && singleMember+ ? `${issue.identifier} · ${singleMember}`+ : tasks.length === 1 && issue+ ? `${issue.identifier} ${issue.title}`+ : memberNames.length > 0+ ? `${t(($) => $.panels.team.running_tasks, { count: tasks.length })} · ${memberNames.join(memberSeparator)}`+ : t(($) => $.panels.team.running_tasks, { count: tasks.length });++ return (+ <PanelLink+ href={p.squadDetail(squad.id)}+ label={squad.name}+ active={active}+ icon={+ <span className="relative shrink-0">+ <ActorAvatar+ name={squad.name}+ initials={squad.name.slice(0, 2).toUpperCase()}+ avatarUrl={resolvePublicFileUrl(squad.avatar_url)}+ isSquad+ size="md"+ />+ <span className="absolute -right-0.5 -bottom-0.5 size-2 rounded-full bg-brand ring-2 ring-page-canvas" />+ </span>+ }+ description={description}+ />+ );+}+/** The Apps link, counting the apps that need someone to act. */function AppsPanelLink({ wsId }: { wsId: string }) {const { t } = useT("layout");@@ -297,6 +356,55 @@ export function TeamPanel() {const { data: squads = [] } = useQuery({ ...squadListOptions(wsId), enabled: !!wsId });const liveSquads = useMemo(() => squads.filter((squad) => !squad.archived_at), [squads]);+ const liveSquadById = useMemo(+ () => new Map(liveSquads.map((squad) => [squad.id, squad] as const)),+ [liveSquads],+ );+ const agentNameById = useMemo(+ () => new Map(agents.map((agent) => [agent.id, agent.name] as const)),+ [agents],+ );++ // Collapse running tasks belonging to a live Squad into a single Squad entry+ // in "Working now". Agents whose running work is entirely inside squads are+ // folded into those squad rows; agents with standalone running tasks remain+ // listed individually alongside the squads.+ const { workingSquadEntries, standaloneWorkingAgents, standaloneRunningTaskByAgent } = useMemo(() => {+ const tasksBySquad = new Map<string, AgentTask[]>();+ const standaloneTaskByAgent = new Map<string, AgentTask>();+ const squadOnlyAgentIds = new Set<string>();+ const standaloneAgentIds = new Set<string>();++ for (const task of snapshot) {+ if (task.status !== "running") continue;+ const squadId = task.squad_id?.trim() || "";+ if (squadId && liveSquadById.has(squadId)) {+ const list = tasksBySquad.get(squadId) ?? [];+ list.push(task);+ tasksBySquad.set(squadId, list);+ squadOnlyAgentIds.add(task.agent_id);+ } else {+ standaloneAgentIds.add(task.agent_id);+ if (!standaloneTaskByAgent.has(task.agent_id)) {+ standaloneTaskByAgent.set(task.agent_id, task);+ }+ }+ }++ const squadEntries = Array.from(tasksBySquad.entries())+ .map(([squadId, tasks]) => ({ squad: liveSquadById.get(squadId)!, tasks }))+ .filter((entry) => Boolean(entry.squad));++ const standaloneAgents = working.filter(+ (agent) => !squadOnlyAgentIds.has(agent.id) || standaloneAgentIds.has(agent.id),+ );++ return {+ workingSquadEntries: squadEntries,+ standaloneWorkingAgents: standaloneAgents,+ standaloneRunningTaskByAgent: standaloneTaskByAgent,+ };+ }, [snapshot, liveSquadById, working]);const { data: members = [] } = useQuery({ ...memberListOptions(wsId), enabled: !!wsId });const { data: skills = [] } = useQuery({ ...skillListOptions(wsId), enabled: !!wsId });const { data: runtimes = [] } = useQuery({ ...runtimeListOptions(wsId), enabled: !!wsId });@@ -371,26 +479,66 @@ export function TeamPanel() {/>)}- {working.length > 0 && (- <AgentStatusSection- key={`working:${wsId}`}- label={t(($) => $.panels.team.working_now)}- agents={working}- collapsed={workingCollapsed}- onCollapsedChange={setWorkingCollapsed}- renderAgent={(agent) => (- <WorkingAgentRow- key={agent.id}- agent={agent}- detail={byAgent.get(agent.id)}- task={runningTaskByAgent.get(agent.id)}- wsId={wsId}- active={isPathWithin(pathname, p.agentDetail(agent.id))}- canManage={canManageAgent(agent)}- canChat={canChatWith(agent)}- />- )}- />+ {(workingSquadEntries.length > 0 || standaloneWorkingAgents.length > 0) && (+ workingSquadEntries.length === 0 ? (+ <AgentStatusSection+ key={`working:${wsId}`}+ label={t(($) => $.panels.team.working_now)}+ agents={standaloneWorkingAgents}+ collapsed={workingCollapsed}+ onCollapsedChange={setWorkingCollapsed}+ renderAgent={(agent) => (+ <WorkingAgentRow+ key={agent.id}+ agent={agent}+ detail={byAgent.get(agent.id)}+ task={standaloneRunningTaskByAgent.get(agent.id) ?? runningTaskByAgent.get(agent.id)}+ wsId={wsId}+ active={isPathWithin(pathname, p.agentDetail(agent.id))}+ canManage={canManageAgent(agent)}+ canChat={canChatWith(agent)}+ />+ )}+ />+ ) : (+ <PanelSection+ key={`working:${wsId}`}+ label={t(($) => $.panels.team.working_now)}+ collapsed={workingCollapsed}+ onCollapsedChange={setWorkingCollapsed}+ action={+ <PanelCount+ value={workingSquadEntries.length + standaloneWorkingAgents.length}+ className="pr-2"+ />+ }+ >+ <PanelList>+ {workingSquadEntries.map(({ squad, tasks }) => (+ <WorkingSquadRow+ key={`squad:${squad.id}`}+ squad={squad}+ tasks={tasks}+ agentNameById={agentNameById}+ wsId={wsId}+ active={isPathWithin(pathname, p.squadDetail(squad.id))}+ />+ ))}+ {standaloneWorkingAgents.map((agent) => (+ <WorkingAgentRow+ key={agent.id}+ agent={agent}+ detail={byAgent.get(agent.id)}+ task={standaloneRunningTaskByAgent.get(agent.id) ?? runningTaskByAgent.get(agent.id)}+ wsId={wsId}+ active={isPathWithin(pathname, p.agentDetail(agent.id))}+ canManage={canManageAgent(agent)}+ canChat={canChatWith(agent)}+ />+ ))}+ </PanelList>+ </PanelSection>+ ))}<PanelSection label={t(($) => $.nav.agents)}>diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.jsonindex ec6c8c742a..3265cadbfe 100644--- a/packages/views/locales/en/usage.json+++ b/packages/views/locales/en/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "Project","all_projects": "All projects",- "period_label": "Period"+ "period_label": "Period",+ "attribution_label": "Attribution",+ "all_attribution": "All attribution",+ "standalone_only": "Standalone agents only",+ "squads_group": "Squads"},"history_limit": {"note": "Your plan covers the last {{days}} days. Upgrade to see earlier data. Nothing is deleted.",@@ -27,7 +31,9 @@"run_time_label": "Run time · {{days}}D","run_time_hint": "Across {{tasks}} runs","tasks_label": "Runs · {{days}}D",- "tasks_hint": "{{failed}} failed"+ "tasks_hint": "{{failed}} failed",+ "cost_squad_hint": "{{name}} overall (incl. delegated members)",+ "cost_squad_share_hint": "Squad-triggered {{cost}} ({{pct}}%)"},"dim": {"label": "Interval",@@ -90,7 +96,8 @@"show_reasons": "Show error codes","hide_reasons": "Hide error codes","show_all": "Show all {{count}}",- "show_less": "Show top {{count}}"+ "show_less": "Show top {{count}}",+ "by_squad": "Errors by squad"},"leaderboard": {"title": "Leaderboard",@@ -111,7 +118,19 @@"usage_totals_pending": "Usage totals are still being processed","show_all": "Show all","show_less": "Show top {{count}}",- "no_data": "No agent activity in this window."+ "no_data": "No agent activity in this window.",+ "group_label": "Group leaderboard by",+ "group_agent": "Agents",+ "group_squad": "Squads",+ "header_squad": "Squad / Attribution",+ "squad_caption": "{{count}} squads",+ "squad_caption_with_standalone": "{{count}} squads · incl. standalone",+ "squad_members_title": "{{name}} member breakdown",+ "squad_members_count": "{{count}} members involved",+ "standalone_agents": "Standalone agents (non-Squad)",+ "standalone_agents_hint": "Direct @mention or assignment · {{count}} agents",+ "deleted_squads": "Deleted squads",+ "toggle_squad_members": "Toggle members for {{name}}"},"empty": {"title": "No usage yet",diff --git a/packages/views/locales/es/usage.json b/packages/views/locales/es/usage.jsonindex 76d1d9fe81..b5bdc7130e 100644--- a/packages/views/locales/es/usage.json+++ b/packages/views/locales/es/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "Proyecto","all_projects": "Todos los proyectos",- "period_label": "Periodo"+ "period_label": "Periodo",+ "attribution_label": "Atribución",+ "all_attribution": "Toda atribución",+ "standalone_only": "Solo agentes independientes",+ "squads_group": "Squads"},"history_limit": {"note": "Tu plan incluye los últimos {{days}} días. Mejora tu plan para ver datos anteriores. No se elimina nada.",@@ -27,7 +31,9 @@"run_time_label": "Tiempo de ejecución · {{days}}D","run_time_hint": "En {{tasks}} ejecuciones","tasks_label": "Ejecuciones · {{days}}D",- "tasks_hint": "{{failed}} fallaron"+ "tasks_hint": "{{failed}} fallaron",+ "cost_squad_hint": "{{name}} total (incl. miembros delegados)",+ "cost_squad_share_hint": "Activado por Squad {{cost}} ({{pct}}%)"},"dim": {"label": "Intervalo",@@ -90,7 +96,8 @@"show_reasons": "Mostrar códigos de error","hide_reasons": "Ocultar códigos de error","show_all": "Mostrar todos ({{count}})",- "show_less": "Mostrar los {{count}} principales"+ "show_less": "Mostrar los {{count}} principales",+ "by_squad": "Errores por squad"},"leaderboard": {"title": "Clasificación",@@ -111,7 +118,19 @@"usage_totals_pending": "Los totales de uso se están procesando","show_all": "Mostrar todos","show_less": "Mostrar los {{count}} principales",- "no_data": "Sin actividad de agentes en este periodo."+ "no_data": "Sin actividad de agentes en este periodo.",+ "group_label": "Agrupar clasificación por",+ "group_agent": "Agentes",+ "group_squad": "Squads",+ "header_squad": "Squad / Atribución",+ "squad_caption": "{{count}} squads",+ "squad_caption_with_standalone": "{{count}} squads · incl. independientes",+ "squad_members_title": "Desglose de miembros de {{name}}",+ "squad_members_count": "{{count}} miembros participantes",+ "standalone_agents": "Agentes independientes (sin Squad)",+ "standalone_agents_hint": "Mención o asignación directa · {{count}} agentes",+ "deleted_squads": "Squads eliminados",+ "toggle_squad_members": "Alternar miembros de {{name}}"},"empty": {"title": "Aún no hay uso",diff --git a/packages/views/locales/fr/usage.json b/packages/views/locales/fr/usage.jsonindex 92e60772c0..33149385fd 100644--- a/packages/views/locales/fr/usage.json+++ b/packages/views/locales/fr/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "Projet","all_projects": "Tous les projets",- "period_label": "Période"+ "period_label": "Période",+ "attribution_label": "Attribution",+ "all_attribution": "Toute attribution",+ "standalone_only": "Agents autonomes uniquement",+ "squads_group": "Squads"},"history_limit": {"note": "Votre forfait couvre les {{days}} derniers jours. Passez à un forfait supérieur pour voir les données plus anciennes. Rien n'est supprimé.",@@ -27,7 +31,9 @@"run_time_label": "Temps d'exécution · {{days}} j","run_time_hint": "Sur {{tasks}} exécutions","tasks_label": "Exécutions · {{days}} j",- "tasks_hint": "{{failed}} en échec"+ "tasks_hint": "{{failed}} en échec",+ "cost_squad_hint": "{{name}} au global (membres délégués inclus)",+ "cost_squad_share_hint": "Déclenché par Squad {{cost}} ({{pct}}%)"},"dim": {"label": "Intervalle",@@ -90,7 +96,8 @@"show_reasons": "Afficher les codes d'erreur","hide_reasons": "Masquer les codes d'erreur","show_all": "Afficher les {{count}}",- "show_less": "Afficher le top {{count}}"+ "show_less": "Afficher le top {{count}}",+ "by_squad": "Erreurs par squad"},"leaderboard": {"title": "Classement",@@ -111,7 +118,19 @@"usage_totals_pending": "Les totaux de consommation sont encore en cours de traitement","show_all": "Tout afficher","show_less": "Afficher le top {{count}}",- "no_data": "Aucune activité d'agent sur cette fenêtre."+ "no_data": "Aucune activité d'agent sur cette fenêtre.",+ "group_label": "Grouper le classement par",+ "group_agent": "Agents",+ "group_squad": "Squads",+ "header_squad": "Squad / Attribution",+ "squad_caption": "{{count}} squads",+ "squad_caption_with_standalone": "{{count}} squads · autonomes inclus",+ "squad_members_title": "Répartition des membres de {{name}}",+ "squad_members_count": "{{count}} membres impliqués",+ "standalone_agents": "Agents autonomes (hors Squad)",+ "standalone_agents_hint": "Mention ou assignation directe · {{count}} agents",+ "deleted_squads": "Squads supprimés",+ "toggle_squad_members": "Afficher ou masquer les membres de {{name}}"},"empty": {"title": "Aucune consommation pour l'instant",diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.jsonindex 3ba0556c88..9534f33304 100644--- a/packages/views/locales/ja/usage.json+++ b/packages/views/locales/ja/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "プロジェクト","all_projects": "すべてのプロジェクト",- "period_label": "期間"+ "period_label": "期間",+ "attribution_label": "帰属",+ "all_attribution": "すべての帰属",+ "standalone_only": "単独エージェントのみ",+ "squads_group": "Squad"},"history_limit": {"note": "現在のプランでは直近 {{days}} 日を表示できます。アップグレードするとそれ以前のデータも表示できます。データは削除されません。",@@ -27,7 +31,9 @@"run_time_label": "実行時間 · {{days}}日","run_time_hint": "{{tasks}} 件の実行全体","tasks_label": "実行 · {{days}}日",- "tasks_hint": "{{failed}} 件失敗"+ "tasks_hint": "{{failed}} 件失敗",+ "cost_squad_hint": "{{name}} 全体(委任メンバー含む)",+ "cost_squad_share_hint": "Squad 経由 {{cost}}({{pct}}%)"},"dim": {"label": "間隔",@@ -90,7 +96,8 @@"show_reasons": "エラーコードを表示","hide_reasons": "エラーコードを隠す","show_all": "全 {{count}} 件を表示",- "show_less": "上位 {{count}} 件のみ"+ "show_less": "上位 {{count}} 件のみ",+ "by_squad": "Squad 別エラー"},"leaderboard": {"title": "リーダーボード",@@ -109,7 +116,19 @@"usage_totals_pending": "使用量を集計しています","show_all": "すべて表示","show_less": "上位 {{count}} 件のみ",- "no_data": "この期間にエージェントの活動はありません。"+ "no_data": "この期間にエージェントの活動はありません。",+ "group_label": "ランキングのグループ化",+ "group_agent": "エージェント",+ "group_squad": "Squad",+ "header_squad": "Squad / 帰属",+ "squad_caption": "{{count}} Squad",+ "squad_caption_with_standalone": "{{count}} Squad・単独含む",+ "squad_members_title": "{{name}} のメンバー内訳",+ "squad_members_count": "{{count}} メンバー参加",+ "standalone_agents": "単独エージェント(Squad 外)",+ "standalone_agents_hint": "直接メンションまたは割当・{{count}} エージェント",+ "deleted_squads": "削除済み Squad",+ "toggle_squad_members": "{{name}} のメンバー内訳を切り替え"},"empty": {"title": "まだ使用量はありません",diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.jsonindex 9d30e8d0e0..e50cf35750 100644--- a/packages/views/locales/ko/usage.json+++ b/packages/views/locales/ko/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "프로젝트","all_projects": "모든 프로젝트",- "period_label": "기간"+ "period_label": "기간",+ "attribution_label": "귀속",+ "all_attribution": "전체 귀속",+ "standalone_only": "단독 에이전트만",+ "squads_group": "Squad"},"history_limit": {"note": "현재 요금제에서는 최근 {{days}}일을 볼 수 있습니다. 업그레이드하면 이전 데이터도 볼 수 있으며, 데이터는 삭제되지 않습니다.",@@ -27,7 +31,9 @@"run_time_label": "실행 시간 · {{days}}일","run_time_hint": "실행 {{tasks}}개 기준","tasks_label": "실행 · {{days}}일",- "tasks_hint": "실패 {{failed}}개"+ "tasks_hint": "실패 {{failed}}개",+ "cost_squad_hint": "{{name}} 전체(위임 멤버 포함)",+ "cost_squad_share_hint": "Squad 트리거 {{cost}}({{pct}}%)"},"dim": {"label": "간격",@@ -90,7 +96,8 @@"show_reasons": "오류 코드 표시","hide_reasons": "오류 코드 숨기기","show_all": "전체 {{count}}개 보기",- "show_less": "상위 {{count}}개만"+ "show_less": "상위 {{count}}개만",+ "by_squad": "Squad별 오류"},"leaderboard": {"title": "리더보드",@@ -109,7 +116,19 @@"usage_totals_pending": "사용량을 집계하는 중","show_all": "전체 보기","show_less": "상위 {{count}}개만",- "no_data": "이 기간에는 에이전트 활동이 없습니다."+ "no_data": "이 기간에는 에이전트 활동이 없습니다.",+ "group_label": "리더보드 그룹 기준",+ "group_agent": "에이전트",+ "group_squad": "Squad",+ "header_squad": "Squad / 귀속",+ "squad_caption": "{{count}}개 Squad",+ "squad_caption_with_standalone": "{{count}}개 Squad · 단독 포함",+ "squad_members_title": "{{name}} 멤버별 사용량",+ "squad_members_count": "{{count}}명 멤버 참여",+ "standalone_agents": "단독 에이전트(Squad 외)",+ "standalone_agents_hint": "직접 멘션 또는 할당 · {{count}}개 에이전트",+ "deleted_squads": "삭제된 Squad",+ "toggle_squad_members": "{{name}} 멤버 세부 정보 전환"},"empty": {"title": "아직 사용량이 없습니다",diff --git a/packages/views/locales/ru/usage.json b/packages/views/locales/ru/usage.jsonindex b9c72892b2..5514dc6949 100644--- a/packages/views/locales/ru/usage.json+++ b/packages/views/locales/ru/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "Проект","all_projects": "Все проекты",- "period_label": "Период"+ "period_label": "Период",+ "attribution_label": "Принадлежность",+ "all_attribution": "Все источники",+ "standalone_only": "Только отдельные агенты",+ "squads_group": "Squad"},"history_limit": {"note": "Ваш тариф охватывает последние {{days}} дн. Перейдите на другой тариф, чтобы увидеть более ранние данные. Данные не удаляются.",@@ -27,7 +31,9 @@"run_time_label": "Время выполнения · {{days}} дн.","run_time_hint": "Всего запусков: {{tasks}}","tasks_label": "Запуски · {{days}} дн.",- "tasks_hint": "{{failed}} с ошибкой"+ "tasks_hint": "{{failed}} с ошибкой",+ "cost_squad_hint": "{{name}} целиком (включая делегированных участников)",+ "cost_squad_share_hint": "Через Squad {{cost}} ({{pct}}%)"},"dim": {"label": "Интервал",@@ -90,7 +96,8 @@"show_reasons": "Показать коды ошибок","hide_reasons": "Скрыть коды ошибок","show_all": "Показать все {{count}}",- "show_less": "Показать топ {{count}}"+ "show_less": "Показать топ {{count}}",+ "by_squad": "Ошибки по Squad"},"leaderboard": {"title": "Рейтинг",@@ -115,7 +122,19 @@"usage_unreported_few": "{{count}} запуска не сообщили об использовании","usage_unreported_many": "{{count}} запусков не сообщили об использовании","usage_unreported_pending_few": "{{count}} запуска не сообщили об использовании · итоги ещё обрабатываются",- "usage_unreported_pending_many": "{{count}} запусков не сообщили об использовании · итоги ещё обрабатываются"+ "usage_unreported_pending_many": "{{count}} запусков не сообщили об использовании · итоги ещё обрабатываются",+ "group_label": "Группировка рейтинга",+ "group_agent": "Агенты",+ "group_squad": "Squad",+ "header_squad": "Squad / Источник",+ "squad_caption": "{{count}} Squad",+ "squad_caption_with_standalone": "{{count}} Squad · включая отдельных",+ "squad_members_title": "Состав расходов {{name}}",+ "squad_members_count": "Участвуют {{count}} участников",+ "standalone_agents": "Отдельные агенты (вне Squad)",+ "standalone_agents_hint": "Прямое упоминание или назначение · {{count}} агентов",+ "deleted_squads": "Удалённые Squad",+ "toggle_squad_members": "Показать или скрыть участников {{name}}"},"empty": {"title": "Данных пока нет",diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.jsonindex c55040e5f7..1ed42c1bbb 100644--- a/packages/views/locales/zh-Hans/usage.json+++ b/packages/views/locales/zh-Hans/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "项目","all_projects": "全部项目",- "period_label": "时间范围"+ "period_label": "时间范围",+ "attribution_label": "归属",+ "all_attribution": "全部归属",+ "standalone_only": "仅独立智能体",+ "squads_group": "Squad"},"history_limit": {"note": "当前套餐可以查看最近 {{days}} 天。升级后可以查看更早的数据,数据一直保留。",@@ -27,7 +31,9 @@"run_time_label": "耗时 · {{days}}天","run_time_hint": "共 {{tasks}} 次运行","tasks_label": "运行数 · {{days}}天",- "tasks_hint": "失败 {{failed}} 次"+ "tasks_hint": "失败 {{failed}} 次",+ "cost_squad_hint": "{{name}} 整体(含委派成员)",+ "cost_squad_share_hint": "其中 Squad 触发 {{cost}}({{pct}}%)"},"dim": {"label": "时间粒度",@@ -90,7 +96,8 @@"show_reasons": "展开错误码","hide_reasons": "收起错误码","show_all": "展开全部 {{count}} 个",- "show_less": "只看前 {{count}} 个"+ "show_less": "只看前 {{count}} 个",+ "by_squad": "问题最多的 Squad"},"leaderboard": {"title": "排行榜",@@ -109,7 +116,19 @@"usage_totals_pending": "用量汇总仍在处理中","show_all": "展开全部","show_less": "只看前 {{count}} 个",- "no_data": "所选时间范围内暂无智能体活动。"+ "no_data": "所选时间范围内暂无智能体活动。",+ "group_label": "排行榜分组方式",+ "group_agent": "智能体",+ "group_squad": "Squad",+ "header_squad": "Squad / 归属",+ "squad_caption": "{{count}} 个 Squad",+ "squad_caption_with_standalone": "{{count}} 个 Squad · 含非 Squad 归总",+ "squad_members_title": "{{name}} 成员消耗构成",+ "squad_members_count": "{{count}} 个成员参与",+ "standalone_agents": "独立智能体(非 Squad 触发)",+ "standalone_agents_hint": "直接 @ 提及或单智能体指派 · {{count}} 个智能体",+ "deleted_squads": "已删除的 Squad",+ "toggle_squad_members": "展开或收起 {{name}} 成员明细"},"empty": {"title": "暂无用量数据",diff --git a/packages/views/locales/zh-Hant/usage.json b/packages/views/locales/zh-Hant/usage.jsonindex 0b5f547aea..f2c02a5c75 100644--- a/packages/views/locales/zh-Hant/usage.json+++ b/packages/views/locales/zh-Hant/usage.json@@ -8,7 +8,11 @@"filter": {"project_label": "專案","all_projects": "全部專案",- "period_label": "時間範圍"+ "period_label": "時間範圍",+ "attribution_label": "歸屬",+ "all_attribution": "全部歸屬",+ "standalone_only": "僅獨立智能體",+ "squads_group": "Squad"},"history_limit": {"note": "目前方案可以查看最近 {{days}} 天。升級後可以查看更早的資料,資料一直保留。",@@ -27,7 +31,9 @@"run_time_label": "耗時 · {{days}}天","run_time_hint": "共 {{tasks}} 次執行","tasks_label": "執行數 · {{days}}天",- "tasks_hint": "失敗 {{failed}} 個"+ "tasks_hint": "失敗 {{failed}} 個",+ "cost_squad_hint": "{{name}} 整體(含委派成員)",+ "cost_squad_share_hint": "其中 Squad 觸發 {{cost}}({{pct}}%)"},"dim": {"label": "時間區間",@@ -90,7 +96,8 @@"show_reasons": "展開錯誤碼","hide_reasons": "收起錯誤碼","show_all": "展開全部 {{count}} 個",- "show_less": "只看前 {{count}} 個"+ "show_less": "只看前 {{count}} 個",+ "by_squad": "問題最多的 Squad"},"leaderboard": {"title": "排行榜",@@ -109,7 +116,19 @@"usage_totals_pending": "用量彙總仍在處理中","show_all": "展開全部","show_less": "只看前 {{count}} 個",- "no_data": "所選時間範圍內暫無 AI 代理活動。"+ "no_data": "所選時間範圍內暫無 AI 代理活動。",+ "group_label": "排行榜分組方式",+ "group_agent": "智能體",+ "group_squad": "Squad",+ "header_squad": "Squad / 歸屬",+ "squad_caption": "{{count}} 個 Squad",+ "squad_caption_with_standalone": "{{count}} 個 Squad · 含非 Squad 彙總",+ "squad_members_title": "{{name}} 成員消耗構成",+ "squad_members_count": "{{count}} 個成員參與",+ "standalone_agents": "獨立智能體(非 Squad 觸發)",+ "standalone_agents_hint": "直接 @ 提及或單智能體指派 · {{count}} 個智能體",+ "deleted_squads": "已刪除的 Squad",+ "toggle_squad_members": "展開或收合 {{name}} 成員明細"},"empty": {"title": "暫無消耗資料",diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex cf56340bfc..6fea42d41a 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,9 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "736_task_usage_hourly_squad_uq_idx": "uq_task_usage_hourly_squad_key_idx",+ "737_task_usage_hourly_dirty_squad_uq_idx": "uq_task_usage_hourly_dirty_squad_key_idx",+ "738_task_usage_hourly_workspace_squad_idx": "idx_task_usage_hourly_workspace_squad_time","733_comment_idempotency_receipt_key": "uq_comment_idempotency_receipt_key","734_comment_idempotency_receipt_created": "idx_comment_idempotency_receipt_created","729_remote_app_connection_workspace_idx": "uq_remote_app_connection_owner_ws",@@ -435,6 +438,8 @@ var concurrentIndexCleanups = map[string]string{// the retry, while a bare CREATE would stay wedged on "already exists"; both// cases need direction-specific cleanup before the rollback can retry safely.var concurrentDownIndexCleanups = map[string]string{+ "740_task_usage_hourly_drop_legacy_key": "uq_task_usage_hourly_key",+ "741_task_usage_hourly_dirty_drop_legacy_key": "uq_task_usage_hourly_dirty_key","730_drop_remote_app_connection_owner_idx": "uq_remote_app_connection_owner","144_drop_agent_task_queue_chat_pending_v1": "idx_agent_task_queue_chat_pending","171_drop_legacy_label_namespace_index": "issue_label_workspace_name_lower_idx",diff --git a/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go b/server/cmd/migrate/migrate_task_usage_hourly_squad_test.gonew file mode 100644index 0000000000..24bb6d38ba--- /dev/null+++ b/server/cmd/migrate/migrate_task_usage_hourly_squad_test.go@@ -0,0 +1,243 @@+package main++import (+ "context"+ "fmt"+ "math/rand/v2"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+)++// TestTaskUsageHourlySquadMigrationsUpDownUp exercises migrations 735–742 in+// both directions against an isolated schema seeded with the pre-735+// task_usage_hourly schema, proving:+// - UP (735–742) creates the concurrent squad indexes, switches the rollup+// pipeline, and drops the legacy 7-column unique constraints.+// - DOWN (742–735) merges split squad buckets back into squad_id = NULL,+// rebuilds uq_task_usage_hourly_key and uq_task_usage_hourly_dirty_key+// CONCURRENTLY (registered in concurrentDownIndexCleanups), attaches them+// via ADD CONSTRAINT ... UNIQUE USING INDEX as UNIQUE NULLS NOT DISTINCT,+// and drops the squad indexes and columns cleanly.+// - Re-applying UP (735–742) succeeds cleanly on the rolled-back schema.+func TestTaskUsageHourlySquadMigrationsUpDownUp(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()++ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())+ schema := "migrate_task_usage_squad_" + suffix+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := adminPool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cleanupCancel()+ if _, err := adminPool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {+ t.Logf("drop schema %s: %v", schema, err)+ }+ })++ pool := openTestPoolWithSearchPath(t, schema)+ for _, stmt := range []string{+ `CREATE TABLE schema_migrations (+ version TEXT PRIMARY KEY,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )`,+ `CREATE FUNCTION task_usage_hour_bucket(ts TIMESTAMPTZ) RETURNS TIMESTAMPTZ LANGUAGE SQL IMMUTABLE AS $$+ SELECT date_trunc('hour', ts AT TIME ZONE 'UTC') AT TIME ZONE 'UTC'+ $$`,+ `CREATE TABLE agent (+ id UUID PRIMARY KEY,+ workspace_id UUID NOT NULL+ )`,+ `CREATE TABLE issue (+ id UUID PRIMARY KEY,+ workspace_id UUID NOT NULL,+ project_id UUID+ )`,+ `CREATE TABLE agent_task_queue (+ id UUID PRIMARY KEY,+ agent_id UUID NOT NULL,+ runtime_id UUID,+ issue_id UUID,+ squad_id UUID+ )`,+ `CREATE TABLE task_usage (+ id UUID PRIMARY KEY,+ task_id UUID NOT NULL,+ provider TEXT NOT NULL,+ model TEXT NOT NULL,+ input_tokens BIGINT NOT NULL DEFAULT 0,+ output_tokens BIGINT NOT NULL DEFAULT 0,+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,+ cost_usd_ticks BIGINT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ+ )`,+ `CREATE TABLE task_usage_hourly (+ bucket_hour TIMESTAMPTZ NOT NULL,+ workspace_id UUID NOT NULL,+ runtime_id UUID NOT NULL,+ agent_id UUID NOT NULL,+ project_id UUID,+ provider TEXT NOT NULL,+ model TEXT NOT NULL,+ input_tokens BIGINT NOT NULL DEFAULT 0,+ output_tokens BIGINT NOT NULL DEFAULT 0,+ cache_read_tokens BIGINT NOT NULL DEFAULT 0,+ cache_write_tokens BIGINT NOT NULL DEFAULT 0,+ cost_usd_ticks BIGINT NOT NULL DEFAULT 0,+ uncosted_input_tokens BIGINT,+ uncosted_output_tokens BIGINT,+ uncosted_cache_read_tokens BIGINT,+ uncosted_cache_write_tokens BIGINT,+ task_count BIGINT NOT NULL DEFAULT 0,+ event_count BIGINT NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT uq_task_usage_hourly_key+ UNIQUE NULLS NOT DISTINCT+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)+ )`,+ `CREATE TABLE task_usage_hourly_dirty (+ bucket_hour TIMESTAMPTZ NOT NULL,+ workspace_id UUID NOT NULL,+ runtime_id UUID NOT NULL,+ agent_id UUID NOT NULL,+ project_id UUID,+ provider TEXT NOT NULL,+ model TEXT NOT NULL,+ enqueued_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT uq_task_usage_hourly_dirty_key+ UNIQUE NULLS NOT DISTINCT+ (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)+ )`,+ } {+ if _, err := pool.Exec(ctx, stmt); err != nil {+ t.Fatalf("seed pre-735 schema: %v", err)+ }+ }++ versions := []string{+ "735_task_usage_hourly_squad_col",+ "736_task_usage_hourly_squad_uq_idx",+ "737_task_usage_hourly_dirty_squad_uq_idx",+ "738_task_usage_hourly_workspace_squad_idx",+ "739_task_usage_hourly_squad_pipeline",+ "740_task_usage_hourly_drop_legacy_key",+ "741_task_usage_hourly_dirty_drop_legacy_key",+ "742_task_usage_hourly_squad_rollback_merge",+ }+ reversed := make([]string, len(versions))+ for i := range versions {+ reversed[i] = versions[len(versions)-1-i]+ }++ runDir := func(dir string, list []string) {+ t.Helper()+ if err := runMigrations(ctx, pool, runOptions{+ Direction: dir,+ Files: realMigrationFiles(t, list, dir),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection(dir),+ }); err != nil {+ t.Fatalf("run %s migrations: %v", dir, err)+ }+ }++ // 1a. UP through 739: legacy 7-column constraints must ALREADY be dropped+ // atomically in 739 up (before 740/741 run) so there is zero intermediate+ // window where 8-column ON CONFLICT statements collide with legacy constraints.+ runDir("up", versions[:5])+ assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_squad_key_idx", true)+ assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_dirty_squad_key_idx", true)+ assertIndexValidity(t, pool, schema, "idx_task_usage_hourly_workspace_squad_time", true)+ assertIndexExists(t, pool, schema, "uq_task_usage_hourly_key", false)+ assertIndexExists(t, pool, schema, "uq_task_usage_hourly_dirty_key", false)++ // 1b. UP remaining 740..742 (forward no-ops paired with concurrent down rebuilds).+ runDir("up", versions[5:])++ // Insert two split squad rows + one standalone row sharing the same legacy+ // 7-column key, plus a pending squad dirty row, to verify 742 down merges+ // them cleanly before 741/740 down rebuild legacy unique indexes CONCURRENTLY.+ const (+ wsID = "00000000-0000-0000-0000-000000000001"+ rtID = "00000000-0000-0000-0000-000000000002"+ agID = "00000000-0000-0000-0000-000000000003"+ sq1ID = "00000000-0000-0000-0000-000000000011"+ sq2ID = "00000000-0000-0000-0000-000000000012"+ )+ if _, err := pool.Exec(ctx, `+ INSERT INTO task_usage_hourly (+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id,+ provider, model, input_tokens, task_count, event_count+ ) VALUES+ ('2026-11-23 10:00:00+00', $1, $2, $3, NULL, $4, 'claude', 'claude-sonnet-4-6', 1000, 1, 1),+ ('2026-11-23 10:00:00+00', $1, $2, $3, NULL, $5, 'claude', 'claude-sonnet-4-6', 2000, 2, 2),+ ('2026-11-23 10:00:00+00', $1, $2, $3, NULL, NULL, 'claude', 'claude-sonnet-4-6', 500, 1, 1)+ `, wsID, rtID, agID, sq1ID, sq2ID); err != nil {+ t.Fatalf("seed split hourly rows: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model+ ) VALUES+ ('2026-11-23 10:00:00+00', $1, $2, $3, NULL, $4, 'claude', 'claude-sonnet-4-6')+ `, wsID, rtID, agID, sq1ID); err != nil {+ t.Fatalf("seed squad dirty row: %v", err)+ }++ // 2. DOWN: 742..735+ runDir("down", reversed)++ // Split rows must have merged into one row totaling 3500 tokens & 4 tasks.+ var rowCount int+ var sumTokens, sumTasks int64+ if err := pool.QueryRow(ctx, `+ SELECT COUNT(*), COALESCE(SUM(input_tokens), 0), COALESCE(SUM(task_count), 0)+ FROM task_usage_hourly+ `).Scan(&rowCount, &sumTokens, &sumTasks); err != nil {+ t.Fatalf("query merged hourly rows: %v", err)+ }+ if rowCount != 1 || sumTokens != 3500 || sumTasks != 4 {+ t.Fatalf("post-down merged hourly = rows:%d tokens:%d tasks:%d, want 1/3500/4", rowCount, sumTokens, sumTasks)+ }++ // Legacy UNIQUE NULLS NOT DISTINCT constraints must be restored with valid backing indexes.+ for _, pair := range [][2]string{+ {"task_usage_hourly", "uq_task_usage_hourly_key"},+ {"task_usage_hourly_dirty", "uq_task_usage_hourly_dirty_key"},+ } {+ assertIndexValidity(t, pool, schema, pair[1], true)+ var conDef string+ if err := pool.QueryRow(ctx, `+ SELECT pg_get_constraintdef(c.oid)+ FROM pg_constraint c+ JOIN pg_class r ON r.oid = c.conrelid+ JOIN pg_namespace n ON n.oid = r.relnamespace+ WHERE n.nspname = $1 AND r.relname = $2 AND c.conname = $3+ `, schema, pair[0], pair[1]).Scan(&conDef); err != nil {+ t.Fatalf("legacy constraint %s.%s missing after down: %v", pair[0], pair[1], err)+ }+ if !strings.Contains(conDef, "UNIQUE NULLS NOT DISTINCT") {+ t.Fatalf("constraint %s.%s def = %q, want UNIQUE NULLS NOT DISTINCT", pair[0], pair[1], conDef)+ }+ }++ // Squad indexes must be gone.+ assertIndexExists(t, pool, schema, "uq_task_usage_hourly_squad_key_idx", false)+ assertIndexExists(t, pool, schema, "uq_task_usage_hourly_dirty_squad_key_idx", false)+ assertIndexExists(t, pool, schema, "idx_task_usage_hourly_workspace_squad_time", false)++ // 3. Re-UP: 735..742 must succeed cleanly on the rolled-back schema.+ runDir("up", versions)+ assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_squad_key_idx", true)+ assertIndexValidity(t, pool, schema, "uq_task_usage_hourly_dirty_squad_key_idx", true)+ assertIndexValidity(t, pool, schema, "idx_task_usage_hourly_workspace_squad_time", true)+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e304e41a44..e46b09e088 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2679,10 +2679,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Route("/api/dashboard", func(r chi.Router) {r.Get("/usage/daily", h.GetDashboardUsageDaily)r.Get("/usage/by-agent", h.GetDashboardUsageByAgent)+ r.Get("/usage/by-squad", h.GetDashboardUsageBySquad)r.Get("/agent-runtime", h.GetDashboardAgentRunTime)+ r.Get("/squad-runtime", h.GetDashboardSquadRunTime)r.Get("/runtime/daily", h.GetDashboardRunTimeDaily)r.Get("/failures/daily", h.GetDashboardFailuresDaily)r.Get("/failures/by-agent", h.GetDashboardFailuresByAgent)+ r.Get("/failures/by-squad", h.GetDashboardFailuresBySquad)})// Runtimesdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 424e05e669..02f8cdf763 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -891,6 +891,13 @@ func visibleTaskHistory(tasks []db.AgentTaskQueue) []db.AgentTaskQueue {// down. It populates WorkspaceID and powers the privacy-safe RelativeWorkDir// derivation; pass "" only on daemon-facing paths that genuinely don't have// it, in which case RelativeWorkDir falls back to the existing WorkDir.+func effectiveTaskSquadID(t db.AgentTaskQueue) pgtype.UUID {+ if t.UsageSquadID.Valid {+ return t.UsageSquadID+ }+ return t.SquadID+}+func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {var cancellation struct {TaskID string `json:"comment_change_cancelled_task_id"`@@ -948,6 +955,7 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {MaxAttempts: t.MaxAttempts,ParentTaskID: uuidToPtr(t.ParentTaskID),IsLeaderTask: t.IsLeaderTask,+ SquadID: uuidToString(effectiveTaskSquadID(t)),CreatedAt: timestampToString(t.CreatedAt),TriggerCommentID: uuidToPtr(t.TriggerCommentID),CoalescedCommentIDs: uuidsToStrings(t.CoalescedCommentIds),diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex c5a073e7c2..b5aa229ce5 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2955,6 +2955,12 @@ func claimResponseAgentIdentityMatches(resp AgentTaskResponse) bool {func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQueue, runtime db.AgentRuntime, runtimeID, runtimeWorkspaceID string) (resp AgentTaskResponse, deliveredCommentIDs []pgtype.UUID, issueSnapshot []byte, agentSkillCount, builtinSkillCount int, failure *claimBuildFailure) {// Build response with fresh agent data (name + skills + custom_env + custom_args).resp = taskToResponse(*task, runtimeWorkspaceID)+ // Installed daemons treat a non-empty claim `squad_id` as a quick-create+ // squad-leader signal (daemon/prompt.go:taskIsSquadLeader). Clear the row's+ // attribution SquadID here so non-leader squad member runs are never promoted+ // to leader role; the quick-create branch below re-populates resp.SquadID+ // exclusively when qc.SquadID is present.+ resp.SquadID = ""if err := (&service.IssueWakeupService{Tasks: h.TaskService}).CheckClaim(r.Context(), *task); err != nil {if !errors.Is(err, service.ErrWakeupForbidden) {return resp, nil, nil, 0, 0, h.rejectClaimSourceLoad(r.Context(), task, err, "wakeup", resp.WakeupID)diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.goindex 0027023f22..309de8a51b 100644--- a/server/internal/handler/dashboard.go+++ b/server/internal/handler/dashboard.go@@ -149,6 +149,29 @@ func parseProjectIDParam(w http.ResponseWriter, r *http.Request) (pgtype.UUID, breturn u, true}+// standaloneSquadFilterSentinel selects runs with squad_id IS NULL (direct+// standalone agent runs, not triggered via any squad).+const standaloneSquadFilterSentinel = "__standalone__"++// parseSquadScopeParam reads optional ?squad_id=<uuid | __standalone__>.+// Returns ("", invalidUUID, true) when absent, ("standalone", invalidUUID, true)+// for standalone-only filtering, or ("squad", uuid, true) for a single squad.+func parseSquadScopeParam(w http.ResponseWriter, r *http.Request) (string, pgtype.UUID, bool) {+ raw := r.URL.Query().Get("squad_id")+ if raw == "" {+ return "", pgtype.UUID{}, true+ }+ if raw == standaloneSquadFilterSentinel {+ return "standalone", pgtype.UUID{}, true+ }+ u, err := util.ParseUUID(raw)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid squad_id")+ return "", pgtype.UUID{}, false+ }+ return "squad", u, true+}+// dashboardProjectVisible guards the project_id filter: a private project// (MUL-8472) the request may not see is answered like one that does not exist,// with an empty rollup, and false.@@ -201,6 +224,10 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)if !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -208,7 +235,7 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)window := h.dashboardCutoff(w, r, workspaceID, tz, 0)since := window.since- resp, err := h.listDashboardUsageDaily(r.Context(), parseUUID(workspaceID), tz, since, projectID)+ resp, err := h.listDashboardUsageDaily(r.Context(), parseUUID(workspaceID), tz, since, projectID, squadScope, squadID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list usage")return@@ -222,12 +249,16 @@ func (h *Handler) listDashboardUsageDaily(tz string,since pgtype.Timestamptz,projectID pgtype.UUID,+ squadScope string,+ squadID pgtype.UUID,) ([]DashboardUsageDailyResponse, error) {rows, err := h.Queries.ListDashboardUsageDaily(ctx, db.ListDashboardUsageDailyParams{WorkspaceID: workspaceID,Tz: tz,Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {return nil, err@@ -290,6 +321,10 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Requesif !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -309,7 +344,7 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Requeswindow := h.dashboardCutoff(w, r, workspaceID, tz, 1)since := window.since- resp, err := h.listDashboardUsageByAgent(r.Context(), parseUUID(workspaceID), since, projectID)+ resp, err := h.listDashboardUsageByAgent(r.Context(), parseUUID(workspaceID), since, projectID, squadScope, squadID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list usage by agent")return@@ -361,11 +396,15 @@ func (h *Handler) listDashboardUsageByAgent(workspaceID pgtype.UUID,since pgtype.Timestamptz,projectID pgtype.UUID,+ squadScope string,+ squadID pgtype.UUID,) ([]DashboardUsageByAgentResponse, error) {rows, err := h.Queries.ListDashboardUsageByAgent(ctx, db.ListDashboardUsageByAgentParams{WorkspaceID: workspaceID,Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {return nil, err@@ -391,6 +430,118 @@ func (h *Handler) listDashboardUsageByAgent(return resp, nil}+// DashboardUsageBySquadResponse is one (squad, agent, provider, model) row.+// SquadID is "" for standalone (non-squad-triggered) runs. Keeping agent_id+// lets the client aggregate squad totals and render inline member breakdowns+// from one response while preserving per-model client pricing.+type DashboardUsageBySquadResponse struct {+ SquadID string `json:"squad_id"`+ AgentID string `json:"agent_id"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUSDTicks int64 `json:"cost_usd_ticks"`+ UncostedInputTokens int64 `json:"uncosted_input_tokens"`+ UncostedOutputTokens int64 `json:"uncosted_output_tokens"`+ UncostedCacheReadTokens int64 `json:"uncosted_cache_read_tokens"`+ UncostedCacheWriteTokens int64 `json:"uncosted_cache_write_tokens"`+ TaskCount int32 `json:"task_count"`+}++// GetDashboardUsageBySquad returns per-(squad, agent, provider, model) token+// aggregates for the workspace, optionally scoped to a project and/or squad.+func (h *Handler) GetDashboardUsageBySquad(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ projectID, ok := parseProjectIDParam(w, r)+ if !ok {+ return+ }+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {+ return+ }+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)+ if !ok {+ return+ }+ tz := h.resolveViewingTZ(r)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.since++ rows, err := h.Queries.ListDashboardUsageBySquad(r.Context(), db.ListDashboardUsageBySquadParams{+ WorkspaceID: parseUUID(workspaceID),+ Since: since,+ ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list usage by squad")+ return+ }+ resp := make([]DashboardUsageBySquadResponse, len(rows))+ for i, row := range rows {+ resp[i] = DashboardUsageBySquadResponse{+ SquadID: uuidToString(row.SquadID),+ AgentID: uuidToString(row.AgentID),+ Provider: row.Provider,+ Model: row.Model,+ InputTokens: row.InputTokens,+ OutputTokens: row.OutputTokens,+ CacheReadTokens: row.CacheReadTokens,+ CacheWriteTokens: row.CacheWriteTokens,+ CostUSDTicks: row.CostUsdTicks,+ UncostedInputTokens: row.UncostedInputTokens,+ UncostedOutputTokens: row.UncostedOutputTokens,+ UncostedCacheReadTokens: row.UncostedCacheReadTokens,+ UncostedCacheWriteTokens: row.UncostedCacheWriteTokens,+ TaskCount: row.TaskCount,+ }+ }+ writeJSON(w, http.StatusOK, foldRestrictedUsageBySquad(resp, restricted))+}++type squadProviderModelKey struct{ squadID, provider, model string }++func foldRestrictedUsageBySquad(+ rows []DashboardUsageBySquadResponse,+ restricted map[string]struct{},+) []DashboardUsageBySquadResponse {+ return foldRestrictedAgents(+ rows,+ restricted,+ func(row DashboardUsageBySquadResponse) string { return row.AgentID },+ func(row DashboardUsageBySquadResponse) (DashboardUsageBySquadResponse, squadProviderModelKey) {+ key := squadProviderModelKey{squadID: row.SquadID, provider: row.Provider, model: row.Model}+ row.AgentID = restrictedAgentsRowID+ return row, key+ },+ func(dst, src DashboardUsageBySquadResponse) DashboardUsageBySquadResponse {+ dst.InputTokens += src.InputTokens+ dst.OutputTokens += src.OutputTokens+ dst.CacheReadTokens += src.CacheReadTokens+ dst.CacheWriteTokens += src.CacheWriteTokens+ dst.CostUSDTicks += src.CostUSDTicks+ dst.UncostedInputTokens += src.UncostedInputTokens+ dst.UncostedOutputTokens += src.UncostedOutputTokens+ dst.UncostedCacheReadTokens += src.UncostedCacheReadTokens+ dst.UncostedCacheWriteTokens += src.UncostedCacheWriteTokens+ dst.TaskCount += src.TaskCount+ return dst+ },+ )+}+// DashboardAgentRunTimeResponse is one agent's total terminal-task run time// over the window. Includes failed and cancelled tasks so the dashboard can// surface how much execution time was spent on runs that didn't succeed.@@ -420,6 +571,10 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Requesif !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -442,6 +597,8 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.RequesWorkspaceID: parseUUID(workspaceID),Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list agent runtime")@@ -487,6 +644,95 @@ func foldRestrictedAgentRunTime()}+// DashboardSquadRunTimeResponse is one (squad, agent) terminal-task run-time+// bucket. SquadID is "" for standalone (non-squad-triggered) runs.+type DashboardSquadRunTimeResponse struct {+ SquadID string `json:"squad_id"`+ AgentID string `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ MeteredTaskCount int32 `json:"metered_task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`+}++// GetDashboardSquadRunTime returns per-(squad, agent) terminal task run time+// and task counts for the workspace.+func (h *Handler) GetDashboardSquadRunTime(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ projectID, ok := parseProjectIDParam(w, r)+ if !ok {+ return+ }+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {+ return+ }+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)+ if !ok {+ return+ }+ tz := h.resolveViewingTZ(r)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.since++ rows, err := h.Queries.ListDashboardSquadRunTime(r.Context(), db.ListDashboardSquadRunTimeParams{+ WorkspaceID: parseUUID(workspaceID),+ Since: since,+ ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list squad runtime")+ return+ }+ resp := make([]DashboardSquadRunTimeResponse, len(rows))+ for i, row := range rows {+ resp[i] = DashboardSquadRunTimeResponse{+ SquadID: uuidToString(row.SquadID),+ AgentID: uuidToString(row.AgentID),+ TotalSeconds: row.TotalSeconds,+ TaskCount: row.TaskCount,+ MeteredTaskCount: row.MeteredTaskCount,+ FailedCount: row.FailedCount,+ CancelledCount: row.CancelledCount,+ }+ }+ writeJSON(w, http.StatusOK, foldRestrictedSquadRunTime(resp, restricted))+}++func foldRestrictedSquadRunTime(+ rows []DashboardSquadRunTimeResponse,+ restricted map[string]struct{},+) []DashboardSquadRunTimeResponse {+ return foldRestrictedAgents(+ rows,+ restricted,+ func(row DashboardSquadRunTimeResponse) string { return row.AgentID },+ func(row DashboardSquadRunTimeResponse) (DashboardSquadRunTimeResponse, string) {+ squadID := row.SquadID+ row.AgentID = restrictedAgentsRowID+ return row, squadID+ },+ func(dst, src DashboardSquadRunTimeResponse) DashboardSquadRunTimeResponse {+ dst.TotalSeconds += src.TotalSeconds+ dst.TaskCount += src.TaskCount+ dst.MeteredTaskCount += src.MeteredTaskCount+ dst.FailedCount += src.FailedCount+ dst.CancelledCount += src.CancelledCount+ return dst+ },+ )+}+// DashboardRunTimeDailyResponse is one (date) bucket of terminal-task run// time and counts. Powers the workspace dashboard's daily Time and Tasks// charts — same toggle as Tokens / Cost, different metric. FailedCount and@@ -513,6 +759,10 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Requesif !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -527,6 +777,8 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.RequesTz: tz,Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list daily runtime")@@ -582,6 +834,10 @@ func (h *Handler) GetDashboardFailuresDaily(w http.ResponseWriter, r *http.Requeif !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -596,6 +852,8 @@ func (h *Handler) GetDashboardFailuresDaily(w http.ResponseWriter, r *http.RequeTz: tz,Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list daily failures")@@ -634,6 +892,10 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Reqif !ok {return}+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {return}@@ -655,6 +917,8 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.ReqWorkspaceID: parseUUID(workspaceID),Since: since,ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to list failures by agent")@@ -672,6 +936,87 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.ReqwriteJSON(w, http.StatusOK, foldRestrictedFailuresByAgent(resp, restricted))}+// DashboardFailureBySquadResponse is one (squad, agent, failure_reason) bucket.+// SquadID is "" for standalone runs; FailureReason == "" is the succeeded bucket.+type DashboardFailureBySquadResponse struct {+ SquadID string `json:"squad_id"`+ AgentID string `json:"agent_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// GetDashboardFailuresBySquad returns per-(squad, agent, failure_reason)+// terminal-task counts for the Errors tab's Squad view.+func (h *Handler) GetDashboardFailuresBySquad(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }+ projectID, ok := parseProjectIDParam(w, r)+ if !ok {+ return+ }+ squadScope, squadID, ok := parseSquadScopeParam(w, r)+ if !ok {+ return+ }+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {+ return+ }+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)+ if !ok {+ return+ }+ tz := h.resolveViewingTZ(r)+ window := h.dashboardCutoff(w, r, workspaceID, tz, 1)+ since := window.since++ rows, err := h.Queries.ListDashboardFailuresBySquad(r.Context(), db.ListDashboardFailuresBySquadParams{+ WorkspaceID: parseUUID(workspaceID),+ Since: since,+ ProjectID: projectID,+ SquadScope: squadScope,+ SquadID: squadID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list failures by squad")+ return+ }+ resp := make([]DashboardFailureBySquadResponse, len(rows))+ for i, row := range rows {+ resp[i] = DashboardFailureBySquadResponse{+ SquadID: uuidToString(row.SquadID),+ AgentID: uuidToString(row.AgentID),+ FailureReason: row.FailureReason,+ TaskCount: row.TaskCount,+ }+ }+ writeJSON(w, http.StatusOK, foldRestrictedFailuresBySquad(resp, restricted))+}++type squadFailureReasonKey struct{ squadID, reason string }++func foldRestrictedFailuresBySquad(+ rows []DashboardFailureBySquadResponse,+ restricted map[string]struct{},+) []DashboardFailureBySquadResponse {+ return foldRestrictedAgents(+ rows,+ restricted,+ func(row DashboardFailureBySquadResponse) string { return row.AgentID },+ func(row DashboardFailureBySquadResponse) (DashboardFailureBySquadResponse, squadFailureReasonKey) {+ key := squadFailureReasonKey{squadID: row.SquadID, reason: row.FailureReason}+ row.AgentID = restrictedAgentsRowID+ return row, key+ },+ func(dst, src DashboardFailureBySquadResponse) DashboardFailureBySquadResponse {+ dst.TaskCount += src.TaskCount+ return dst+ },+ )+}+// The restricted bucket keeps its failure_reason split: the client derives the// bucket's failure rate and class mix from these raw rows exactly like any// other agent's, and the succeeded rows (failure_reason == "") are thediff --git a/server/internal/handler/dashboard_squad_integration_test.go b/server/internal/handler/dashboard_squad_integration_test.gonew file mode 100644index 0000000000..b1fe27d2d2--- /dev/null+++ b/server/internal/handler/dashboard_squad_integration_test.go@@ -0,0 +1,558 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// TestDashboardSquadAttributionAndEndpoints verifies the end-to-end Squad usage+// rollup pipeline (migration 735–739), legacy NULL-squad bucket healing, the 3+// additive Squad dashboard endpoints, and `?squad_id=` scoping across the+// existing dashboard endpoints.+func TestDashboardSquadAttributionAndEndpoints(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ // Dedicated isolated runtime + 2 agents + 1 squad so ambient test rows+ // never collide with assertions.+ runtimeID := createClaimReclaimRuntime(t, ctx, "squad-dash-rt")+ leaderID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "squad-dash-leader")+ memberID, _ := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "squad-dash-member")++ var squadID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)+ VALUES ($1, 'Dashboard Squad', '', $2, $3)+ RETURNING id+ `, testWorkspaceID, leaderID, testUserID).Scan(&squadID); err != nil {+ t.Fatalf("create squad: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })++ const provider = "squad-e2e-prov"+ const model = "claude-sonnet-4-6"+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly WHERE runtime_id = $1`, runtimeID)+ testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE runtime_id = $1`, runtimeID)+ })++ now := time.Now().UTC()+ hourBucket := now.Truncate(time.Hour)+ started := now.Add(-15 * time.Minute)+ completed := now.Add(-5 * time.Minute) // 600s each++ // Pre-seed a stale legacy (pre-735) squad_id=NULL bucket for the leader in+ // the same hour. Migration 739's dirty_from_updates UNION must heal this+ // legacy NULL row down to 0 (delete it) once the squad-attributed task+ // rolls up, proving zero double-counting.+ dbfx.Exec(t, `+ INSERT INTO task_usage_hourly (+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id,+ provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, task_count, event_count+ )+ VALUES ($1, $2, $3, $4, NULL, NULL, $5, $6, 99999, 0, 0, 0, 1, 1)+ `, hourBucket, testWorkspaceID, runtimeID, leaderID, provider, model)++ // 1. Leader task (squad_id = squadID, completed, 1000 input tokens)+ leaderTaskID := dbfx.Task(t, leaderID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "is_leader_task": true,+ "squad_id": squadID,+ "started_at": started,+ "completed_at": completed,+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": leaderTaskID,+ "provider": provider,+ "model": model,+ "input_tokens": 1000,+ "output_tokens": 200,+ "created_at": now.Add(-4 * time.Minute),+ "updated_at": now.Add(-4 * time.Minute),+ })++ // 2. Delegated member task (usage_squad_id = squadID, squad_id = NULL, is_leader_task = false, failed, 2000 input tokens)+ memberSquadTaskID := dbfx.Task(t, memberID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "failed",+ "failure_reason": "timeout",+ "is_leader_task": false,+ "usage_squad_id": squadID,+ "delegated_from_task_id": leaderTaskID,+ "started_at": started,+ "completed_at": completed,+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": memberSquadTaskID,+ "provider": provider,+ "model": model,+ "input_tokens": 2000,+ "output_tokens": 400,+ "created_at": now.Add(-3 * time.Minute),+ "updated_at": now.Add(-3 * time.Minute),+ })++ // 3. Standalone member task (squad_id = NULL, completed, 500 input tokens)+ standaloneTaskID := dbfx.Task(t, memberID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "is_leader_task": false,+ "started_at": started,+ "completed_at": completed,+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": standaloneTaskID,+ "provider": provider,+ "model": model,+ "input_tokens": 500,+ "output_tokens": 100,+ "created_at": now.Add(-2 * time.Minute),+ "updated_at": now.Add(-2 * time.Minute),+ })++ // Run the hourly rollup window over the last hour.+ var affected int64+ dbfx.QueryRow(t, `SELECT rollup_task_usage_hourly_window($1, $2)`,+ now.Add(-10*time.Minute), now.Add(time.Minute),+ ).Scan(&affected)+ if affected < 3 {+ t.Fatalf("expected rollup to upsert >=3 rows, got %d", affected)+ }++ // Verify the legacy NULL squad bucket for leaderID was healed/deleted!+ var legacyCount int+ dbfx.QueryRow(t, `+ SELECT COUNT(*) FROM task_usage_hourly+ WHERE runtime_id = $1 AND agent_id = $2 AND squad_id IS NULL AND provider = $3+ `, runtimeID, leaderID, provider).Scan(&legacyCount)+ if legacyCount != 0 {+ t.Fatalf("legacy squad_id=NULL bucket for leader was NOT healed; count=%d", legacyCount)+ }++ // Helper to call dashboard handlers as the workspace owner.+ getJSON := func(handlerFn func(http.ResponseWriter, *http.Request), path string, wantStatus int, out any) {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest(http.MethodGet, path, nil)+ handlerFn(w, req)+ if w.Code != wantStatus {+ t.Fatalf("GET %s: status=%d, want %d; body=%s", path, w.Code, wantStatus, w.Body.String())+ }+ if out != nil {+ if err := json.Unmarshal(w.Body.Bytes(), out); err != nil {+ t.Fatalf("decode GET %s: %v", path, err)+ }+ }+ }++ // 1) Invalid squad_id must return 400.+ getJSON(testHandler.GetDashboardUsageDaily, "/api/dashboard/usage/daily?days=7&squad_id=not-a-uuid", http.StatusBadRequest, nil)++ // 2) GET /api/dashboard/usage/by-squad returns both squad rows and standalone row.+ var bySquad []struct {+ SquadID string `json:"squad_id"`+ AgentID string `json:"agent_id"`+ Provider string `json:"provider"`+ InputTokens int64 `json:"input_tokens"`+ TaskCount int32 `json:"task_count"`+ }+ getJSON(testHandler.GetDashboardUsageBySquad, "/api/dashboard/usage/by-squad?days=7&tz=UTC", http.StatusOK, &bySquad)+ squadTokens := int64(0)+ standaloneTokens := int64(0)+ for _, r := range bySquad {+ if r.Provider != provider {+ continue+ }+ switch r.SquadID {+ case squadID:+ squadTokens += r.InputTokens+ case "":+ standaloneTokens += r.InputTokens+ }+ }+ if squadTokens != 3000 {+ t.Fatalf("by-squad squad input_tokens = %d, want 3000 (leader 1000 + member 2000)", squadTokens)+ }+ if standaloneTokens != 500 {+ t.Fatalf("by-squad standalone input_tokens = %d, want 500", standaloneTokens)+ }++ // 3) GET /api/dashboard/usage/by-agent?squad_id=<squadID> scopes to the squad only.+ var byAgentScoped []struct {+ AgentID string `json:"agent_id"`+ Provider string `json:"provider"`+ InputTokens int64 `json:"input_tokens"`+ }+ getJSON(testHandler.GetDashboardUsageByAgent, "/api/dashboard/usage/by-agent?days=7&tz=UTC&squad_id="+squadID, http.StatusOK, &byAgentScoped)+ scopedTotal := int64(0)+ for _, r := range byAgentScoped {+ if r.Provider == provider {+ scopedTotal += r.InputTokens+ }+ }+ if scopedTotal != 3000 {+ t.Fatalf("by-agent?squad_id=<S> input_tokens = %d, want 3000", scopedTotal)+ }++ // 4) GET /api/dashboard/usage/by-agent?squad_id=__standalone__ scopes to non-squad tasks only.+ var byAgentStandalone []struct {+ AgentID string `json:"agent_id"`+ Provider string `json:"provider"`+ InputTokens int64 `json:"input_tokens"`+ }+ getJSON(testHandler.GetDashboardUsageByAgent, "/api/dashboard/usage/by-agent?days=7&tz=UTC&squad_id=__standalone__", http.StatusOK, &byAgentStandalone)+ standaloneScopedTotal := int64(0)+ for _, r := range byAgentStandalone {+ if r.Provider == provider {+ standaloneScopedTotal += r.InputTokens+ }+ }+ if standaloneScopedTotal != 500 {+ t.Fatalf("by-agent?squad_id=__standalone__ input_tokens = %d, want 500", standaloneScopedTotal)+ }++ // 5) GET /api/dashboard/squad-runtime returns per-(squad, agent) runtime totals.+ var squadRuntime []struct {+ SquadID string `json:"squad_id"`+ AgentID string `json:"agent_id"`+ TotalSeconds float64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ }+ getJSON(testHandler.GetDashboardSquadRunTime, "/api/dashboard/squad-runtime?days=7&tz=UTC", http.StatusOK, &squadRuntime)+ var squadTasks, squadFailed int32+ for _, r := range squadRuntime {+ if r.SquadID == squadID {+ squadTasks += r.TaskCount+ squadFailed += r.FailedCount+ }+ }+ if squadTasks != 2 || squadFailed != 1 {+ t.Fatalf("squad-runtime for squad = tasks:%d failed:%d, want 2/1", squadTasks, squadFailed)+ }++ // 6) GET /api/dashboard/failures/by-squad returns both succeeded ("") and failed ("timeout") rows.+ var failuresBySquad []struct {+ SquadID string `json:"squad_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+ }+ getJSON(testHandler.GetDashboardFailuresBySquad, "/api/dashboard/failures/by-squad?days=7&tz=UTC", http.StatusOK, &failuresBySquad)+ var squadSuccesses, squadTimeouts int32+ for _, r := range failuresBySquad {+ if r.SquadID != squadID {+ continue+ }+ switch r.FailureReason {+ case "":+ squadSuccesses += r.TaskCount+ case "timeout":+ squadTimeouts += r.TaskCount+ }+ }+ if squadSuccesses != 1 || squadTimeouts != 1 {+ t.Fatalf("failures/by-squad for squad = ok:%d timeout:%d, want 1/1", squadSuccesses, squadTimeouts)+ }+}++// TestSquadInheritanceAndDaemonClaimSafety verifies that:+// 1. A member task delegated from a Squad leader comment inherits squad_id+// with is_leader_task=false.+// 2. A sub-issue created by a Squad task (origin_type='agent_create') causes+// tasks enqueued for that sub-issue to inherit squad_id with+// is_leader_task=false.+// 3. ListIssueTasks exposes squad_id to the UI so execution avatars collapse.+// 4. ClaimTaskByRuntime strips squad_id (resp.Task.SquadID == "") and keeps+// is_leader_task=false with NO Squad leader briefing, preserving daemon+// compatibility with taskIsSquadLeader (daemon/prompt.go).+func TestSquadInheritanceAndDaemonClaimSafety(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ leaderRuntimeID := createClaimReclaimRuntime(t, ctx, "inherit-leader-rt")+ memberRuntimeID := createClaimReclaimRuntime(t, ctx, "inherit-member-rt")+ leaderID, parentIssueID := createClaimReclaimAgentAndIssue(t, ctx, leaderRuntimeID, "inherit-leader")+ memberID, standaloneIssueID := createClaimReclaimAgentAndIssue(t, ctx, memberRuntimeID, "inherit-member")+ dbfx.Exec(t, `UPDATE agent SET instructions = '' WHERE id IN ($1, $2)`, leaderID, memberID)++ var squadID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)+ VALUES ($1, 'Inherit Squad', '', $2, $3)+ RETURNING id+ `, testWorkspaceID, leaderID, testUserID).Scan(&squadID); err != nil {+ t.Fatalf("create squad: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })++ // Seed the leader's running task on the parent issue with squad_id = squadID.+ leaderTaskID := dbfx.Task(t, leaderID, testutil.Cols{+ "issue_id": parentIssueID,+ "runtime_id": leaderRuntimeID,+ "status": "running",+ "is_leader_task": true,+ "squad_id": squadID,+ })++ // Case A: Leader leaves a comment @mentioning memberID with source_task_id = leaderTaskID.+ var commentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO comment (workspace_id, issue_id, author_type, author_id, content, source_task_id)+ VALUES ($1, $2, 'agent', $3, 'please implement this', $4)+ RETURNING id+ `, testWorkspaceID, parentIssueID, leaderID, leaderTaskID).Scan(&commentID); err != nil {+ t.Fatalf("create leader delegation comment: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, commentID) })++ parentIssue, err := testHandler.Queries.GetIssue(ctx, parseUUID(parentIssueID))+ if err != nil {+ t.Fatalf("GetIssue(parent): %v", err)+ }+ delegatedTask, err := testHandler.TaskService.EnqueueTaskForMention(+ ctx, parentIssue, parseUUID(memberID), parseUUID(commentID), service.OriginNamed,+ )+ if err != nil {+ t.Fatalf("EnqueueTaskForMention: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, uuidToString(delegatedTask.ID)) })++ if uuidToString(delegatedTask.UsageSquadID) != squadID {+ t.Fatalf("delegated task usage_squad_id = %q, want %q", uuidToString(delegatedTask.UsageSquadID), squadID)+ }+ if delegatedTask.SquadID.Valid {+ t.Fatalf("delegated task must keep role-proof squad_id NULL, got %q", uuidToString(delegatedTask.SquadID))+ }+ if delegatedTask.IsLeaderTask {+ t.Fatalf("delegated task must have is_leader_task=false")+ }++ // Verify ListTasksByIssue exposes squad_id to the UI.+ wList := httptest.NewRecorder()+ reqList := withURLParam(newRequest(http.MethodGet, "/api/issues/"+parentIssueID+"/task-runs", nil), "id", parentIssueID)+ testHandler.ListTasksByIssue(wList, reqList)+ if wList.Code != http.StatusOK {+ t.Fatalf("ListIssueTasks status=%d: %s", wList.Code, wList.Body.String())+ }+ var listed []AgentTaskResponse+ if err := json.Unmarshal(wList.Body.Bytes(), &listed); err != nil {+ t.Fatalf("decode ListIssueTasks: %v", err)+ }+ foundDelegated := false+ for _, item := range listed {+ if item.ID == uuidToString(delegatedTask.ID) {+ foundDelegated = true+ if item.SquadID != squadID {+ t.Fatalf("ListIssueTasks delegated task squad_id = %q, want %q", item.SquadID, squadID)+ }+ if item.IsLeaderTask {+ t.Fatalf("ListIssueTasks delegated task is_leader_task = true, want false")+ }+ }+ }+ if !foundDelegated {+ t.Fatalf("delegated task %s missing from ListIssueTasks", uuidToString(delegatedTask.ID))+ }++ // CRITICAL: ClaimTaskByRuntime MUST strip squad_id on non-quick-create claims+ // so installed daemons running taskIsSquadLeader never inject leader framing.+ wClaim := httptest.NewRecorder()+ reqClaim := withURLParam(+ newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+memberRuntimeID+"/tasks/claim", nil),+ "runtimeId", memberRuntimeID,+ )+ testHandler.ClaimTaskByRuntime(wClaim, reqClaim)+ if wClaim.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime status=%d: %s", wClaim.Code, wClaim.Body.String())+ }+ var claimed struct {+ Task *AgentTaskResponse `json:"task"`+ }+ if err := json.Unmarshal(wClaim.Body.Bytes(), &claimed); err != nil {+ t.Fatalf("decode claim: %v", err)+ }+ if claimed.Task == nil || claimed.Task.ID != uuidToString(delegatedTask.ID) {+ t.Fatalf("claimed task = %+v, want %s", claimed.Task, uuidToString(delegatedTask.ID))+ }+ if claimed.Task.SquadID != "" {+ t.Fatalf("CRITICAL: ClaimTaskByRuntime leaked squad_id=%q on delegated member task!", claimed.Task.SquadID)+ }+ if claimed.Task.IsLeaderTask {+ t.Fatalf("ClaimTaskByRuntime reported is_leader_task=true on delegated member task")+ }+ if claimed.Task.Agent != nil && (strings.Contains(claimed.Task.Agent.Instructions, "## Squad Operating Protocol") ||+ strings.Contains(claimed.Task.Agent.Instructions, "## Squad Roster")) {+ t.Fatalf("ClaimTaskByRuntime injected squad briefing into delegated member task: %s", claimed.Task.Agent.Instructions)+ }++ // Case B: Sub-issue created by the Squad leader task (origin_type='agent_create',+ // origin_task_id=leaderTaskID) inherits squad_id when assigned to memberID.+ var childIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, number, title, status, priority,+ assignee_type, assignee_id, creator_type, creator_id,+ parent_issue_id, origin_type, origin_id+ )+ VALUES (+ $1, (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1),+ 'Squad Child Issue', 'todo', 'none',+ 'agent', $2, 'agent', $3,+ $4, 'agent_create', $5+ )+ RETURNING id+ `, testWorkspaceID, memberID, leaderID, parentIssueID, leaderTaskID).Scan(&childIssueID); err != nil {+ t.Fatalf("create squad child issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, childIssueID) })++ childIssue, err := testHandler.Queries.GetIssue(ctx, parseUUID(childIssueID))+ if err != nil {+ t.Fatalf("GetIssue(child): %v", err)+ }+ childTask, err := testHandler.TaskService.EnqueueTaskForIssue(ctx, childIssue)+ if err != nil {+ t.Fatalf("EnqueueTaskForIssue(child): %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, uuidToString(childTask.ID)) })+ if uuidToString(childTask.UsageSquadID) != squadID {+ t.Fatalf("sub-issue task usage_squad_id = %q, want %q", uuidToString(childTask.UsageSquadID), squadID)+ }+ if childTask.SquadID.Valid {+ t.Fatalf("sub-issue task must keep role-proof squad_id NULL, got %q", uuidToString(childTask.SquadID))+ }+ if childTask.IsLeaderTask {+ t.Fatalf("sub-issue task must have is_leader_task=false")+ }++ // Case C: Standalone human-created issue assigned to memberID stays usage_squad_id = NULL & squad_id = NULL.+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, standaloneIssueID, memberID)+ standaloneIssue, err := testHandler.Queries.GetIssue(ctx, parseUUID(standaloneIssueID))+ if err != nil {+ t.Fatalf("GetIssue(standalone): %v", err)+ }+ standaloneTask, err := testHandler.TaskService.EnqueueTaskForIssue(ctx, standaloneIssue)+ if err != nil {+ t.Fatalf("EnqueueTaskForIssue(standalone): %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, uuidToString(standaloneTask.ID)) })+ if standaloneTask.SquadID.Valid || standaloneTask.UsageSquadID.Valid {+ t.Fatalf("standalone task must have NULL squad_id and usage_squad_id, got squad=%q usage_squad=%q",+ uuidToString(standaloneTask.SquadID), uuidToString(standaloneTask.UsageSquadID))+ }+}++// TestDashboardRollupHealsLegacyNullBucketOnProjectMove reproduces the+// trigger-enqueued dirty-key scenario: a pre-735 task_usage_hourly row sits+// under (old_project, squad_id=NULL) while the underlying task carries a+// squad_id. Moving the issue to a new project enqueues dirty keys via trigger+// (not watermark). Rollup must heal/delete the legacy NULL row on old_project+// and write only the new (new_project, squad_id) row — zero double-counting.+func TestDashboardRollupHealsLegacyNullBucketOnProjectMove(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ runtimeID := createClaimReclaimRuntime(t, ctx, "squad-move-rt")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "squad-move-agent")++ var squadID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)+ VALUES ($1, 'Move Squad', '', $2, $3)+ RETURNING id+ `, testWorkspaceID, agentID, testUserID).Scan(&squadID); err != nil {+ t.Fatalf("create squad: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })++ projA := dbfx.Project(t, "Move Proj A")+ projB := dbfx.Project(t, "Move Proj B")++ dbfx.Exec(t, `UPDATE issue SET project_id = $2 WHERE id = $1`, issueID, projA)++ const provider = "squad-move-prov"+ const model = "claude-sonnet-4-6"+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly WHERE runtime_id = $1`, runtimeID)+ testPool.Exec(context.Background(), `DELETE FROM task_usage_hourly_dirty WHERE runtime_id = $1`, runtimeID)+ })++ // Place task_usage in an older hour outside the rollup's p_from..p_to+ // watermark window so ONLY dirty_from_queue (enqueued by the project-move+ // trigger) drives the rollup — exercising the exact bug path.+ oldTime := time.Now().UTC().Add(-6 * time.Hour)+ oldBucket := oldTime.Truncate(time.Hour)++ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "issue_id": issueID,+ "runtime_id": runtimeID,+ "status": "completed",+ "usage_squad_id": squadID,+ "started_at": oldTime.Add(-2 * time.Minute),+ "completed_at": oldTime,+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": taskID,+ "provider": provider,+ "model": model,+ "input_tokens": 1000,+ "output_tokens": 0,+ "created_at": oldTime,+ "updated_at": oldTime,+ })++ // Simulate pre-735 state: the bucket on projA was rolled up with squad_id = NULL.+ dbfx.Exec(t, `+ INSERT INTO task_usage_hourly (+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id,+ provider, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ task_count, event_count+ )+ VALUES ($1, $2, $3, $4, $5, NULL, $6, $7, 1000, 0, 0, 0, 1, 1)+ `, oldBucket, testWorkspaceID, runtimeID, agentID, projA, provider, model)++ // Move issue from projA to projB — fires enqueue_task_usage_hourly_dirty_for_issue_project.+ dbfx.Exec(t, `UPDATE issue SET project_id = $2 WHERE id = $1`, issueID, projB)++ // Run rollup over ONLY the last 5 minutes (excludes oldTime from dirty_raw!).+ now := time.Now().UTC()+ var affected int64+ dbfx.QueryRow(t, `SELECT rollup_task_usage_hourly_window($1, $2)`,+ now.Add(-5*time.Minute), now.Add(time.Minute),+ ).Scan(&affected)++ var totalTokens int64+ var oldProjRows int+ dbfx.QueryRow(t, `+ SELECT COALESCE(SUM(input_tokens), 0),+ COUNT(*) FILTER (WHERE project_id = $2)+ FROM task_usage_hourly+ WHERE runtime_id = $1 AND provider = $3+ `, runtimeID, projA, provider).Scan(&totalTokens, &oldProjRows)++ if oldProjRows != 0 {+ t.Fatalf("legacy NULL bucket on old project survived move: oldProjRows=%d", oldProjRows)+ }+ if totalTokens != 1000 {+ t.Fatalf("total input_tokens after project move = %d, want 1000 (no double-counting)", totalTokens)+ }+}diff --git a/server/internal/handler/dashboard_squad_unit_test.go b/server/internal/handler/dashboard_squad_unit_test.gonew file mode 100644index 0000000000..2ff676b895--- /dev/null+++ b/server/internal/handler/dashboard_squad_unit_test.go@@ -0,0 +1,130 @@+package handler++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestParseSquadScopeParam(t *testing.T) {+ validID := uuid.NewString()+ cases := []struct {+ name string+ query string+ wantScope string+ wantValid bool+ wantOK bool+ wantCode int+ }{+ {name: "empty", query: "", wantScope: "", wantValid: false, wantOK: true},+ {name: "standalone", query: "?squad_id=__standalone__", wantScope: "standalone", wantValid: false, wantOK: true},+ {name: "valid uuid", query: "?squad_id=" + validID, wantScope: "squad", wantValid: true, wantOK: true},+ {name: "invalid uuid", query: "?squad_id=not-a-uuid", wantScope: "", wantValid: false, wantOK: false, wantCode: http.StatusBadRequest},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/dashboard/usage/daily"+tc.query, nil)+ scope, id, ok := parseSquadScopeParam(rec, req)+ if ok != tc.wantOK {+ t.Fatalf("ok = %v, want %v", ok, tc.wantOK)+ }+ if scope != tc.wantScope {+ t.Fatalf("scope = %q, want %q", scope, tc.wantScope)+ }+ if id.Valid != tc.wantValid {+ t.Fatalf("id.Valid = %v, want %v", id.Valid, tc.wantValid)+ }+ if !tc.wantOK && rec.Code != tc.wantCode {+ t.Fatalf("status = %d, want %d", rec.Code, tc.wantCode)+ }+ })+ }+}++func TestFoldRestrictedUsageBySquadPreservesSquadBoundaries(t *testing.T) {+ restricted := map[string]struct{}{+ "priv-a": {},+ "priv-b": {},+ }+ rows := []DashboardUsageBySquadResponse{+ {SquadID: "squad-1", AgentID: "pub-1", Provider: "anthropic", Model: "claude", InputTokens: 100, TaskCount: 1},+ {SquadID: "squad-1", AgentID: "priv-a", Provider: "anthropic", Model: "claude", InputTokens: 200, TaskCount: 2},+ {SquadID: "squad-1", AgentID: "priv-b", Provider: "anthropic", Model: "claude", InputTokens: 300, TaskCount: 3},+ {SquadID: "squad-2", AgentID: "priv-a", Provider: "anthropic", Model: "claude", InputTokens: 50, TaskCount: 1},+ {SquadID: "", AgentID: "priv-b", Provider: "anthropic", Model: "claude", InputTokens: 75, TaskCount: 1},+ }++ got := foldRestrictedUsageBySquad(rows, restricted)+ if len(got) != 4 {+ t.Fatalf("len(got) = %d, want 4: %+v", len(got), got)+ }+ // squad-1 public row untouched, two private rows merged into one restricted row under squad-1+ if got[0].AgentID != "pub-1" || got[0].InputTokens != 100 {+ t.Fatalf("row[0] = %+v, want pub-1 100", got[0])+ }+ if got[1].SquadID != "squad-1" || got[1].AgentID != restrictedAgentsRowID || got[1].InputTokens != 500 || got[1].TaskCount != 5 {+ t.Fatalf("row[1] = %+v, want squad-1 restricted 500/5", got[1])+ }+ if got[2].SquadID != "squad-2" || got[2].AgentID != restrictedAgentsRowID || got[2].InputTokens != 50 {+ t.Fatalf("row[2] = %+v, want squad-2 restricted 50", got[2])+ }+ if got[3].SquadID != "" || got[3].AgentID != restrictedAgentsRowID || got[3].InputTokens != 75 {+ t.Fatalf("row[3] = %+v, want standalone restricted 75", got[3])+ }+}++func TestFoldRestrictedSquadRunTimeAndFailuresPreserveSquadBoundaries(t *testing.T) {+ restricted := map[string]struct{}{"priv-a": {}, "priv-b": {}}++ rt := foldRestrictedSquadRunTime([]DashboardSquadRunTimeResponse{+ {SquadID: "squad-1", AgentID: "priv-a", TotalSeconds: 60, TaskCount: 2, FailedCount: 1},+ {SquadID: "squad-1", AgentID: "priv-b", TotalSeconds: 40, TaskCount: 1, CancelledCount: 1},+ {SquadID: "", AgentID: "priv-a", TotalSeconds: 20, TaskCount: 1},+ }, restricted)+ if len(rt) != 2 {+ t.Fatalf("len(rt) = %d, want 2", len(rt))+ }+ if rt[0].SquadID != "squad-1" || rt[0].AgentID != restrictedAgentsRowID || rt[0].TotalSeconds != 100 || rt[0].TaskCount != 3 || rt[0].FailedCount != 1 || rt[0].CancelledCount != 1 {+ t.Fatalf("rt[0] = %+v", rt[0])+ }+ if rt[1].SquadID != "" || rt[1].AgentID != restrictedAgentsRowID || rt[1].TotalSeconds != 20 {+ t.Fatalf("rt[1] = %+v", rt[1])+ }++ fl := foldRestrictedFailuresBySquad([]DashboardFailureBySquadResponse{+ {SquadID: "squad-1", AgentID: "priv-a", FailureReason: "timeout", TaskCount: 2},+ {SquadID: "squad-1", AgentID: "priv-b", FailureReason: "timeout", TaskCount: 3},+ {SquadID: "squad-1", AgentID: "priv-a", FailureReason: "", TaskCount: 5},+ {SquadID: "squad-2", AgentID: "priv-b", FailureReason: "timeout", TaskCount: 1},+ }, restricted)+ if len(fl) != 3 {+ t.Fatalf("len(fl) = %d, want 3: %+v", len(fl), fl)+ }+ if fl[0].SquadID != "squad-1" || fl[0].FailureReason != "timeout" || fl[0].TaskCount != 5 {+ t.Fatalf("fl[0] = %+v", fl[0])+ }+}++func TestTaskToResponseIncludesSquadID(t *testing.T) {+ squadID := uuid.New()+ task := db.AgentTaskQueue{+ ID: pgtype.UUID{Bytes: uuid.New(), Valid: true},+ AgentID: pgtype.UUID{Bytes: uuid.New(), Valid: true},+ SquadID: pgtype.UUID{Bytes: squadID, Valid: true},+ IsLeaderTask: false,+ Status: "running",+ }+ resp := taskToResponse(task, "ws-1")+ if resp.SquadID != squadID.String() {+ t.Fatalf("resp.SquadID = %q, want %q", resp.SquadID, squadID.String())+ }+ if resp.IsLeaderTask {+ t.Fatalf("resp.IsLeaderTask = true, want false for delegated member task")+ }+}diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.goindex a1926bae95..5deec5fe3a 100644--- a/server/internal/handler/dashboard_test.go+++ b/server/internal/handler/dashboard_test.go@@ -453,7 +453,7 @@ func TestDashboardUsageDailyBucketsByViewerTimezone(t *testing.T) {$1, $2, $3, NULL, 'tz-bucket-test', 'tz-bucket-model',999, 0, 0, 0, 1)- ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATESET input_tokens = EXCLUDED.input_tokensRETURNING bucket_hour`, testWorkspaceID, runtimeID, agentID).Scan(&bucketHour)@@ -1746,7 +1746,7 @@ func TestDashboardPerAgentRollupsUseExactWindow(t *testing.T) {$1, $2, $3, NULL, $4, $5,7777, 0, 0, 0, 1)- ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATESET input_tokens = EXCLUDED.input_tokens`, testWorkspaceID, runtimeID, agentID, windowProvider, windowModel)diff --git a/server/internal/handler/runtime_test.go b/server/internal/handler/runtime_test.goindex 11d0ba06a7..0f6d4b8f0d 100644--- a/server/internal/handler/runtime_test.go+++ b/server/internal/handler/runtime_test.go@@ -423,7 +423,7 @@ func TestListRuntimeUsageBucketsByViewerTimezone(t *testing.T) {'cutoff-test', 'old-day', 111, 0, 0, 0, 1),(($2::date + interval '4 hours') AT TIME ZONE 'Asia/Shanghai', $3, $4, $5, NULL,'cutoff-test', 'cutoff-day', 222, 0, 0, 0, 1)- ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATESET input_tokens = EXCLUDED.input_tokens,output_tokens = EXCLUDED.output_tokens,cache_read_tokens = EXCLUDED.cache_read_tokens,diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.goindex 2dadc7ce3e..749f642f83 100644--- a/server/internal/service/issue_wakeup.go+++ b/server/internal/service/issue_wakeup.go@@ -1339,7 +1339,7 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)if err = guardIssueNotInTriage(ctx, q, issue.ID, OriginNamed); err != nil {return err}- var squadID pgtype.UUID+ var leaderSquadID pgtype.UUIDif issue.AssigneeType.String == "squad" && issue.AssigneeID.Valid {squad, squadErr := q.GetSquadInWorkspace(ctx, db.GetSquadInWorkspaceParams{ID: issue.AssigneeID, WorkspaceID: issue.WorkspaceID,@@ -1350,11 +1350,21 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)// Only the issue's current, active squad leader gets leader authority.// Other wakeup targets remain ordinary agent turns.if squadErr == nil && !squad.ArchivedAt.Valid && squad.LeaderID == agent.ID {- squadID = squad.ID+ leaderSquadID = squad.ID+ }+ }+ usageSquadID := leaderSquadID+ if !usageSquadID.Valid && w.SourceTaskID.Valid {+ if srcTask, srcErr := q.GetAgentTask(ctx, w.SourceTaskID); srcErr == nil {+ if srcTask.UsageSquadID.Valid {+ usageSquadID = srcTask.UsageSquadID+ } else if srcTask.SquadID.Valid {+ usageSquadID = srcTask.SquadID+ }}}contextJSON, _ := json.Marshal(map[string]any{"wakeup_id": util.UUIDToString(w.ID), "wakeup_revision": w.Revision, "wakeup_evidence": evidence, "wakeup_chain": chain})- task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{ID: dbid.NewV7(), AgentID: w.AgentID, RuntimeID: agent.RuntimeID, IssueID: w.IssueID, Priority: priorityToInt(issue.Priority), TriggerCommentID: w.ParentCommentID, TriggerSummary: pgtype.Text{String: "Wakeup: " + truncateForSummary(w.Instruction, 160), Valid: true}, HandoffNote: pgtype.Text{String: noteText, Valid: true}, IsLeaderTask: pgtype.Bool{Bool: squadID.Valid, Valid: true}, SquadID: squadID, OriginatorUserID: w.CreatedBy, AccountableUserID: w.CreatedBy, OriginatorSource: pgtype.Text{String: "trigger_owner", Valid: true}, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID, DelegatedFromTaskID: w.SourceTaskID, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps})+ task, err = q.CreateWakeupTask(ctx, db.CreateWakeupTaskParams{ID: dbid.NewV7(), AgentID: w.AgentID, RuntimeID: agent.RuntimeID, IssueID: w.IssueID, Priority: priorityToInt(issue.Priority), TriggerCommentID: w.ParentCommentID, TriggerSummary: pgtype.Text{String: "Wakeup: " + truncateForSummary(w.Instruction, 160), Valid: true}, HandoffNote: pgtype.Text{String: noteText, Valid: true}, IsLeaderTask: pgtype.Bool{Bool: leaderSquadID.Valid, Valid: true}, SquadID: leaderSquadID, UsageSquadID: usageSquadID, OriginatorUserID: w.CreatedBy, AccountableUserID: w.CreatedBy, OriginatorSource: pgtype.Text{String: "trigger_owner", Valid: true}, TriggerEvidenceKind: pgtype.Text{String: "issue_wakeup", Valid: true}, TriggerEvidenceRefID: w.ID, DelegatedFromTaskID: w.SourceTaskID, WakeupContext: contextJSON, RuntimeMcpOverlay: overlay.Overlay, RuntimeConnectedApps: overlay.ConnectedApps})}if err != nil {return errdiff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 933540a1d0..c641a67a35 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -816,6 +816,50 @@ func attributionCreateParams(attr attribution.Result) (source pgtype.Text, delegreturn}+// effectiveTaskSquadID returns a task's squad attribution (usage_squad_id if+// set, falling back to squad_id for leader/worker tasks created before+// usage_squad_id existed or stamped directly with squad_id).+func effectiveTaskSquadID(task db.AgentTaskQueue) pgtype.UUID {+ if task.UsageSquadID.Valid {+ return task.UsageSquadID+ }+ return task.SquadID+}++// resolveInheritedSquadID propagates squad usage attribution along delegation+// chains (leader comment @mention -> member task, multi-hop delegation, and+// squad-created sub-issues) while leaving direct standalone human triggers+// unattributed.+//+// Callers write the result to usage_squad_id — NEVER to squad_id — so existing+// leader/worker routing semantics keyed off squad_id (workflow step ownership,+// self-trigger suppression, conversation root ownership) remain untouched.+func (s *TaskService) resolveInheritedSquadID(ctx context.Context, issue db.Issue, explicitSquadID, delegatedFromTaskID pgtype.UUID) pgtype.UUID {+ if explicitSquadID.Valid {+ return explicitSquadID+ }+ if s == nil || s.Queries == nil {+ return pgtype.UUID{}+ }+ if delegatedFromTaskID.Valid {+ if sourceTask, err := s.Queries.GetAgentTask(ctx, delegatedFromTaskID); err == nil {+ if sid := effectiveTaskSquadID(sourceTask); sid.Valid {+ return sid+ }+ }+ }+ if issue.OriginType.Valid &&+ (issue.OriginType.String == "agent_create" || issue.OriginType.String == "quick_create") &&+ issue.OriginID.Valid {+ if originTask, err := s.Queries.GetAgentTask(ctx, issue.OriginID); err == nil {+ if sid := effectiveTaskSquadID(originTask); sid.Valid {+ return sid+ }+ }+ }+ return pgtype.UUID{}+}+// RecordHumanDelegation notes that attr's member personally started an agent// run, for the self-host telemetry "delegating member" counts. Call it once the// run row (or the fold into a queued row) is committed, with the attribution@@ -1320,6 +1364,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issueoriginatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)+ inheritedSquadID := s.resolveInheritedSquadID(ctx, issue, pgtype.UUID{}, attrDelegatedFrom)createParams := db.CreateAgentTaskParams{ID: dbid.NewV7(),AgentID: issue.AssigneeID,@@ -1331,6 +1376,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issueTriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},+ UsageSquadID: inheritedSquadID,OriginatorUserID: originatorUserID,AccountableUserID: attr.AccountableUserID,RuleVersionID: attr.RuleVersionID,@@ -1496,6 +1542,7 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issoriginatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)+ resolvedSquadID := s.resolveInheritedSquadID(ctx, issue, squadID, attrDelegatedFrom)params := db.CreateAgentTaskParams{ID: dbid.NewV7(),AgentID: agentID,@@ -1509,6 +1556,7 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},SquadID: squadID,+ UsageSquadID: resolvedSquadID,OriginatorUserID: originatorUserID,AccountableUserID: attr.AccountableUserID,RuleVersionID: attr.RuleVersionID,@@ -1706,6 +1754,7 @@ func (s *TaskService) enqueueQuickCreateTask(ctx context.Context, workspaceID, rRuntimeID: agent.RuntimeID,Priority: priorityToInt("high"),Context: contextJSON,+ UsageSquadID: squadID,OriginatorUserID: requesterID,AccountableUserID: attr.AccountableUserID,RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,diff --git a/server/migrations/735_task_usage_hourly_squad_col.down.sql b/server/migrations/735_task_usage_hourly_squad_col.down.sqlnew file mode 100644index 0000000000..d7aea5dfd8--- /dev/null+++ b/server/migrations/735_task_usage_hourly_squad_col.down.sql@@ -0,0 +1,8 @@+ALTER TABLE task_usage_hourly_dirty+ DROP COLUMN IF EXISTS squad_id;++ALTER TABLE task_usage_hourly+ DROP COLUMN IF EXISTS squad_id;++ALTER TABLE agent_task_queue+ DROP COLUMN IF EXISTS usage_squad_id;diff --git a/server/migrations/735_task_usage_hourly_squad_col.up.sql b/server/migrations/735_task_usage_hourly_squad_col.up.sqlnew file mode 100644index 0000000000..23a8359c71--- /dev/null+++ b/server/migrations/735_task_usage_hourly_squad_col.up.sql@@ -0,0 +1,27 @@+-- Add nullable squad_id dimension to task_usage_hourly and its dirty queue, and+-- a dedicated usage_squad_id attribution column to agent_task_queue.+--+-- Keeping usage_squad_id separate from agent_task_queue.squad_id preserves the+-- existing leader/worker routing semantics of squad_id (workflow step ownership,+-- self-trigger suppression, conversation root ownership) while allowing+-- delegated member runs, squad-created sub-issues, wakeups, and quick-creates+-- to carry squad attribution cleanly. Rollup and dashboard queries read+-- COALESCE(atq.usage_squad_id, atq.squad_id) so existing rows require no+-- backfill on agent_task_queue.+--+-- Metadata-only ADD COLUMN (nullable, no default): instant DDL, no table+-- rewrite, no FK (matches agent_task_queue.squad_id from migration 127).+ALTER TABLE agent_task_queue+ ADD COLUMN IF NOT EXISTS usage_squad_id UUID;++ALTER TABLE task_usage_hourly+ ADD COLUMN IF NOT EXISTS squad_id UUID;++ALTER TABLE task_usage_hourly_dirty+ ADD COLUMN IF NOT EXISTS squad_id UUID;++COMMENT ON COLUMN agent_task_queue.usage_squad_id IS+ 'Squad UUID for usage attribution and unified execution avatar grouping. Separate from squad_id (which carries leader/worker routing authority). NULL for standalone non-squad runs.';++COMMENT ON COLUMN task_usage_hourly.squad_id IS+ 'Triggering squad UUID (from COALESCE(agent_task_queue.usage_squad_id, agent_task_queue.squad_id)). NULL for standalone non-squad runs and legacy pre-backfill buckets.';diff --git a/server/migrations/736_task_usage_hourly_squad_uq_idx.down.sql b/server/migrations/736_task_usage_hourly_squad_uq_idx.down.sqlnew file mode 100644index 0000000000..cb0c04e8ee--- /dev/null+++ b/server/migrations/736_task_usage_hourly_squad_uq_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_task_usage_hourly_squad_key_idx;diff --git a/server/migrations/736_task_usage_hourly_squad_uq_idx.up.sql b/server/migrations/736_task_usage_hourly_squad_uq_idx.up.sqlnew file mode 100644index 0000000000..c8ed2e9e97--- /dev/null+++ b/server/migrations/736_task_usage_hourly_squad_uq_idx.up.sql@@ -0,0 +1,3 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_task_usage_hourly_squad_key_idx+ ON task_usage_hourly (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model)+ NULLS NOT DISTINCT;diff --git a/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.down.sql b/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.down.sqlnew file mode 100644index 0000000000..18847bc8da--- /dev/null+++ b/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_task_usage_hourly_dirty_squad_key_idx;diff --git a/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.up.sql b/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.up.sqlnew file mode 100644index 0000000000..57ad9ee586--- /dev/null+++ b/server/migrations/737_task_usage_hourly_dirty_squad_uq_idx.up.sql@@ -0,0 +1,3 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_task_usage_hourly_dirty_squad_key_idx+ ON task_usage_hourly_dirty (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model)+ NULLS NOT DISTINCT;diff --git a/server/migrations/738_task_usage_hourly_workspace_squad_idx.down.sql b/server/migrations/738_task_usage_hourly_workspace_squad_idx.down.sqlnew file mode 100644index 0000000000..7d82c52dd5--- /dev/null+++ b/server/migrations/738_task_usage_hourly_workspace_squad_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_task_usage_hourly_workspace_squad_time;diff --git a/server/migrations/738_task_usage_hourly_workspace_squad_idx.up.sql b/server/migrations/738_task_usage_hourly_workspace_squad_idx.up.sqlnew file mode 100644index 0000000000..cbf97589df--- /dev/null+++ b/server/migrations/738_task_usage_hourly_workspace_squad_idx.up.sql@@ -0,0 +1,3 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_usage_hourly_workspace_squad_time+ ON task_usage_hourly (workspace_id, squad_id, bucket_hour DESC)+ WHERE squad_id IS NOT NULL;diff --git a/server/migrations/739_task_usage_hourly_squad_pipeline.down.sql b/server/migrations/739_task_usage_hourly_squad_pipeline.down.sqlnew file mode 100644index 0000000000..3c744e4a3d--- /dev/null+++ b/server/migrations/739_task_usage_hourly_squad_pipeline.down.sql@@ -0,0 +1,360 @@+-- Rollback 739: attach the concurrently-built legacy unique indexes (from+-- 740/741 down) as UNIQUE constraints (metadata-only instant attach, zero+-- index rebuild / table scan), then restore the legacy triggers and+-- rollup_task_usage_hourly_window.++DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conrelid = 'task_usage_hourly'::regclass+ AND conname = 'uq_task_usage_hourly_key'+ ) THEN+ ALTER TABLE task_usage_hourly+ ADD CONSTRAINT uq_task_usage_hourly_key+ UNIQUE USING INDEX uq_task_usage_hourly_key;+ END IF;+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conrelid = 'task_usage_hourly_dirty'::regclass+ AND conname = 'uq_task_usage_hourly_dirty_key'+ ) THEN+ ALTER TABLE task_usage_hourly_dirty+ ADD CONSTRAINT uq_task_usage_hourly_dirty_key+ UNIQUE USING INDEX uq_task_usage_hourly_dirty_key;+ END IF;+END;+$$;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_atq()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ IF TG_OP = 'UPDATE' THEN+ IF OLD.runtime_id IS DISTINCT FROM NEW.runtime_id+ OR OLD.issue_id IS DISTINCT FROM NEW.issue_id THEN+ IF OLD.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ OLD.runtime_id,+ OLD.agent_id,+ i_old.project_id,+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = OLD.agent_id+ LEFT JOIN issue i_old ON i_old.id = OLD.issue_id+ WHERE tu.task_id = OLD.id+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;++ IF NEW.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ NEW.runtime_id,+ NEW.agent_id,+ i_new.project_id,+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = NEW.agent_id+ LEFT JOIN issue i_new ON i_new.id = NEW.issue_id+ WHERE tu.task_id = NEW.id+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ END IF;+ RETURN NEW;+ ELSIF TG_OP = 'DELETE' THEN+ IF OLD.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ OLD.runtime_id,+ OLD.agent_id,+ i.project_id,+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = OLD.agent_id+ LEFT JOIN issue i ON i.id = OLD.issue_id+ WHERE tu.task_id = OLD.id+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ RETURN OLD;+ END IF;+ RETURN NULL;+END;+$$;++DROP TRIGGER IF EXISTS trg_atq_dirty_hourly ON agent_task_queue;+CREATE TRIGGER trg_atq_dirty_hourly+BEFORE UPDATE OF runtime_id, issue_id OR DELETE ON agent_task_queue+FOR EACH ROW+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_atq();++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ OLD.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ OLD.project_id,+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = OLD.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ RETURN OLD;+END;+$$;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_project()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ IF OLD.project_id IS DISTINCT FROM NEW.project_id THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ NEW.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ OLD.project_id,+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = NEW.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);++ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ NEW.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ NEW.project_id,+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = NEW.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ RETURN NEW;+END;+$$;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_tu()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ )+ SELECT+ task_usage_hour_bucket(OLD.created_at),+ a.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ i.project_id,+ OLD.provider,+ OLD.model+ FROM agent_task_queue atq+ JOIN agent a ON a.id = atq.agent_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ WHERE atq.id = OLD.task_id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_dirty_key DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ RETURN OLD;+END;+$$;++CREATE OR REPLACE FUNCTION rollup_task_usage_hourly_window(+ p_from TIMESTAMPTZ,+ p_to TIMESTAMPTZ+)+RETURNS BIGINT+LANGUAGE plpgsql+AS $$+DECLARE+ v_rows BIGINT;+BEGIN+ IF p_from >= p_to THEN+ RETURN 0;+ END IF;++ WITH+ dirty_from_updates AS (+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at) AS bucket_hour,+ a.workspace_id AS workspace_id,+ atq.runtime_id AS runtime_id,+ atq.agent_id AS agent_id,+ i.project_id AS project_id,+ tu.provider AS provider,+ tu.model AS model+ FROM task_usage tu+ JOIN agent_task_queue atq ON atq.id = tu.task_id+ JOIN agent a ON a.id = atq.agent_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ WHERE atq.runtime_id IS NOT NULL+ AND (+ (tu.updated_at >= p_from AND tu.updated_at < p_to)+ OR (tu.updated_at IS NULL+ AND tu.created_at >= p_from+ AND tu.created_at < p_to)+ )+ ),+ dirty_from_queue AS (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model+ FROM task_usage_hourly_dirty+ WHERE enqueued_at < p_to+ ),+ dirty_keys AS (+ SELECT * FROM dirty_from_updates+ UNION+ SELECT * FROM dirty_from_queue+ ),+ recomputed AS (+ SELECT+ dk.bucket_hour,+ dk.workspace_id,+ dk.runtime_id,+ dk.agent_id,+ dk.project_id,+ dk.provider,+ dk.model,+ SUM(tu.input_tokens)::bigint AS input_tokens,+ SUM(tu.output_tokens)::bigint AS output_tokens,+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,+ COALESCE(SUM(tu.cost_usd_ticks), 0)::bigint AS cost_usd_ticks,+ COALESCE(SUM(tu.input_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_input_tokens,+ COALESCE(SUM(tu.output_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_output_tokens,+ COALESCE(SUM(tu.cache_read_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_read_tokens,+ COALESCE(SUM(tu.cache_write_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_write_tokens,+ COUNT(DISTINCT tu.task_id)::bigint AS task_count,+ COUNT(*)::bigint AS event_count+ FROM dirty_keys dk+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id+ AND atq.agent_id = dk.agent_id+ JOIN agent a ON a.id = atq.agent_id+ AND a.workspace_id = dk.workspace_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ JOIN task_usage tu ON tu.task_id = atq.id+ AND tu.provider = dk.provider+ AND tu.model = dk.model+ AND task_usage_hour_bucket(tu.created_at) = dk.bucket_hour+ WHERE (i.project_id IS NOT DISTINCT FROM dk.project_id)+ GROUP BY 1, 2, 3, 4, 5, 6, 7+ ),+ upserted AS (+ INSERT INTO task_usage_hourly AS d (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks,+ uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count+ )+ SELECT+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks,+ uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count+ FROM recomputed+ ON CONFLICT ON CONSTRAINT uq_task_usage_hourly_key DO UPDATE+ SET input_tokens = EXCLUDED.input_tokens,+ output_tokens = EXCLUDED.output_tokens,+ cache_read_tokens = EXCLUDED.cache_read_tokens,+ cache_write_tokens = EXCLUDED.cache_write_tokens,+ cost_usd_ticks = EXCLUDED.cost_usd_ticks,+ uncosted_input_tokens = EXCLUDED.uncosted_input_tokens,+ uncosted_output_tokens = EXCLUDED.uncosted_output_tokens,+ uncosted_cache_read_tokens = EXCLUDED.uncosted_cache_read_tokens,+ uncosted_cache_write_tokens = EXCLUDED.uncosted_cache_write_tokens,+ task_count = EXCLUDED.task_count,+ event_count = EXCLUDED.event_count,+ updated_at = now()+ RETURNING 1+ ),+ deleted_empty AS (+ DELETE FROM task_usage_hourly d+ USING dirty_keys dk+ WHERE d.bucket_hour = dk.bucket_hour+ AND d.workspace_id = dk.workspace_id+ AND d.runtime_id = dk.runtime_id+ AND d.agent_id = dk.agent_id+ AND d.project_id IS NOT DISTINCT FROM dk.project_id+ AND d.provider = dk.provider+ AND d.model = dk.model+ AND NOT EXISTS (+ SELECT 1 FROM recomputed r+ WHERE r.bucket_hour = dk.bucket_hour+ AND r.workspace_id = dk.workspace_id+ AND r.runtime_id = dk.runtime_id+ AND r.agent_id = dk.agent_id+ AND r.project_id IS NOT DISTINCT FROM dk.project_id+ AND r.provider = dk.provider+ AND r.model = dk.model+ )+ RETURNING 1+ )+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)+ INTO v_rows;++ DELETE FROM task_usage_hourly_dirty WHERE enqueued_at < p_to;++ RETURN v_rows;+END;+$$;diff --git a/server/migrations/739_task_usage_hourly_squad_pipeline.up.sql b/server/migrations/739_task_usage_hourly_squad_pipeline.up.sqlnew file mode 100644index 0000000000..e3b2ddc23b--- /dev/null+++ b/server/migrations/739_task_usage_hourly_squad_pipeline.up.sql@@ -0,0 +1,394 @@+-- Switch the task_usage_hourly rollup pipeline and dirty-key triggers to the+-- squad_id-aware unique indexes built concurrently in migrations 736–737,+-- reading effective squad attribution via COALESCE(usage_squad_id, squad_id).+--+-- The legacy 7-column unique constraints (uq_task_usage_hourly_key and+-- uq_task_usage_hourly_dirty_key) are dropped atomically in THIS same+-- transaction so there is never an intermediate state where the new 8-column+-- ON CONFLICT statements collide with the legacy 7-column UNIQUE constraints.+-- Migrations 740–741 are forward no-ops whose down directions rebuild the two+-- legacy backing indexes CONCURRENTLY (registered in concurrentDownIndexCleanups)+-- before 739 down attaches them via ADD CONSTRAINT ... UNIQUE USING INDEX.+--+-- Both dirty_from_updates and dirty_from_queue UNION a NULL::uuid squad_id+-- variant whenever a squad-attributed key is recomputed, so pre-735 legacy+-- buckets (stored with squad_id = NULL) heal automatically on both watermark+-- updates and trigger-driven invalidations (project move, issue delete,+-- task/usage delete) without double-counting.++ALTER TABLE task_usage_hourly+ DROP CONSTRAINT IF EXISTS uq_task_usage_hourly_key;++ALTER TABLE task_usage_hourly_dirty+ DROP CONSTRAINT IF EXISTS uq_task_usage_hourly_dirty_key;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_atq()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ IF TG_OP = 'UPDATE' THEN+ IF OLD.runtime_id IS DISTINCT FROM NEW.runtime_id+ OR OLD.issue_id IS DISTINCT FROM NEW.issue_id+ OR COALESCE(OLD.usage_squad_id, OLD.squad_id) IS DISTINCT FROM COALESCE(NEW.usage_squad_id, NEW.squad_id) THEN+ IF OLD.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ OLD.runtime_id,+ OLD.agent_id,+ i_old.project_id,+ COALESCE(OLD.usage_squad_id, OLD.squad_id),+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = OLD.agent_id+ LEFT JOIN issue i_old ON i_old.id = OLD.issue_id+ WHERE tu.task_id = OLD.id+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;++ IF NEW.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ NEW.runtime_id,+ NEW.agent_id,+ i_new.project_id,+ COALESCE(NEW.usage_squad_id, NEW.squad_id),+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = NEW.agent_id+ LEFT JOIN issue i_new ON i_new.id = NEW.issue_id+ WHERE tu.task_id = NEW.id+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ END IF;+ RETURN NEW;+ ELSIF TG_OP = 'DELETE' THEN+ IF OLD.runtime_id IS NOT NULL THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ a.workspace_id,+ OLD.runtime_id,+ OLD.agent_id,+ i.project_id,+ COALESCE(OLD.usage_squad_id, OLD.squad_id),+ tu.provider,+ tu.model+ FROM task_usage tu+ JOIN agent a ON a.id = OLD.agent_id+ LEFT JOIN issue i ON i.id = OLD.issue_id+ WHERE tu.task_id = OLD.id+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ RETURN OLD;+ END IF;+ RETURN NULL;+END;+$$;++DROP TRIGGER IF EXISTS trg_atq_dirty_hourly ON agent_task_queue;+CREATE TRIGGER trg_atq_dirty_hourly+BEFORE UPDATE OF runtime_id, issue_id, squad_id, usage_squad_id OR DELETE ON agent_task_queue+FOR EACH ROW+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')+EXECUTE FUNCTION enqueue_task_usage_hourly_dirty_for_atq();++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_delete()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ OLD.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ OLD.project_id,+ COALESCE(atq.usage_squad_id, atq.squad_id),+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = OLD.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ RETURN OLD;+END;+$$;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_issue_project()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ IF OLD.project_id IS DISTINCT FROM NEW.project_id THEN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ NEW.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ OLD.project_id,+ COALESCE(atq.usage_squad_id, atq.squad_id),+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = NEW.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);++ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at),+ NEW.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ NEW.project_id,+ COALESCE(atq.usage_squad_id, atq.squad_id),+ tu.provider,+ tu.model+ FROM agent_task_queue atq+ JOIN task_usage tu ON tu.task_id = atq.id+ WHERE atq.issue_id = NEW.id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ END IF;+ RETURN NEW;+END;+$$;++CREATE OR REPLACE FUNCTION enqueue_task_usage_hourly_dirty_for_tu()+RETURNS TRIGGER+LANGUAGE plpgsql+AS $$+BEGIN+ INSERT INTO task_usage_hourly_dirty (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ )+ SELECT+ task_usage_hour_bucket(OLD.created_at),+ a.workspace_id,+ atq.runtime_id,+ atq.agent_id,+ i.project_id,+ COALESCE(atq.usage_squad_id, atq.squad_id),+ OLD.provider,+ OLD.model+ FROM agent_task_queue atq+ JOIN agent a ON a.id = atq.agent_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ WHERE atq.id = OLD.task_id+ AND atq.runtime_id IS NOT NULL+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET enqueued_at = GREATEST(task_usage_hourly_dirty.enqueued_at, EXCLUDED.enqueued_at);+ RETURN OLD;+END;+$$;++CREATE OR REPLACE FUNCTION rollup_task_usage_hourly_window(+ p_from TIMESTAMPTZ,+ p_to TIMESTAMPTZ+)+RETURNS BIGINT+LANGUAGE plpgsql+AS $$+DECLARE+ v_rows BIGINT;+BEGIN+ IF p_from >= p_to THEN+ RETURN 0;+ END IF;++ WITH+ dirty_raw AS (+ SELECT DISTINCT+ task_usage_hour_bucket(tu.created_at) AS bucket_hour,+ a.workspace_id AS workspace_id,+ atq.runtime_id AS runtime_id,+ atq.agent_id AS agent_id,+ i.project_id AS project_id,+ COALESCE(atq.usage_squad_id, atq.squad_id) AS squad_id,+ tu.provider AS provider,+ tu.model AS model+ FROM task_usage tu+ JOIN agent_task_queue atq ON atq.id = tu.task_id+ JOIN agent a ON a.id = atq.agent_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ WHERE atq.runtime_id IS NOT NULL+ AND (+ (tu.updated_at >= p_from AND tu.updated_at < p_to)+ OR (tu.updated_at IS NULL+ AND tu.created_at >= p_from+ AND tu.created_at < p_to)+ )+ ),+ dirty_from_updates AS (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ FROM dirty_raw+ UNION+ -- Heal pre-735 buckets (stored with squad_id = NULL) whenever a+ -- squad-attributed task in that bucket is recomputed or backfilled.+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, NULL::uuid AS squad_id, provider, model+ FROM dirty_raw+ WHERE squad_id IS NOT NULL+ ),+ dirty_queue_raw AS (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ FROM task_usage_hourly_dirty+ WHERE enqueued_at < p_to+ ),+ dirty_from_queue AS (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model+ FROM dirty_queue_raw+ UNION+ -- Heal pre-735 legacy NULL-squad buckets when triggers (issue project+ -- move, issue delete, task/task_usage delete) enqueue a squad-attributed+ -- dirty key, preventing old NULL buckets from surviving and double-counting.+ SELECT bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, NULL::uuid AS squad_id, provider, model+ FROM dirty_queue_raw+ WHERE squad_id IS NOT NULL+ ),+ dirty_keys AS (+ SELECT * FROM dirty_from_updates+ UNION+ SELECT * FROM dirty_from_queue+ ),+ recomputed AS (+ SELECT+ dk.bucket_hour,+ dk.workspace_id,+ dk.runtime_id,+ dk.agent_id,+ dk.project_id,+ dk.squad_id,+ dk.provider,+ dk.model,+ SUM(tu.input_tokens)::bigint AS input_tokens,+ SUM(tu.output_tokens)::bigint AS output_tokens,+ SUM(tu.cache_read_tokens)::bigint AS cache_read_tokens,+ SUM(tu.cache_write_tokens)::bigint AS cache_write_tokens,+ COALESCE(SUM(tu.cost_usd_ticks), 0)::bigint AS cost_usd_ticks,+ COALESCE(SUM(tu.input_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_input_tokens,+ COALESCE(SUM(tu.output_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_output_tokens,+ COALESCE(SUM(tu.cache_read_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_read_tokens,+ COALESCE(SUM(tu.cache_write_tokens) FILTER (WHERE tu.cost_usd_ticks IS NULL), 0)::bigint AS uncosted_cache_write_tokens,+ COUNT(DISTINCT tu.task_id)::bigint AS task_count,+ COUNT(*)::bigint AS event_count+ FROM dirty_keys dk+ JOIN agent_task_queue atq ON atq.runtime_id = dk.runtime_id+ AND atq.agent_id = dk.agent_id+ AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NOT DISTINCT FROM dk.squad_id+ JOIN agent a ON a.id = atq.agent_id+ AND a.workspace_id = dk.workspace_id+ LEFT JOIN issue i ON i.id = atq.issue_id+ JOIN task_usage tu ON tu.task_id = atq.id+ AND tu.provider = dk.provider+ AND tu.model = dk.model+ AND task_usage_hour_bucket(tu.created_at) = dk.bucket_hour+ WHERE (i.project_id IS NOT DISTINCT FROM dk.project_id)+ GROUP BY 1, 2, 3, 4, 5, 6, 7, 8+ ),+ upserted AS (+ INSERT INTO task_usage_hourly AS d (+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks,+ uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count+ )+ SELECT+ bucket_hour, workspace_id, runtime_id, agent_id,+ project_id, squad_id, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks,+ uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count+ FROM recomputed+ ON CONFLICT (bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model) DO UPDATE+ SET input_tokens = EXCLUDED.input_tokens,+ output_tokens = EXCLUDED.output_tokens,+ cache_read_tokens = EXCLUDED.cache_read_tokens,+ cache_write_tokens = EXCLUDED.cache_write_tokens,+ cost_usd_ticks = EXCLUDED.cost_usd_ticks,+ uncosted_input_tokens = EXCLUDED.uncosted_input_tokens,+ uncosted_output_tokens = EXCLUDED.uncosted_output_tokens,+ uncosted_cache_read_tokens = EXCLUDED.uncosted_cache_read_tokens,+ uncosted_cache_write_tokens = EXCLUDED.uncosted_cache_write_tokens,+ task_count = EXCLUDED.task_count,+ event_count = EXCLUDED.event_count,+ updated_at = now()+ RETURNING 1+ ),+ deleted_empty AS (+ DELETE FROM task_usage_hourly d+ USING dirty_keys dk+ WHERE d.bucket_hour = dk.bucket_hour+ AND d.workspace_id = dk.workspace_id+ AND d.runtime_id = dk.runtime_id+ AND d.agent_id = dk.agent_id+ AND d.project_id IS NOT DISTINCT FROM dk.project_id+ AND d.squad_id IS NOT DISTINCT FROM dk.squad_id+ AND d.provider = dk.provider+ AND d.model = dk.model+ AND NOT EXISTS (+ SELECT 1 FROM recomputed r+ WHERE r.bucket_hour = dk.bucket_hour+ AND r.workspace_id = dk.workspace_id+ AND r.runtime_id = dk.runtime_id+ AND r.agent_id = dk.agent_id+ AND r.project_id IS NOT DISTINCT FROM dk.project_id+ AND r.squad_id IS NOT DISTINCT FROM dk.squad_id+ AND r.provider = dk.provider+ AND r.model = dk.model+ )+ RETURNING 1+ )+ SELECT (SELECT COUNT(*) FROM upserted) + (SELECT COUNT(*) FROM deleted_empty)+ INTO v_rows;++ DELETE FROM task_usage_hourly_dirty WHERE enqueued_at < p_to;++ RETURN v_rows;+END;+$$;diff --git a/server/migrations/740_task_usage_hourly_drop_legacy_key.down.sql b/server/migrations/740_task_usage_hourly_drop_legacy_key.down.sqlnew file mode 100644index 0000000000..50955bd146--- /dev/null+++ b/server/migrations/740_task_usage_hourly_drop_legacy_key.down.sql@@ -0,0 +1,3 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_task_usage_hourly_key+ ON task_usage_hourly (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)+ NULLS NOT DISTINCT;diff --git a/server/migrations/740_task_usage_hourly_drop_legacy_key.up.sql b/server/migrations/740_task_usage_hourly_drop_legacy_key.up.sqlnew file mode 100644index 0000000000..6013b85857--- /dev/null+++ b/server/migrations/740_task_usage_hourly_drop_legacy_key.up.sql@@ -0,0 +1,6 @@+-- Forward no-op: uq_task_usage_hourly_key is dropped atomically in 739 up+-- alongside the function switch so there is no intermediate constraint-conflict+-- window. This migration exists so the down direction can rebuild the legacy+-- 7-column unique index CONCURRENTLY (registered in concurrentDownIndexCleanups)+-- before 739 down attaches it via ADD CONSTRAINT ... UNIQUE USING INDEX.+SELECT 1;diff --git a/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.down.sql b/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.down.sqlnew file mode 100644index 0000000000..818017e36f--- /dev/null+++ b/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.down.sql@@ -0,0 +1,3 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_task_usage_hourly_dirty_key+ ON task_usage_hourly_dirty (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)+ NULLS NOT DISTINCT;diff --git a/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.up.sql b/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.up.sqlnew file mode 100644index 0000000000..e20012e165--- /dev/null+++ b/server/migrations/741_task_usage_hourly_dirty_drop_legacy_key.up.sql@@ -0,0 +1,6 @@+-- Forward no-op: uq_task_usage_hourly_dirty_key is dropped atomically in 739 up+-- alongside the trigger switch so there is no intermediate constraint-conflict+-- window. This migration exists so the down direction can rebuild the legacy+-- 7-column unique index CONCURRENTLY (registered in concurrentDownIndexCleanups)+-- before 739 down attaches it via ADD CONSTRAINT ... UNIQUE USING INDEX.+SELECT 1;diff --git a/server/migrations/742_task_usage_hourly_squad_rollback_merge.down.sql b/server/migrations/742_task_usage_hourly_squad_rollback_merge.down.sqlnew file mode 100644index 0000000000..011c1eeef8--- /dev/null+++ b/server/migrations/742_task_usage_hourly_squad_rollback_merge.down.sql@@ -0,0 +1,64 @@+-- Rollback prep before 741/740 down rebuild legacy 7-column unique indexes+-- CONCURRENTLY: merge any split squad_id buckets in task_usage_hourly back into+-- a single squad_id = NULL row per 7-column key so the concurrent unique index+-- builds succeed without uniqueness violations.+--+-- Operational note: pause the rollup worker before running rollback so the+-- squad-aware rollup does not write new split squad_id rows during the window+-- between 742 down and 741/740 down finishing their CONCURRENTLY index builds+-- (if interrupted, concurrentDownIndexCleanups cleans up any INVALID index for+-- safe retry).+--+-- Materialize merged rows into a transaction-scoped temp table and DELETE+-- before INSERT as separate statements: a single CTE WITH DELETE + INSERT runs+-- under one MVCC snapshot and collides with uq_task_usage_hourly_squad_key_idx+-- when a standalone (squad_id = NULL) row already shares the 7-column key.+--+-- Unprocessed task_usage_hourly_dirty rows carrying a non-NULL squad_id are+-- discarded here so 741 down can rebuild uq_task_usage_hourly_dirty_key; those+-- buckets will recompute on the next triggering touch or watermark backfill.+CREATE TEMP TABLE _tmp_merged_task_usage_hourly ON COMMIT DROP AS+SELECT+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model,+ SUM(input_tokens)::bigint AS input_tokens,+ SUM(output_tokens)::bigint AS output_tokens,+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,+ SUM(cache_write_tokens)::bigint AS cache_write_tokens,+ SUM(cost_usd_ticks)::bigint AS cost_usd_ticks,+ SUM(COALESCE(uncosted_input_tokens, input_tokens))::bigint AS uncosted_input_tokens,+ SUM(COALESCE(uncosted_output_tokens, output_tokens))::bigint AS uncosted_output_tokens,+ SUM(COALESCE(uncosted_cache_read_tokens, cache_read_tokens))::bigint AS uncosted_cache_read_tokens,+ SUM(COALESCE(uncosted_cache_write_tokens, cache_write_tokens))::bigint AS uncosted_cache_write_tokens,+ SUM(task_count)::bigint AS task_count,+ SUM(event_count)::bigint AS event_count,+ MAX(updated_at) AS updated_at+ FROM task_usage_hourly+ WHERE (bucket_hour, workspace_id, runtime_id, agent_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid), provider, model) IN (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid), provider, model+ FROM task_usage_hourly+ WHERE squad_id IS NOT NULL+ )+ GROUP BY 1, 2, 3, 4, 5, 6, 7;++DELETE FROM task_usage_hourly+ WHERE (bucket_hour, workspace_id, runtime_id, agent_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid), provider, model) IN (+ SELECT bucket_hour, workspace_id, runtime_id, agent_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid), provider, model+ FROM _tmp_merged_task_usage_hourly+ );++INSERT INTO task_usage_hourly (+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, squad_id, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks, uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count, updated_at+)+SELECT+ bucket_hour, workspace_id, runtime_id, agent_id, project_id, NULL, provider, model,+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,+ cost_usd_ticks, uncosted_input_tokens, uncosted_output_tokens,+ uncosted_cache_read_tokens, uncosted_cache_write_tokens,+ task_count, event_count, updated_at+ FROM _tmp_merged_task_usage_hourly;++DELETE FROM task_usage_hourly_dirty WHERE squad_id IS NOT NULL;diff --git a/server/migrations/742_task_usage_hourly_squad_rollback_merge.up.sql b/server/migrations/742_task_usage_hourly_squad_rollback_merge.up.sqlnew file mode 100644index 0000000000..e648f0ad7f--- /dev/null+++ b/server/migrations/742_task_usage_hourly_squad_rollback_merge.up.sql@@ -0,0 +1,4 @@+-- Forward no-op: pairs with 742 down, which merges split squad_id buckets back+-- into squad_id = NULL before 741/740 down rebuild the legacy 7-column unique+-- indexes CONCURRENTLY.+SELECT 1;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex e9218806bd..8892be4369 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -32,7 +32,7 @@ WHERE acknowledged.id = (WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'AND attempt_count.trigger_evidence_ref_id = $2) >= $3::int-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot, acknowledged.workflow_step+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot, acknowledged.workflow_step, acknowledged.usage_squad_id`type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {@@ -109,6 +109,7 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -310,7 +311,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Automatic cancellation without an explicit persisted failure reason. Unlike@@ -379,6 +380,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -440,7 +442,7 @@ SET status = 'cancelled',ENDWHERE task.id = $1AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`type CancelAgentTaskByUserParams struct {@@ -523,6 +525,7 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, arg CancelAgentTask&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -538,7 +541,7 @@ SET status = 'cancelled',cancelled_by_id = NULL,cancelled_by_name = NULLWHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CancelAgentTaskWithReasonParams struct {@@ -618,6 +621,7 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -627,7 +631,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -705,6 +709,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -721,7 +726,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Cancels active tasks belonging to a chat session. Called from@@ -799,6 +804,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -815,7 +821,7 @@ UPDATE agent_task_queueSET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Cancels every active task on the issue and returns the affected rows so the@@ -893,6 +899,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -911,7 +918,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,context = COALESCE(context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', id::text)WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Cancels active tasks whose planned batch contains the edited/deleted comment.@@ -988,6 +995,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1005,7 +1013,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE issue_id = $1 AND agent_id = $2AND status IN ('queued', 'dispatched', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CancelPendingTasksByIssueAndAgentParams struct {@@ -1099,6 +1107,7 @@ func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg Can&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1117,7 +1126,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,WHERE issue_id = $1 AND agent_id = $2AND status IN ('queued', 'dispatched', 'deferred')AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CancelPendingTasksByIssueAndAgentInThreadParams struct {@@ -1198,6 +1207,7 @@ func (q *Queries) CancelPendingTasksByIssueAndAgentInThread(ctx context.Context,&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1218,7 +1228,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,WHERE id = $4AND chat_session_id = $5AND status = 'queued'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CancelQueuedAgentTaskParams struct {@@ -1301,6 +1311,7 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1329,7 +1340,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,WHERE queued.chat_session_id = $1AND queued.status = 'queued'AND queued.id IS DISTINCT FROM (SELECT id FROM head)-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot, queued.workflow_step+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot, queued.workflow_step, queued.usage_squad_id`// Clear only positional follow-ups. The first visible task is current even@@ -1406,6 +1417,7 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1434,7 +1446,7 @@ WHERE r.runtime_id = ANY($1::uuid[])AND successor.id <> r.idAND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory'))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Cancels deferred auto-retry rows that a newer active task has already@@ -1529,6 +1541,7 @@ func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1591,7 +1604,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type ClaimAgentTaskParams struct {@@ -1680,6 +1693,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1688,7 +1702,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :oneUPDATE agent_task_queueSET chat_finalize_deferred_at = NULLWHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Atomically claims the deferred marker so the daemon ack and the sweeper@@ -1757,6 +1771,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1955,7 +1970,7 @@ SET status = 'completed', completed_at = now(), result = $2,retired_session_id = COALESCE($8, retired_session_id),prepare_lease_expires_at = NULLWHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CompleteAgentTaskParams struct {@@ -2053,6 +2068,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -2265,16 +2281,16 @@ func (q *Queries) CreateAgentBuilder(ctx context.Context, arg CreateAgentBuilderconst createAgentTask = `-- name: CreateAgentTask :oneWITH enqueue_agent AS MATERIALIZED (- SELECT a.id, COALESCE(a.runtime_id, $27::uuid) AS runtime_id+ SELECT a.id, COALESCE(a.runtime_id, $28::uuid) AS runtime_idFROM agent aWHERE a.id = $1- AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $27::uuid))+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $28::uuid))FOR KEY SHARE OF a)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,workflow_step, fire_at, id)@@ -2288,20 +2304,20 @@ SELECTCOALESCE($9::boolean, FALSE),$10,$11,+ $12,NULLIF(CASE- WHEN COALESCE($12::text, '') <> ''- THEN jsonb_build_object('head_sha', $12::text)+ WHEN COALESCE($13::text, '') <> ''+ THEN jsonb_build_object('head_sha', $13::text)ELSE '{}'::jsonbEND || CASE- WHEN COALESCE($13::boolean, FALSE)+ WHEN COALESCE($14::boolean, FALSE)THEN '{"fresh_rerun":true}'::jsonbELSE '{}'::jsonbEND || CASE- WHEN $14::bigint IS NOT NULL- THEN jsonb_build_object('workflow_handoff_revision', $14::bigint)+ WHEN $15::bigint IS NOT NULL+ THEN jsonb_build_object('workflow_handoff_revision', $15::bigint)ELSE '{}'::jsonbEND, '{}'::jsonb),- $15,$16,$17,$18,@@ -2311,12 +2327,13 @@ SELECT$22,$23,$24,+ $25,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).- COALESCE($25::text, (SELECT i.status FROM issue i WHERE i.id = $2)),+ COALESCE($26::text, (SELECT i.status FROM issue i WHERE i.id = $2)),$3,- COALESCE($26::uuid, gen_random_uuid())+ COALESCE($27::uuid, gen_random_uuid())FROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateAgentTaskParams struct {@@ -2331,6 +2348,7 @@ type CreateAgentTaskParams struct {IsLeaderTask pgtype.Bool `json:"is_leader_task"`HandoffNote pgtype.Text `json:"handoff_note"`SquadID pgtype.UUID `json:"squad_id"`+ UsageSquadID pgtype.UUID `json:"usage_squad_id"`HeadSha pgtype.Text `json:"head_sha"`FreshRerun pgtype.Bool `json:"fresh_rerun"`WorkflowHandoffRevision pgtype.Int8 `json:"workflow_handoff_revision"`@@ -2386,6 +2404,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsarg.IsLeaderTask,arg.HandoffNote,arg.SquadID,+ arg.UsageSquadID,arg.HeadSha,arg.FreshRerun,arg.WorkflowHandoffRevision,@@ -2465,22 +2484,23 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}const createDeferredChannelIssueTask = `-- name: CreateDeferredChannelIssueTask :oneWITH enqueue_agent AS MATERIALIZED (- SELECT a.id, COALESCE(a.runtime_id, $24::uuid) AS runtime_id+ SELECT a.id, COALESCE(a.runtime_id, $25::uuid) AS runtime_idFROM agent aWHERE a.id = $1- AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $24::uuid))+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $25::uuid))FOR KEY SHARE OF a)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,trigger_evidence_kind, trigger_evidence_ref_id, fire_at,workflow_step, id@@ -2493,11 +2513,11 @@ SELECTCOALESCE($8::boolean, FALSE),$9,$10,+ $11,jsonb_strip_nulls(jsonb_build_object(- 'head_sha', NULLIF(COALESCE($11::text, ''), ''),+ 'head_sha', NULLIF(COALESCE($12::text, ''), ''),'channel_issue_media_pending', TRUE)),- $12,$13,$14,$15,@@ -2508,11 +2528,12 @@ SELECT$20,$21,$22,+ $23,-- The issue's status as this task is queued: the workflow step it works on (MUL-7420).(SELECT i.status FROM issue i WHERE i.id = $2),- COALESCE($23::uuid, gen_random_uuid())+ COALESCE($24::uuid, gen_random_uuid())FROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateDeferredChannelIssueTaskParams struct {@@ -2526,6 +2547,7 @@ type CreateDeferredChannelIssueTaskParams struct {IsLeaderTask pgtype.Bool `json:"is_leader_task"`HandoffNote pgtype.Text `json:"handoff_note"`SquadID pgtype.UUID `json:"squad_id"`+ UsageSquadID pgtype.UUID `json:"usage_squad_id"`HeadSha pgtype.Text `json:"head_sha"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`AccountableUserID pgtype.UUID `json:"accountable_user_id"`@@ -2561,6 +2583,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Createarg.IsLeaderTask,arg.HandoffNote,arg.SquadID,+ arg.UsageSquadID,arg.HeadSha,arg.OriginatorUserID,arg.AccountableUserID,@@ -2638,6 +2661,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -2645,14 +2669,14 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Createconst createManualQuickCreateRetryTask = `-- name: CreateManualQuickCreateRetryTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context,- force_fresh_session, is_leader_task, squad_id,+ force_fresh_session, is_leader_task, squad_id, usage_squad_id,originator_user_id, accountable_user_id,runtime_mcp_overlay, runtime_connected_apps,originator_source, rerun_of_task_id, id)SELECTp.agent_id, COALESCE(a.runtime_id, p.runtime_id), 'queued', p.priority, p.context,- TRUE, p.is_leader_task, p.squad_id,+ TRUE, p.is_leader_task, p.squad_id, p.usage_squad_id,$1, $1,$2, $3,'direct_human', p.id, $4@@ -2664,7 +2688,7 @@ WHERE p.id = $5AND p.chat_session_id IS NULLAND p.autopilot_run_id IS NULLAND lock_task_owner_rows(p.agent_id, p.issue_id, COALESCE(a.runtime_id, p.runtime_id))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateManualQuickCreateRetryTaskParams struct {@@ -2755,20 +2779,21 @@ func (q *Queries) CreateManualQuickCreateRetryTask(ctx context.Context, arg Crea&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}const createQuickCreateTask = `-- name: CreateQuickCreateTask :oneWITH enqueue_agent AS MATERIALIZED (- SELECT a.id, COALESCE(a.runtime_id, $12::uuid) AS runtime_id+ SELECT a.id, COALESCE(a.runtime_id, $13::uuid) AS runtime_idFROM agent aWHERE a.id = $1- AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, $12::uuid))+ AND lock_task_owner_rows(a.id, NULL, COALESCE(a.runtime_id, $13::uuid))FOR KEY SHARE OF a)INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,+ agent_id, runtime_id, issue_id, status, priority, context, usage_squad_id, originator_user_id,accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, trigger_evidence_kind, trigger_evidence_ref_id,id@@ -2782,15 +2807,17 @@ SELECT$8,$9,$10,- COALESCE($11::uuid, gen_random_uuid())+ $11,+ COALESCE($12::uuid, gen_random_uuid())FROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateQuickCreateTaskParams struct {AgentID pgtype.UUID `json:"agent_id"`Priority int32 `json:"priority"`Context []byte `json:"context"`+ UsageSquadID pgtype.UUID `json:"usage_squad_id"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`AccountableUserID pgtype.UUID `json:"accountable_user_id"`RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`@@ -2817,6 +2844,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreaarg.AgentID,arg.Priority,arg.Context,+ arg.UsageSquadID,arg.OriginatorUserID,arg.AccountableUserID,arg.RuntimeMcpOverlay,@@ -2889,6 +2917,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -2899,7 +2928,7 @@ INSERT INTO agent_task_queue (status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,- squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id,trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,chat_input_task_id, fire_at,@@ -2918,6 +2947,7 @@ SELECTp.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',p.is_leader_task,p.squad_id,+ p.usage_squad_id,p.originator_user_id,p.accountable_user_id,$4,@@ -2940,7 +2970,7 @@ WHERE p.id = $1ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))) WHERE status IN ('queued', 'dispatched')OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')DO NOTHING-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateRetryTaskParams struct {@@ -3048,6 +3078,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -3228,7 +3259,7 @@ WHERE t.id = v.idWHERE retry_parent.id = t.parent_task_idAND retry_parent.failure_reason = 'runtime_offline')-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id`type ExpireStaleQueuedTasksParams struct {@@ -3314,6 +3345,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -3332,7 +3364,7 @@ WHERE id = $1AND runtime_id = $2AND status IN ('dispatched', 'waiting_local_directory')AND started_at IS NULL-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type ExtendAgentTaskPrepareLeaseParams struct {@@ -3409,6 +3441,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -3427,7 +3460,7 @@ SET status = 'failed',retired_session_id = COALESCE($9, retired_session_id),prepare_lease_expires_at = NULLWHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type FailAgentTaskParams struct {@@ -3531,6 +3564,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -3577,7 +3611,7 @@ WHERE retry.id = victims.idAND COALESCE(runtime.last_seen_at, runtime.updated_at) >=now() - make_interval(secs => $2::double precision))-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot, retry.workflow_step+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot, retry.workflow_step, retry.usage_squad_id`type FailExpiredRuntimeReconnectRetriesParams struct {@@ -3663,6 +3697,7 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -3717,7 +3752,7 @@ WHERE ()))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type FailStaleTasksParams struct {@@ -3834,6 +3869,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -4075,7 +4111,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE id = $1`@@ -4143,12 +4179,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE id = $1FOR UPDATE`@@ -4220,12 +4257,13 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE atq.id = $1 AND a.workspace_id = $2`@@ -4306,6 +4344,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -5181,7 +5220,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC`@@ -5261,6 +5300,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -5375,7 +5415,7 @@ func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActi}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE agent_id = $1-- Apply visibility before LIMIT so hidden fallbacks cannot end a page early.-- Keep this predicate in sync with handler.visibleTaskHistory.@@ -5468,6 +5508,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, arg ListAgentTasksParams)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -5658,7 +5699,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U}const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE chat_finalize_deferred_at IS NOT NULLAND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)ORDER BY chat_finalize_deferred_at@@ -5743,6 +5784,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6020,7 +6062,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -6095,6 +6137,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6107,7 +6150,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atqWHERE atq.runtime_id = $1AND atq.status = 'queued'AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))@@ -6204,6 +6247,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6216,7 +6260,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim}const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atqWHERE atq.runtime_id = ANY($1::uuid[])AND atq.status = 'queued'AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))@@ -6315,6 +6359,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6327,7 +6372,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -6402,6 +6447,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6422,7 +6468,7 @@ WITH RECURSIVE subtree(id) AS (JOIN subtree parent ON child.parent_issue_id = parent.idWHERE child.workspace_id = $3)-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, i.title AS issue_title, i.number AS issue_number, w.issue_prefix+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, i.title AS issue_title, i.number AS issue_number, w.issue_prefixFROM agent_task_queue atqJOIN subtree ON subtree.id = atq.issue_idJOIN issue i ON i.id = atq.issue_id@@ -6517,6 +6563,7 @@ func (q *Queries) ListTasksByIssueSubtree(ctx context.Context, arg ListTasksByIs&i.AgentTaskQueue.CancelledByName,&i.AgentTaskQueue.IssueSnapshot,&i.AgentTaskQueue.WorkflowStep,+ &i.AgentTaskQueue.UsageSquadID,&i.IssueTitle,&i.IssueNumber,&i.IssuePrefix,@@ -6627,7 +6674,7 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI}const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1AND (atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')@@ -6635,9 +6682,9 @@ WHERE a.workspace_id = $1UNION ALL-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot, latest.workflow_step FROM agent a+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot, latest.workflow_step, latest.usage_squad_id FROM agent aJOIN LATERAL (- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_idFROM agent_task_queue atqWHERE atq.agent_id = a.idAND atq.status IN ('completed', 'failed')@@ -6742,6 +6789,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -6996,7 +7044,7 @@ func (q *Queries) LockAgentForTaskEnqueue(ctx context.Context, id pgtype.UUID) (}const lockAgentTaskStartClaim = `-- name: LockAgentTaskStartClaim :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3AND status IN ('dispatched', 'waiting_local_directory', 'running')FOR UPDATE@@ -7074,6 +7122,7 @@ func (q *Queries) LockAgentTaskStartClaim(ctx context.Context, arg LockAgentTask&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7084,7 +7133,7 @@ SET status = 'waiting_local_directory',wait_reason = $2,prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type MarkAgentTaskWaitingLocalDirectoryParams struct {@@ -7167,6 +7216,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7175,7 +7225,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :oneUPDATE agent_task_queueSET chat_finalize_deferred_at = now()WHERE id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Arms the deferred chat-finalize marker for a cancelled chat task whose@@ -7244,6 +7294,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7305,7 +7356,7 @@ WHERE id = (LIMIT 1FOR UPDATE OF t)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type MergeCommentIntoPendingTaskParams struct {@@ -7448,6 +7499,7 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeComm&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7475,7 +7527,7 @@ WHERE id = (ORDER BY t.created_at DESCLIMIT 1)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type MergeDelegatedFailureCommentIntoPendingTaskParams struct {@@ -7560,6 +7612,7 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7616,7 +7669,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTasUPDATE agent_task_queueSET status = 'queued', fire_at = NULLWHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Early promotion is idempotent at the service layer: a task already promoted@@ -7685,6 +7738,7 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -7723,7 +7777,7 @@ WITH due AS (UPDATE agent_task_queueSET status = 'queued'WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type PromoteDueDeferredTasksForRuntimeParams struct {@@ -7816,6 +7870,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -7861,7 +7916,7 @@ WITH due AS (UPDATE agent_task_queueSET status = 'queued'WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type PromoteDueDeferredTasksForRuntimesParams struct {@@ -7942,6 +7997,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -8111,7 +8167,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type ReclaimStaleDispatchedTaskForRuntimeParams struct {@@ -8195,6 +8251,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -8239,7 +8296,7 @@ UPDATE agent_task_queueSET dispatched_at = now(),prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)WHERE id IN (SELECT id FROM candidates)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type ReclaimStaleDispatchedTasksForRuntimesParams struct {@@ -8335,6 +8392,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -8355,7 +8413,7 @@ SET status = 'failed',wait_reason = NULL,prepare_lease_expires_at = NULLWHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Called by the daemon at startup. Atomically fails any dispatched/running/@@ -8434,6 +8492,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -8597,7 +8656,7 @@ WHERE task.id = $1AND task.started_at IS NULLAND task.dispatched_at = $3AND lock_task_owner_rows(task.agent_id, task.issue_id, COALESCE(enqueue_agent.runtime_id, task.runtime_id))-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`type RequeueAgentTaskAfterClaimFailureParams struct {@@ -8677,6 +8736,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 5555ed6a7a..cd566aade3 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -315,7 +315,7 @@ SELECT$10,COALESCE($11::uuid, gen_random_uuid())FROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateAutopilotTaskParams struct {@@ -429,6 +429,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1000,7 +1001,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD}const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queueWHERE autopilot_run_id = $1ORDER BY created_atLIMIT 1@@ -1072,6 +1073,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex b33abc5468..2055595c82 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -406,7 +406,7 @@ SELECTCOALESCE($15::uuid, gen_random_uuid()),$16::jsonbFROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateChatTaskParams struct {@@ -518,6 +518,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -599,7 +600,7 @@ FROM (WHERE task.id = $1AND pending.max_until IS NOT NULLAND (task.fire_at IS NULL OR task.fire_at < pending.max_until)-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`// Closes the enqueue-vs-append race: under READ COMMITTED a media message can@@ -672,6 +673,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -3066,7 +3068,7 @@ WHERE task.chat_session_id = $1AND message.role = 'user'AND message.channel_media_pending_until > now())-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`// Media completion may race with the 3s run batcher. Promote every original@@ -3145,6 +3147,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -3577,7 +3580,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :oneUPDATE agent_task_queueSET chat_input_task_id = idWHERE id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`// Stamps a freshly-created direct-chat task as the owner of its own input batch@@ -3651,6 +3654,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/generated/chat_supplement.sql.go b/server/pkg/db/generated/chat_supplement.sql.goindex 37423e146f..5bf3f10072 100644--- a/server/pkg/db/generated/chat_supplement.sql.go+++ b/server/pkg/db/generated/chat_supplement.sql.go@@ -170,7 +170,7 @@ func (q *Queries) ListChatGuidanceInProviderSession(ctx context.Context, arg Lis}const lockRunningChatTaskForSupplement = `-- name: LockRunningChatTaskForSupplement :one-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step FROM agent_task_queue t+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id FROM agent_task_queue tJOIN task_supplement_capability cap ON cap.task_id = t.idWHERE t.chat_session_id = $1 AND t.status = 'running'AND t.regenerate_quick_actions_for IS NULL@@ -245,6 +245,7 @@ func (q *Queries) LockRunningChatTaskForSupplement(ctx context.Context, chatSess&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex dce415a920..693803774c 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -193,6 +193,8 @@ type AgentTaskQueue struct {CancelledByName pgtype.Text `json:"cancelled_by_name"`IssueSnapshot []byte `json:"issue_snapshot"`WorkflowStep pgtype.Text `json:"workflow_step"`+ // Squad UUID for usage attribution and unified execution avatar grouping. Separate from squad_id (which carries leader/worker routing authority). NULL for standalone non-squad runs.+ UsageSquadID pgtype.UUID `json:"usage_squad_id"`}type AgentToLabel struct {@@ -2094,6 +2096,8 @@ type TaskUsageHourly struct {UncostedOutputTokens pgtype.Int8 `json:"uncosted_output_tokens"`UncostedCacheReadTokens pgtype.Int8 `json:"uncosted_cache_read_tokens"`UncostedCacheWriteTokens pgtype.Int8 `json:"uncosted_cache_write_tokens"`+ // Triggering squad UUID (from COALESCE(agent_task_queue.usage_squad_id, agent_task_queue.squad_id)). NULL for standalone non-squad runs and legacy pre-backfill buckets.+ SquadID pgtype.UUID `json:"squad_id"`}type TaskUsageHourlyDirty struct {@@ -2105,6 +2109,7 @@ type TaskUsageHourlyDirty struct {Provider string `json:"provider"`Model string `json:"model"`EnqueuedAt pgtype.Timestamptz `json:"enqueued_at"`+ SquadID pgtype.UUID `json:"squad_id"`}type TaskUsageHourlyRollupState struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex fd58db20da..aafe18c7bf 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -17,7 +17,7 @@ SET status = 'cancelled', completed_at = now(),cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULLWHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CancelAgentTasksByRuntimeOrAgentParams struct {@@ -117,6 +117,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -142,7 +143,7 @@ WHERE task.agent_id = agent.idAND agent.owner_id IS DISTINCT FROM $3AND NOT COALESCE(agent.owner_id = ANY($4::uuid[]), false)AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`type CancelNonOwnerTasksByRuntimeParams struct {@@ -232,6 +233,7 @@ func (q *Queries) CancelNonOwnerTasksByRuntime(ctx context.Context, arg CancelNo&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -353,7 +355,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',FROM victimsWHERE task.id = victims.idAND task.status IN ('dispatched', 'running', 'waiting_local_directory')-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`type FailTasksForOfflineRuntimesParams struct {@@ -439,6 +441,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -949,7 +952,7 @@ func (q *Queries) ListDaemonCustomNames(ctx context.Context, arg ListDaemonCusto}const listNonOwnerActiveTasksByRuntime = `-- name: ListNonOwnerActiveTasksByRuntime :many-SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_idFROM agent_task_queue AS taskJOIN agent ON agent.id = task.agent_idWHERE task.runtime_id = $1@@ -1037,6 +1040,7 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntime(ctx context.Context, arg List&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -1049,7 +1053,7 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntime(ctx context.Context, arg List}const listNonOwnerActiveTasksByRuntimeForUpdate = `-- name: ListNonOwnerActiveTasksByRuntimeForUpdate :many-SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_idFROM agent_task_queue AS taskJOIN agent ON agent.id = task.agent_idWHERE task.runtime_id = $1@@ -1138,6 +1142,7 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntimeForUpdate(ctx context.Context,&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.goindex a618a909b8..9bc1ed89d5 100644--- a/server/pkg/db/generated/supplement.sql.go+++ b/server/pkg/db/generated/supplement.sql.go@@ -880,7 +880,7 @@ WHERE t.id = candidate.id-- Reference the data-modifying CTE explicitly: capability persistence and-- the returned running row are one indivisible statement.AND (SELECT count(*) FROM capability) >= 0-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id`type StartAgentTaskWithSupplementParams struct {@@ -956,6 +956,7 @@ func (q *Queries) StartAgentTaskWithSupplement(ctx context.Context, arg StartAge&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/generated/task_cleanup.sql.go b/server/pkg/db/generated/task_cleanup.sql.goindex dc7524dc50..f5ce156e28 100644--- a/server/pkg/db/generated/task_cleanup.sql.go+++ b/server/pkg/db/generated/task_cleanup.sql.go@@ -31,7 +31,7 @@ SET status = 'failed',completed_at = now(),chat_finalize_deferred_at = NULLWHERE id = $2 AND status = 'cancelled'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type FailCancelledTaskProcessCleanupParams struct {@@ -106,6 +106,7 @@ func (q *Queries) FailCancelledTaskProcessCleanup(ctx context.Context, arg FailC&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -121,7 +122,7 @@ WHERE task.id = ANY($1::uuid[])AND (task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'OR EXISTS (SELECT 1 FROM agent_runtime runtimeWHERE runtime.id = task.runtime_id AND runtime.provider = 'museapp'))-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id`// Run inside the bulk terminal-write transaction, before its rows reach the@@ -198,6 +199,7 @@ func (q *Queries) MarkMuseAppRecoveryCleanupUnconfirmed(ctx context.Context, tas&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex c97e898961..96b6f1ddfd 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -219,6 +219,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= $2::timestamptzAND ($3::uuid IS NULL OR i.project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($4::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $5::uuid)+ )GROUP BY atq.agent_idORDER BY total_seconds DESC`@@ -227,6 +232,8 @@ type ListDashboardAgentRunTimeParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardAgentRunTimeRow struct {@@ -255,7 +262,13 @@ type ListDashboardAgentRunTimeRow struct {// charts the client trims to the same span; passed straight through without// re-truncation.func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboardAgentRunTimeParams) ([]ListDashboardAgentRunTimeRow, error) {- rows, err := q.db.Query(ctx, listDashboardAgentRunTime, arg.WorkspaceID, arg.Since, arg.ProjectID)+ rows, err := q.db.Query(ctx, listDashboardAgentRunTime,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )if err != nil {return nil, err}@@ -298,6 +311,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= $2::timestamptzAND ($3::uuid IS NULL OR i.project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($4::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $5::uuid)+ )GROUP BY atq.agent_id, 2ORDER BY atq.agent_id, 2`@@ -306,6 +324,8 @@ type ListDashboardFailuresByAgentParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardFailuresByAgentRow struct {@@ -322,7 +342,13 @@ type ListDashboardFailuresByAgentRow struct {// No date bucketing, so no @tz — @since is the viewer's local// start-of-day-(N) so the window lines up with the per-agent run-time card.func (q *Queries) ListDashboardFailuresByAgent(ctx context.Context, arg ListDashboardFailuresByAgentParams) ([]ListDashboardFailuresByAgentRow, error) {- rows, err := q.db.Query(ctx, listDashboardFailuresByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)+ rows, err := q.db.Query(ctx, listDashboardFailuresByAgent,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )if err != nil {return nil, err}@@ -341,6 +367,81 @@ func (q *Queries) ListDashboardFailuresByAgent(ctx context.Context, arg ListDashreturn items, nil}+const listDashboardFailuresBySquad = `-- name: ListDashboardFailuresBySquad :many+SELECT+ COALESCE(atq.usage_squad_id, atq.squad_id)::uuid AS squad_id,+ atq.agent_id,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= $2::timestamptz+ AND ($3::uuid IS NULL OR i.project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($4::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $5::uuid)+ )+GROUP BY COALESCE(atq.usage_squad_id, atq.squad_id), atq.agent_id, 3+ORDER BY 1 NULLS LAST, atq.agent_id, 3+`++type ListDashboardFailuresBySquadParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Since pgtype.Timestamptz `json:"since"`+ ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`+}++type ListDashboardFailuresBySquadRow struct {+ SquadID pgtype.UUID `json:"squad_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// Per-(squad, agent, failure_reason) terminal-task counts for the Errors tab's+// Squad breakdown. squad_id IS NULL represents standalone agent runs.+func (q *Queries) ListDashboardFailuresBySquad(ctx context.Context, arg ListDashboardFailuresBySquadParams) ([]ListDashboardFailuresBySquadRow, error) {+ rows, err := q.db.Query(ctx, listDashboardFailuresBySquad,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDashboardFailuresBySquadRow{}+ for rows.Next() {+ var i ListDashboardFailuresBySquadRow+ if err := rows.Scan(+ &i.SquadID,+ &i.AgentID,+ &i.FailureReason,+ &i.TaskCount,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listDashboardFailuresDaily = `-- name: ListDashboardFailuresDaily :manySELECTDATE(atq.completed_at AT TIME ZONE $2::text) AS date,@@ -358,6 +459,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= $3::timestamptzAND ($4::uuid IS NULL OR i.project_id = $4)+ AND (+ $5::text = ''+ OR ($5::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($5::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $6::uuid)+ )GROUP BY 1, 2ORDER BY 1 DESC, 2`@@ -367,6 +473,8 @@ type ListDashboardFailuresDailyParams struct {Tz string `json:"tz"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardFailuresDailyRow struct {@@ -402,6 +510,8 @@ func (q *Queries) ListDashboardFailuresDaily(ctx context.Context, arg ListDashboarg.Tz,arg.Since,arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,)if err != nil {return nil, err@@ -440,6 +550,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= $3::timestamptzAND ($4::uuid IS NULL OR i.project_id = $4)+ AND (+ $5::text = ''+ OR ($5::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($5::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $6::uuid)+ )GROUP BY DATE(atq.completed_at AT TIME ZONE $2::text)ORDER BY DATE(atq.completed_at AT TIME ZONE $2::text) DESC`@@ -449,6 +564,8 @@ type ListDashboardRunTimeDailyParams struct {Tz string `json:"tz"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardRunTimeDailyRow struct {@@ -485,6 +602,8 @@ func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboaarg.Tz,arg.Since,arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,)if err != nil {return nil, err@@ -510,6 +629,92 @@ func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboareturn items, nil}+const listDashboardSquadRunTime = `-- name: ListDashboardSquadRunTime :many+SELECT+ COALESCE(atq.usage_squad_id, atq.squad_id)::uuid AS squad_id,+ atq.agent_id,+ COALESCE(+ SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,+ 0+ )::bigint AS total_seconds,+ COUNT(*)::int AS task_count,+ COUNT(*) FILTER (WHERE EXISTS (+ SELECT 1 FROM task_usage tu WHERE tu.task_id = atq.id+ ))::int AS metered_task_count,+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed', 'cancelled')+ AND atq.started_at IS NOT NULL+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= $2::timestamptz+ AND ($3::uuid IS NULL OR i.project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR ($4::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = $5::uuid)+ )+GROUP BY COALESCE(atq.usage_squad_id, atq.squad_id), atq.agent_id+ORDER BY total_seconds DESC+`++type ListDashboardSquadRunTimeParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Since pgtype.Timestamptz `json:"since"`+ ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`+}++type ListDashboardSquadRunTimeRow struct {+ SquadID pgtype.UUID `json:"squad_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ TotalSeconds int64 `json:"total_seconds"`+ TaskCount int32 `json:"task_count"`+ MeteredTaskCount int32 `json:"metered_task_count"`+ FailedCount int32 `json:"failed_count"`+ CancelledCount int32 `json:"cancelled_count"`+}++// Per-(squad, agent) terminal-task run time and task counts for the workspace.+// squad_id IS NULL represents standalone (non-squad-triggered) agent runs.+func (q *Queries) ListDashboardSquadRunTime(ctx context.Context, arg ListDashboardSquadRunTimeParams) ([]ListDashboardSquadRunTimeRow, error) {+ rows, err := q.db.Query(ctx, listDashboardSquadRunTime,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDashboardSquadRunTimeRow{}+ for rows.Next() {+ var i ListDashboardSquadRunTimeRow+ if err := rows.Scan(+ &i.SquadID,+ &i.AgentID,+ &i.TotalSeconds,+ &i.TaskCount,+ &i.MeteredTaskCount,+ &i.FailedCount,+ &i.CancelledCount,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listDashboardUsageByAgent = `-- name: ListDashboardUsageByAgent :manySELECTagent_id,@@ -529,6 +734,11 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= $2::timestamptzAND ($3::uuid IS NULL OR project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND squad_id IS NULL)+ OR ($4::text = 'squad' AND squad_id = $5::uuid)+ )GROUP BY agent_id, LOWER(provider), modelORDER BY agent_id, LOWER(provider), model`@@ -537,6 +747,8 @@ type ListDashboardUsageByAgentParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardUsageByAgentRow struct {@@ -570,7 +782,13 @@ type ListDashboardUsageByAgentRow struct {// provider is LOWER()-normalized so mixed-case historical rows merge with// new rows (see ListDashboardUsageDaily).func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboardUsageByAgentParams) ([]ListDashboardUsageByAgentRow, error) {- rows, err := q.db.Query(ctx, listDashboardUsageByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)+ rows, err := q.db.Query(ctx, listDashboardUsageByAgent,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )if err != nil {return nil, err}@@ -603,6 +821,105 @@ func (q *Queries) ListDashboardUsageByAgent(ctx context.Context, arg ListDashboareturn items, nil}+const listDashboardUsageBySquad = `-- name: ListDashboardUsageBySquad :many+SELECT+ squad_id,+ agent_id,+ LOWER(provider) AS provider,+ model,+ SUM(input_tokens)::bigint AS input_tokens,+ SUM(output_tokens)::bigint AS output_tokens,+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,+ SUM(cache_write_tokens)::bigint AS cache_write_tokens,+ SUM(cost_usd_ticks)::bigint AS cost_usd_ticks,+ SUM(COALESCE(uncosted_input_tokens, input_tokens))::bigint AS uncosted_input_tokens,+ SUM(COALESCE(uncosted_output_tokens, output_tokens))::bigint AS uncosted_output_tokens,+ SUM(COALESCE(uncosted_cache_read_tokens, cache_read_tokens))::bigint AS uncosted_cache_read_tokens,+ SUM(COALESCE(uncosted_cache_write_tokens, cache_write_tokens))::bigint AS uncosted_cache_write_tokens,+ SUM(task_count)::int AS task_count+FROM task_usage_hourly+WHERE workspace_id = $1+ AND bucket_hour >= $2::timestamptz+ AND ($3::uuid IS NULL OR project_id = $3)+ AND (+ $4::text = ''+ OR ($4::text = 'standalone' AND squad_id IS NULL)+ OR ($4::text = 'squad' AND squad_id = $5::uuid)+ )+GROUP BY squad_id, agent_id, LOWER(provider), model+ORDER BY squad_id NULLS LAST, agent_id, LOWER(provider), model+`++type ListDashboardUsageBySquadParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Since pgtype.Timestamptz `json:"since"`+ ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`+}++type ListDashboardUsageBySquadRow struct {+ SquadID pgtype.UUID `json:"squad_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUsdTicks int64 `json:"cost_usd_ticks"`+ UncostedInputTokens int64 `json:"uncosted_input_tokens"`+ UncostedOutputTokens int64 `json:"uncosted_output_tokens"`+ UncostedCacheReadTokens int64 `json:"uncosted_cache_read_tokens"`+ UncostedCacheWriteTokens int64 `json:"uncosted_cache_write_tokens"`+ TaskCount int32 `json:"task_count"`+}++// Per-(squad, agent, provider, model) token aggregates from `task_usage_hourly`.+// Preserves agent_id so the UI can render both squad-overall totals and inline+// member breakdowns from one payload, while keeping provider+model for pricing.+// squad_id IS NULL represents standalone (non-squad-triggered) agent runs.+func (q *Queries) ListDashboardUsageBySquad(ctx context.Context, arg ListDashboardUsageBySquadParams) ([]ListDashboardUsageBySquadRow, error) {+ rows, err := q.db.Query(ctx, listDashboardUsageBySquad,+ arg.WorkspaceID,+ arg.Since,+ arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDashboardUsageBySquadRow{}+ for rows.Next() {+ var i ListDashboardUsageBySquadRow+ if err := rows.Scan(+ &i.SquadID,+ &i.AgentID,+ &i.Provider,+ &i.Model,+ &i.InputTokens,+ &i.OutputTokens,+ &i.CacheReadTokens,+ &i.CacheWriteTokens,+ &i.CostUsdTicks,+ &i.UncostedInputTokens,+ &i.UncostedOutputTokens,+ &i.UncostedCacheReadTokens,+ &i.UncostedCacheWriteTokens,+ &i.TaskCount,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listDashboardUsageDaily = `-- name: ListDashboardUsageDaily :manySELECTDATE(bucket_hour AT TIME ZONE $2::text) AS date,@@ -622,6 +939,11 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= $3::timestamptzAND ($4::uuid IS NULL OR project_id = $4)+ AND (+ $5::text = ''+ OR ($5::text = 'standalone' AND squad_id IS NULL)+ OR ($5::text = 'squad' AND squad_id = $6::uuid)+ )GROUP BY DATE(bucket_hour AT TIME ZONE $2::text), LOWER(provider), modelORDER BY DATE(bucket_hour AT TIME ZONE $2::text) DESC, LOWER(provider), model`@@ -631,6 +953,8 @@ type ListDashboardUsageDailyParams struct {Tz string `json:"tz"`Since pgtype.Timestamptz `json:"since"`ProjectID pgtype.UUID `json:"project_id"`+ SquadScope string `json:"squad_scope"`+ SquadID pgtype.UUID `json:"squad_id"`}type ListDashboardUsageDailyRow struct {@@ -672,6 +996,8 @@ func (q *Queries) ListDashboardUsageDaily(ctx context.Context, arg ListDashboardarg.Tz,arg.Since,arg.ProjectID,+ arg.SquadScope,+ arg.SquadID,)if err != nil {return nil, errdiff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.goindex 0edc957d96..69cbfa401a 100644--- a/server/pkg/db/generated/wakeup.sql.go+++ b/server/pkg/db/generated/wakeup.sql.go@@ -37,7 +37,7 @@ func (q *Queries) AdvanceIssueWakeup(ctx context.Context, arg AdvanceIssueWakeupconst cancelUnstartedIssueWakeupTasks = `-- name: CancelUnstartedIssueWakeupTasks :manyUPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'-WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID pgtype.UUID) ([]AgentTaskQueue, error) {@@ -110,6 +110,7 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID p&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -123,7 +124,7 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID pconst cancelUnstartedWakeupTasks = `-- name: CancelUnstartedWakeupTasks :manyUPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Wakeup disabled or updated'-WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID string) ([]AgentTaskQueue, error) {@@ -196,6 +197,7 @@ func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID strin&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,); err != nil {return nil, err}@@ -371,16 +373,16 @@ func (q *Queries) CreateIssueWakeup(ctx context.Context, arg CreateIssueWakeupPaconst createWakeupTask = `-- name: CreateWakeupTask :oneWITH enqueue_agent AS MATERIALIZED (- SELECT a.id, COALESCE(a.runtime_id, $24::uuid) AS runtime_id+ SELECT a.id, COALESCE(a.runtime_id, $25::uuid) AS runtime_idFROM agent aWHERE a.id = $1- AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $24::uuid))+ AND lock_task_owner_rows(a.id, $2, COALESCE(a.runtime_id, $25::uuid))FOR KEY SHARE OF a)INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,workflow_step, id)@@ -392,12 +394,12 @@ SELECTCOALESCE($8::boolean, FALSE),$9,$10,+ $11,CASE- WHEN COALESCE($11::text, '') <> ''- THEN jsonb_build_object('head_sha', $11::text)+ WHEN COALESCE($12::text, '') <> ''+ THEN jsonb_build_object('head_sha', $12::text)ELSE '{}'::jsonb- END || $12::jsonb,- $13,+ END || $13::jsonb,$14,$15,$16,@@ -407,17 +409,18 @@ SELECT$20,$21,$22,+ $23,-- The workflow step this run works on (MUL-7420). A wakeup continues the-- run that registered it, so it keeps that run's step: a status change it-- makes after someone else moved the issue is refused like the run's own-- would be. A wakeup a member registered starts from the issue's status.COALESCE(- (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = $18 AND s.issue_id = $2),+ (SELECT s.workflow_step FROM agent_task_queue s WHERE s.id = $19 AND s.issue_id = $2),(SELECT i.status FROM issue i WHERE i.id = $2)),- COALESCE($23::uuid, gen_random_uuid())+ COALESCE($24::uuid, gen_random_uuid())FROM enqueue_agent-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type CreateWakeupTaskParams struct {@@ -431,6 +434,7 @@ type CreateWakeupTaskParams struct {IsLeaderTask pgtype.Bool `json:"is_leader_task"`HandoffNote pgtype.Text `json:"handoff_note"`SquadID pgtype.UUID `json:"squad_id"`+ UsageSquadID pgtype.UUID `json:"usage_squad_id"`HeadSha pgtype.Text `json:"head_sha"`WakeupContext []byte `json:"wakeup_context"`OriginatorUserID pgtype.UUID `json:"originator_user_id"`@@ -477,6 +481,7 @@ func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskParaarg.IsLeaderTask,arg.HandoffNote,arg.SquadID,+ arg.UsageSquadID,arg.HeadSha,arg.WakeupContext,arg.OriginatorUserID,@@ -554,6 +559,7 @@ func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskPara&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -623,7 +629,7 @@ func (q *Queries) DiscardWakeupReceipts(ctx context.Context, id pgtype.UUID) err}const findPendingWakeupTask = `-- name: FindPendingWakeupTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE`func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (AgentTaskQueue, error) {@@ -690,6 +696,7 @@ func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (A&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1562,7 +1569,7 @@ func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, e}const lockWakeupSourceTask = `-- name: LockWakeupSourceTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT`type LockWakeupSourceTaskParams struct {@@ -1634,6 +1641,7 @@ func (q *Queries) LockWakeupSourceTask(ctx context.Context, arg LockWakeupSource&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1783,7 +1791,7 @@ func (q *Queries) ReleaseWakeupReceipts(ctx context.Context, ids []pgtype.UUID)}const replaceWakeupEvidence = `-- name: ReplaceWakeupEvidence :one-UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type ReplaceWakeupEvidenceParams struct {@@ -1856,6 +1864,7 @@ func (q *Queries) ReplaceWakeupEvidence(ctx context.Context, arg ReplaceWakeupEv&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}@@ -1878,7 +1887,7 @@ func (q *Queries) ReserveWakeupReceipts(ctx context.Context, arg ReserveWakeupReconst setClaimedTaskContext = `-- name: SetClaimedTaskContext :oneUPDATE agent_task_queue SET context= $1::jsonb-WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step+WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id`type SetClaimedTaskContextParams struct {@@ -1952,6 +1961,7 @@ func (q *Queries) SetClaimedTaskContext(ctx context.Context, arg SetClaimedTaskC&i.CancelledByName,&i.IssueSnapshot,&i.WorkflowStep,+ &i.UsageSquadID,)return i, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex d68f13f926..873fd8699d 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -360,7 +360,7 @@ WITH enqueue_agent AS MATERIALIZED (INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,workflow_step, fire_at, id)@@ -374,6 +374,7 @@ SELECTCOALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),sqlc.narg(handoff_note),sqlc.narg(squad_id),+ sqlc.narg(usage_squad_id),NULLIF(CASEWHEN COALESCE(sqlc.narg('head_sha')::text, '') <> ''THEN jsonb_build_object('head_sha', sqlc.narg('head_sha')::text)@@ -422,7 +423,7 @@ WITH enqueue_agent AS MATERIALIZED (INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,trigger_evidence_kind, trigger_evidence_ref_id, fire_at,workflow_step, id@@ -435,6 +436,7 @@ SELECTCOALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),sqlc.narg(handoff_note),sqlc.narg(squad_id),+ sqlc.narg(usage_squad_id),jsonb_strip_nulls(jsonb_build_object('head_sha', NULLIF(COALESCE(sqlc.narg('head_sha')::text, ''), ''),'channel_issue_media_pending', TRUE@@ -496,13 +498,14 @@ WITH enqueue_agent AS MATERIALIZED (FOR KEY SHARE OF a)INSERT INTO agent_task_queue (- agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,+ agent_id, runtime_id, issue_id, status, priority, context, usage_squad_id, originator_user_id,accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, trigger_evidence_kind, trigger_evidence_ref_id,id)SELECTsqlc.arg(agent_id), enqueue_agent.runtime_id, NULL, 'queued', sqlc.arg(priority), sqlc.narg(context),+ sqlc.narg(usage_squad_id),sqlc.narg(originator_user_id),sqlc.narg(accountable_user_id),sqlc.narg(runtime_mcp_overlay),@@ -560,7 +563,7 @@ INSERT INTO agent_task_queue (status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,session_id, work_dir,attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,- squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id,trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,chat_input_task_id, fire_at,@@ -579,6 +582,7 @@ SELECTp.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',p.is_leader_task,p.squad_id,+ p.usage_squad_id,p.originator_user_id,p.accountable_user_id,sqlc.narg(runtime_mcp_overlay),@@ -621,14 +625,14 @@ UPDATE agent_task_queue SET workflow_step = @workflow_step WHERE id = @id;-- CreateRetryTask, the run is stamped with the agent's current runtime (#10717).INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context,- force_fresh_session, is_leader_task, squad_id,+ force_fresh_session, is_leader_task, squad_id, usage_squad_id,originator_user_id, accountable_user_id,runtime_mcp_overlay, runtime_connected_apps,originator_source, rerun_of_task_id, id)SELECTp.agent_id, COALESCE(a.runtime_id, p.runtime_id), 'queued', p.priority, p.context,- TRUE, p.is_leader_task, p.squad_id,+ TRUE, p.is_leader_task, p.squad_id, p.usage_squad_id,sqlc.arg(actor_user_id), sqlc.arg(actor_user_id),sqlc.narg(runtime_mcp_overlay), sqlc.narg(runtime_connected_apps),'direct_human', p.id, sqlc.arg(new_task_id)diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 636ec8067c..ff995b6483 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -157,6 +157,11 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= sqlc.arg('since')::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND squad_id IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND squad_id = sqlc.narg('squad_id')::uuid)+ )GROUP BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text), LOWER(provider), modelORDER BY DATE(bucket_hour AT TIME ZONE sqlc.arg('tz')::text) DESC, LOWER(provider), model;@@ -193,9 +198,46 @@ FROM task_usage_hourlyWHERE workspace_id = $1AND bucket_hour >= @since::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND squad_id IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND squad_id = sqlc.narg('squad_id')::uuid)+ )GROUP BY agent_id, LOWER(provider), modelORDER BY agent_id, LOWER(provider), model;+-- name: ListDashboardUsageBySquad :many+-- Per-(squad, agent, provider, model) token aggregates from `task_usage_hourly`.+-- Preserves agent_id so the UI can render both squad-overall totals and inline+-- member breakdowns from one payload, while keeping provider+model for pricing.+-- squad_id IS NULL represents standalone (non-squad-triggered) agent runs.+SELECT+ squad_id,+ agent_id,+ LOWER(provider) AS provider,+ model,+ SUM(input_tokens)::bigint AS input_tokens,+ SUM(output_tokens)::bigint AS output_tokens,+ SUM(cache_read_tokens)::bigint AS cache_read_tokens,+ SUM(cache_write_tokens)::bigint AS cache_write_tokens,+ SUM(cost_usd_ticks)::bigint AS cost_usd_ticks,+ SUM(COALESCE(uncosted_input_tokens, input_tokens))::bigint AS uncosted_input_tokens,+ SUM(COALESCE(uncosted_output_tokens, output_tokens))::bigint AS uncosted_output_tokens,+ SUM(COALESCE(uncosted_cache_read_tokens, cache_read_tokens))::bigint AS uncosted_cache_read_tokens,+ SUM(COALESCE(uncosted_cache_write_tokens, cache_write_tokens))::bigint AS uncosted_cache_write_tokens,+ SUM(task_count)::int AS task_count+FROM task_usage_hourly+WHERE workspace_id = $1+ AND bucket_hour >= @since::timestamptz+ AND (sqlc.narg('project_id')::uuid IS NULL OR project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND squad_id IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND squad_id = sqlc.narg('squad_id')::uuid)+ )+GROUP BY squad_id, agent_id, LOWER(provider), model+ORDER BY squad_id NULLS LAST, agent_id, LOWER(provider), model;+-- name: ListDashboardRunTimeDaily :many-- Daily per-date run time + task counts for the workspace, optionally-- scoped to a single project. Powers the workspace dashboard's "Time"@@ -235,6 +277,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= sqlc.arg('since')::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )GROUP BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text)ORDER BY DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) DESC;@@ -276,9 +323,47 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= @since::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )GROUP BY atq.agent_idORDER BY total_seconds DESC;+-- name: ListDashboardSquadRunTime :many+-- Per-(squad, agent) terminal-task run time and task counts for the workspace.+-- squad_id IS NULL represents standalone (non-squad-triggered) agent runs.+SELECT+ COALESCE(atq.usage_squad_id, atq.squad_id)::uuid AS squad_id,+ atq.agent_id,+ COALESCE(+ SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,+ 0+ )::bigint AS total_seconds,+ COUNT(*)::int AS task_count,+ COUNT(*) FILTER (WHERE EXISTS (+ SELECT 1 FROM task_usage tu WHERE tu.task_id = atq.id+ ))::int AS metered_task_count,+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed', 'cancelled')+ AND atq.started_at IS NOT NULL+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= @since::timestamptz+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )+GROUP BY COALESCE(atq.usage_squad_id, atq.squad_id), atq.agent_id+ORDER BY total_seconds DESC;+-- name: ListDashboardFailuresDaily :many-- Daily per-(date, failure_reason) terminal-task counts for the workspace,-- optionally scoped to a single project. Powers the workspace dashboard's@@ -317,6 +402,11 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= sqlc.arg('since')::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )GROUP BY 1, 2ORDER BY 1 DESC, 2;@@ -344,5 +434,38 @@ WHERE a.workspace_id = $1AND atq.completed_at IS NOT NULLAND atq.completed_at >= @since::timestamptzAND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )GROUP BY atq.agent_id, 2ORDER BY atq.agent_id, 2;++-- name: ListDashboardFailuresBySquad :many+-- Per-(squad, agent, failure_reason) terminal-task counts for the Errors tab's+-- Squad breakdown. squad_id IS NULL represents standalone agent runs.+SELECT+ COALESCE(atq.usage_squad_id, atq.squad_id)::uuid AS squad_id,+ atq.agent_id,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= @since::timestamptz+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+ AND (+ sqlc.arg('squad_scope')::text = ''+ OR (sqlc.arg('squad_scope')::text = 'standalone' AND COALESCE(atq.usage_squad_id, atq.squad_id) IS NULL)+ OR (sqlc.arg('squad_scope')::text = 'squad' AND COALESCE(atq.usage_squad_id, atq.squad_id) = sqlc.narg('squad_id')::uuid)+ )+GROUP BY COALESCE(atq.usage_squad_id, atq.squad_id), atq.agent_id, 3+ORDER BY 1 NULLS LAST, atq.agent_id, 3;diff --git a/server/pkg/db/queries/wakeup.sql b/server/pkg/db/queries/wakeup.sqlindex d5d1cd7d6b..cdc7578a63 100644--- a/server/pkg/db/queries/wakeup.sql+++ b/server/pkg/db/queries/wakeup.sql@@ -184,7 +184,7 @@ WITH enqueue_agent AS MATERIALIZED (INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,- squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ squad_id, usage_squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id, trigger_evidence_kind, trigger_evidence_ref_id,workflow_step, id)@@ -196,6 +196,7 @@ SELECTCOALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),sqlc.narg(handoff_note),sqlc.narg(squad_id),+ sqlc.narg(usage_squad_id),CASEWHEN COALESCE(sqlc.narg('head_sha')::text, '') <> ''THEN jsonb_build_object('head_sha', sqlc.narg('head_sha')::text)