Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(attribution): Human Attribution Phase 1 (MUL-4302) (#5150)

Bohan Jiang4fac8d772ff5
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 3fa1410808..787259b11e 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -724,6 +724,55 @@ describe("ApiClient", () => {
});
});
+ it("parses task attribution when the backend enriches it", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({
+ ...taskResponse,
+ attribution: {
+ source: "direct_human",
+ precise: true,
+ initiator: { id: "user-1", name: "Ada", avatar_url: "https://x/a.png" },
+ originator: { id: "user-1", name: "Ada" },
+ evidence: { kind: "comment", ref_id: "comment-1" },
+ },
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ const result = await client.cancelTaskById("task-1");
+
+ expect(result.attribution).toEqual({
+ source: "direct_human",
+ precise: true,
+ initiator: { id: "user-1", name: "Ada", avatar_url: "https://x/a.png" },
+ originator: { id: "user-1", name: "Ada" },
+ evidence: { kind: "comment", ref_id: "comment-1" },
+ });
+ });
+
+ it("leaves attribution absent on servers that predate it", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(taskResponse), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ const result = await client.cancelTaskById("task-1");
+
+ expect(result.attribution).toBeUndefined();
+ });
+
// The server only defers the empty-transcript judgment — and so only
// withholds the synchronous restore — for clients that advertise this
// capability (#5219). Drop the header and this client is treated as a
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 389c71bedb..7c962b6fc5 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -193,6 +193,8 @@ import {
GroupedIssuesResponseSchema,
ListAutopilotsResponseSchema,
EMPTY_LIST_AUTOPILOTS_RESPONSE,
+ AutopilotRunSchema,
+ FALLBACK_AUTOPILOT_RUN,
ListIssuesResponseSchema,
ListWebhookDeliveriesResponseSchema,
RuntimeHourlyActivityListSchema,
@@ -280,6 +282,20 @@ export class ApiError extends Error {
}
}
+// dispatchReasonCode extracts the stable, machine-readable admission reason
+// (MUL-4525) from a blocked-trigger error's structured body, when present. UI
+// callers localize a blocked/partial trigger from this code instead of pattern
+// matching the human-readable message. Returns undefined for non-ApiErrors or
+// bodies without a reason_code (older servers), so callers fall back to their
+// generic failure toast.
+export function dispatchReasonCode(err: unknown): string | undefined {
+ if (err instanceof ApiError && err.body && typeof err.body === "object") {
+ const code = (err.body as { reason_code?: unknown }).reason_code;
+ if (typeof code === "string" && code.length > 0) return code;
+ }
+ return undefined;
+}
+
// Thrown by getAttachmentTextContent when the server refuses to inline a
// file because it exceeds the 2 MB cap. UI maps to a "too large, please
// download" affordance with the Download CTA still available.
@@ -2332,7 +2348,13 @@ export class ApiClient {
}
async triggerAutopilot(id: string): Promise<AutopilotRun> {
- return this.fetch(`/api/autopilots/${id}/trigger`, { method: "POST" });
+ // Manual "run now" returns 200 even when admission blocks the run (status
+ // skipped/failed). The UI branches on status/reason_code to avoid a
+ // false-success toast (MUL-4525), so parse defensively rather than casting.
+ const raw = await this.fetch<unknown>(`/api/autopilots/${id}/trigger`, { method: "POST" });
+ return parseWithFallback(raw, AutopilotRunSchema, FALLBACK_AUTOPILOT_RUN, {
+ endpoint: "POST /api/autopilots/:id/trigger",
+ });
}
async listAutopilotRuns(id: string, params?: { limit?: number; offset?: number }): Promise<ListAutopilotRunsResponse> {
diff --git a/packages/core/api/index.ts b/packages/core/api/index.ts
index 49e06bc036..1f3ca87c4c 100644
--- a/packages/core/api/index.ts
+++ b/packages/core/api/index.ts
@@ -1,6 +1,7 @@
export {
ApiClient,
ApiError,
+ dispatchReasonCode,
PreviewTooLargeError,
PreviewUnsupportedError,
} from "./client";
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 92c9874557..d2bb4116b9 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -2,6 +2,9 @@ import { describe, expect, it } from "vitest";
import {
AppConfigSchema,
AgentTaskListSchema,
+ AutopilotRunSchema,
+ FALLBACK_AUTOPILOT_RUN,
+ CommentTriggerPreviewSchema,
DashboardAgentRunTimeListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
@@ -683,3 +686,90 @@ describe("SearchProjectsResponseSchema date drift", () => {
expect(parsed.projects[0]?.due_date).toBeNull();
});
});
+
+// The "run now" flow branches on run.status/reason_code to avoid a false-success
+// toast (MUL-4525), so the trigger response must survive backend drift.
+describe("AutopilotRunSchema", () => {
+ const ENDPOINT = { endpoint: "POST /api/autopilots/:id/trigger" };
+ const baseRun = {
+ id: "run-1",
+ autopilot_id: "ap-1",
+ trigger_id: null,
+ source: "manual",
+ status: "issue_created",
+ issue_id: "issue-1",
+ task_id: null,
+ triggered_at: "2026-07-14T00:00:00Z",
+ completed_at: null,
+ failure_reason: null,
+ trigger_payload: null,
+ result: null,
+ created_at: "2026-07-14T00:00:00Z",
+ };
+
+ it("preserves a blocked run's status and reason_code", () => {
+ const parsed = parseWithFallback(
+ { ...baseRun, status: "skipped", failure_reason: "you are not allowed to trigger this autopilot's assignee agent", reason_code: "invocation_not_allowed" },
+ AutopilotRunSchema,
+ FALLBACK_AUTOPILOT_RUN,
+ ENDPOINT,
+ );
+ expect(parsed.status).toBe("skipped");
+ expect(parsed.reason_code).toBe("invocation_not_allowed");
+ });
+
+ it("tolerates an older server omitting reason_code", () => {
+ const parsed = parseWithFallback(baseRun, AutopilotRunSchema, FALLBACK_AUTOPILOT_RUN, ENDPOINT);
+ expect(parsed.status).toBe("issue_created");
+ expect(parsed.reason_code).toBeUndefined();
+ });
+
+ it("degrades a malformed response to a non-success fallback (never a false success)", () => {
+ const parsed = parseWithFallback("not-an-object", AutopilotRunSchema, FALLBACK_AUTOPILOT_RUN, ENDPOINT);
+ expect(parsed).toBe(FALLBACK_AUTOPILOT_RUN);
+ expect(parsed.status).toBe("failed");
+ });
+});
+
+// The comment composer branches on preview.blocked to warn before sending
+// (MUL-4525 §2), so the additive field must parse and degrade gracefully.
+describe("CommentTriggerPreviewSchema.blocked", () => {
+ it("parses blocked mention outcomes alongside agents", () => {
+ const parsed = CommentTriggerPreviewSchema.parse({
+ agents: [{ id: "a1", source: "mention_agent", reason: "" }],
+ blocked: [
+ { target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
+ ],
+ });
+ expect(parsed.agents).toHaveLength(1);
+ expect(parsed.blocked).toEqual([
+ { target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
+ ]);
+ });
+
+ it("defaults blocked to [] when an older server omits it", () => {
+ const parsed = CommentTriggerPreviewSchema.parse({ agents: [] });
+ expect(parsed.blocked).toEqual([]);
+ });
+
+ it("degrades a malformed blocked field to [] without dropping agents", () => {
+ const parsed = CommentTriggerPreviewSchema.parse({
+ agents: [{ id: "a1", source: "mention_agent", reason: "" }],
+ blocked: "nope",
+ });
+ expect(parsed.agents).toHaveLength(1);
+ expect(parsed.blocked).toEqual([]);
+ });
+
+ it("drops a single malformed blocked entry without discarding the valid ones", () => {
+ const parsed = CommentTriggerPreviewSchema.parse({
+ agents: [],
+ blocked: [
+ { target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
+ { status: "blocked" }, // missing target_id → dropped individually
+ { target_type: "agent", target_id: "a1", status: "blocked", reason_code: "runtime_offline" },
+ ],
+ });
+ expect(parsed.blocked.map((b) => b.target_id)).toEqual(["s1", "a1"]);
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 0a789e9201..f286d2f674 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -5,6 +5,7 @@ import type {
AgentTemplateSummary,
AgentBuilderSession,
Attachment,
+ AutopilotRun,
BillingBalance,
BillingBatchesPage,
BillingCheckoutSessionStatus,
@@ -293,8 +294,31 @@ const CommentTriggerPreviewAgentSchema = z.object({
reason: z.string().default(""),
}).loose();
+// Per-target outcome of an explicit @agent / @squad mention (MUL-4525 §2).
+// target_id is required to correlate with the client's rendered mention; a
+// malformed entry (missing id) is dropped rather than failing the whole payload.
+export const CommentTriggerOutcomeSchema = z.object({
+ target_type: z.string().default(""),
+ target_id: z.string(),
+ status: z.string().default(""),
+ reason_code: z.string().default(""),
+}).loose();
+
export const CommentTriggerPreviewSchema = z.object({
agents: z.array(CommentTriggerPreviewAgentSchema).default([]),
+ // Drop malformed blocked entries INDIVIDUALLY (MUL-4525): a single bad item
+ // must not discard the whole set of valid blocked mentions. A non-array
+ // degrades to []; each valid entry is kept, each malformed one dropped.
+ blocked: z
+ .array(z.unknown())
+ .catch([])
+ .default([])
+ .transform((items) =>
+ items.flatMap((item) => {
+ const parsed = CommentTriggerOutcomeSchema.safeParse(item);
+ return parsed.success ? [parsed.data] : [];
+ }),
+ ),
}).loose();
const IssueTriggerPreviewItemSchema = z.object({
@@ -584,6 +608,34 @@ export const RuntimeUsageByHourListSchema = z.array(RuntimeUsageByHourSchema);
// can drift while task-list consumers still validate the fields they render.
// ---------------------------------------------------------------------------
+// Human attribution (MUL-4302 §9): who an agent run is accountable to, and how
+// that human was resolved. Every field is defensive so a departed member, an
+// autopilot run (no originator), or an older backend degrades to a partial
+// object instead of a parse failure.
+const AttributionUserSchema = z.object({
+ id: z.string().default(""),
+ name: z.string().optional(),
+ email: z.string().optional(),
+ avatar_url: z.string().optional(),
+}).loose();
+
+const TaskEvidenceSchema = z.object({
+ kind: z.string().default(""),
+ ref_id: z.string().default(""),
+}).loose();
+
+const TaskAttributionSchema = z.object({
+ source: z.string().default("unattributed"),
+ precise: z.boolean().default(false),
+ initiator: AttributionUserSchema.optional(),
+ originator: AttributionUserSchema.optional(),
+ evidence: TaskEvidenceSchema.optional(),
+ rule_version_id: z.string().optional(),
+ delegated_from_task_id: z.string().optional(),
+ retry_of_task_id: z.string().optional(),
+ rerun_of_task_id: z.string().optional(),
+}).loose();
+
const OptionalStringArraySchema = z.preprocess(
(value) =>
Array.isArray(value) && value.every((item) => typeof item === "string")
@@ -621,6 +673,7 @@ export const AgentTaskSchema = z.object({
kind: z.string().optional(),
work_dir: z.string().optional(),
relative_work_dir: z.string().optional(),
+ attribution: TaskAttributionSchema.optional(),
}).loose();
export const AgentTaskListSchema = z.array(AgentTaskSchema);
@@ -1020,6 +1073,45 @@ export const EMPTY_LIST_AUTOPILOTS_RESPONSE = {
total: 0,
};
+// Autopilot run (POST /trigger, GET /runs). Consumed by the "run now" flow,
+// which branches on `status` to avoid a false-success toast (MUL-4525), so the
+// response must be schema-parsed. `reason_code` is an additive, stable
+// classification of a non-success run the UI localizes; older servers omit it.
+// Defaults are conservative: an unreadable run degrades to a non-success status
+// so the UI never shows success it cannot confirm. .loose() tolerates new fields.
+export const AutopilotRunSchema = z.object({
+ id: z.string().default(""),
+ autopilot_id: z.string().default(""),
+ trigger_id: z.string().nullable().default(null),
+ source: z.string().default("manual"),
+ status: z.string().default("failed"),
+ issue_id: z.string().nullable().default(null),
+ task_id: z.string().nullable().default(null),
+ triggered_at: z.string().default(""),
+ completed_at: z.string().nullable().default(null),
+ failure_reason: z.string().nullable().default(null),
+ reason_code: z.string().optional(),
+ trigger_payload: z.unknown().default(null),
+ result: z.unknown().default(null),
+ created_at: z.string().default(""),
+}).loose();
+
+export const FALLBACK_AUTOPILOT_RUN: AutopilotRun = {
+ id: "",
+ autopilot_id: "",
+ trigger_id: null,
+ source: "manual",
+ status: "failed",
+ issue_id: null,
+ task_id: null,
+ triggered_at: "",
+ completed_at: null,
+ failure_reason: null,
+ trigger_payload: null,
+ result: null,
+ created_at: "",
+};
+
export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {
id: "",
workspace_id: "",
diff --git a/packages/core/issues/comment-trigger-outcomes.test.ts b/packages/core/issues/comment-trigger-outcomes.test.ts
new file mode 100644
index 0000000000..412224444f
--- /dev/null
+++ b/packages/core/issues/comment-trigger-outcomes.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+import {
+ parseCommentTriggerOutcomes,
+ unhandledCommentTriggerOutcomes,
+ mentionLabelsByTarget,
+ blockedTriggerLabel,
+} from "./comment-trigger-outcomes";
+
+// MUL-4525 §2: the create/edit comment response's trigger_outcomes drive the
+// "posted, but N not triggered" warning, so parsing must be defensive (drop
+// malformed entries, tolerate older servers) and count only real blocks.
+describe("comment trigger outcomes", () => {
+ it("parses valid outcomes and drops malformed entries individually", () => {
+ const raw = [
+ { target_type: "agent", target_id: "a1", status: "queued", reason_code: "queued" },
+ { target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
+ { status: "blocked" }, // missing target_id → dropped
+ "not-an-object", // → dropped
+ ];
+ const parsed = parseCommentTriggerOutcomes(raw);
+ expect(parsed.map((o) => o.target_id)).toEqual(["a1", "s1"]);
+ });
+
+ it("returns [] for a missing / non-array field (older server)", () => {
+ expect(parseCommentTriggerOutcomes(undefined)).toEqual([]);
+ expect(parseCommentTriggerOutcomes(null)).toEqual([]);
+ expect(parseCommentTriggerOutcomes("nope")).toEqual([]);
+ });
+
+ it("treats only queued/coalesced/deferred as handled; blocked warns", () => {
+ const raw = [
+ { target_type: "agent", target_id: "a1", status: "queued", reason_code: "queued" },
+ { target_type: "agent", target_id: "a2", status: "coalesced", reason_code: "coalesced" },
+ { target_type: "agent", target_id: "a3", status: "deferred", reason_code: "deferred" },
+ { target_type: "squad", target_id: "s1", status: "blocked", reason_code: "invocation_not_allowed" },
+ ];
+ const unhandled = unhandledCommentTriggerOutcomes(raw);
+ expect(unhandled).toHaveLength(1);
+ expect(unhandled[0]?.target_id).toBe("s1");
+ });
+
+ it("warns on an unknown / future / empty status instead of assuming success", () => {
+ const raw = [
+ { target_type: "agent", target_id: "ok", status: "queued", reason_code: "queued" },
+ { target_type: "agent", target_id: "future", status: "throttled", reason_code: "x" },
+ { target_type: "squad", target_id: "empty", status: "", reason_code: "" },
+ ];
+ const unhandled = unhandledCommentTriggerOutcomes(raw);
+ expect(unhandled.map((o) => o.target_id).sort()).toEqual(["empty", "future"]);
+ });
+});
+
+// A blocked outcome carries no name (enumeration-safety), so the composer/toast
+// recover it from the user's own mention markup. `@` prefix is stripped and the
+// map is keyed by `${type}:${id}` to correlate with an outcome's target.
+describe("mentionLabelsByTarget", () => {
+ it("maps each mention target to the label the user typed (strips @)", () => {
+ const content =
+ "[@Go](mention://agent/deadbeef-0001) and [Design Squad](mention://squad/cafef00d-0002) hi";
+ const labels = mentionLabelsByTarget(content);
+ expect(labels.get("agent:deadbeef-0001")).toBe("Go");
+ expect(labels.get("squad:cafef00d-0002")).toBe("Design Squad");
+ });
+
+ it("correlates a blocked outcome to its label, undefined when absent", () => {
+ const labels = mentionLabelsByTarget("[@Go](mention://agent/deadbeef-0001)");
+ expect(
+ blockedTriggerLabel({ target_type: "agent", target_id: "deadbeef-0001" }, labels),
+ ).toBe("Go");
+ expect(
+ blockedTriggerLabel({ target_type: "agent", target_id: "beefdead-9999" }, labels),
+ ).toBeUndefined();
+ });
+
+ it("returns an empty map for content with no mentions", () => {
+ expect(mentionLabelsByTarget("just text").size).toBe(0);
+ expect(mentionLabelsByTarget("").size).toBe(0);
+ });
+});
diff --git a/packages/core/issues/comment-trigger-outcomes.ts b/packages/core/issues/comment-trigger-outcomes.ts
new file mode 100644
index 0000000000..e5cb8ec40a
--- /dev/null
+++ b/packages/core/issues/comment-trigger-outcomes.ts
@@ -0,0 +1,83 @@
+import { CommentTriggerOutcomeSchema } from "../api/schemas";
+import type { CommentTriggerOutcome } from "../types/comment";
+
+// Source for a rendered mention in comment markdown, capturing the label the
+// user picked, the target type, and the target id: `[@Go](mention://agent/UUID)`.
+// Kept as a string so every parse builds its OWN global RegExp — sharing one
+// global instance across `matchAll` calls leaks `lastIndex` and drops matches.
+const MENTION_MARKUP_SOURCE =
+ "\\[@?(.+?)\\]\\(mention:\\/\\/(member|agent|squad|issue|all)\\/([0-9a-fA-F-]+|all)\\)";
+
+export interface ParsedMention {
+ label: string;
+ type: string;
+ id: string;
+}
+
+// Every mention in the body, in order. Callers that only care about a subset
+// (e.g. skipping `issue` links, or deduping) filter the result.
+export function parseMentions(content: string): ParsedMention[] {
+ const re = new RegExp(MENTION_MARKUP_SOURCE, "g");
+ const mentions: ParsedMention[] = [];
+ for (const match of content.matchAll(re)) {
+ const label = match[1];
+ const type = match[2];
+ const id = match[3];
+ if (!label || !type || !id) continue;
+ mentions.push({ label, type, id });
+ }
+ return mentions;
+}
+
+// A blocked trigger outcome from the server intentionally omits the target's
+// name (enumeration-safety: the wire never reveals a private target). But the
+// CLIENT already rendered that name in its own draft/comment, so the composer
+// and the post-send toast can label a blocked mention from the markup the user
+// typed — no new disclosure. Returns a `${target_type}:${target_id}` -> label map.
+export function mentionLabelsByTarget(content: string): Map<string, string> {
+ const labels = new Map<string, string>();
+ for (const { label, type, id } of parseMentions(content)) {
+ labels.set(`${type}:${id}`, label);
+ }
+ return labels;
+}
+
+// The label a user typed for one blocked outcome, or undefined when it cannot be
+// correlated (e.g. the mention was edited away). Callers fall back to a
+// name-free reason so the warning is still shown.
+export function blockedTriggerLabel(
+ outcome: { target_type: string; target_id: string },
+ labels: Map<string, string>,
+): string | undefined {
+ return labels.get(`${outcome.target_type}:${outcome.target_id}`);
+}
+
+// Validates the `trigger_outcomes` off a create/edit comment response
+// (MUL-4525 §2). The create/edit responses are not fully schema-parsed, so the
+// one field the UI branches on is validated here: a non-array yields [], and a
+// malformed entry is dropped individually rather than failing the whole set.
+export function parseCommentTriggerOutcomes(raw: unknown): CommentTriggerOutcome[] {
+ if (!Array.isArray(raw)) return [];
+ const out: CommentTriggerOutcome[] = [];
+ for (const item of raw) {
+ const parsed = CommentTriggerOutcomeSchema.safeParse(item);
+ if (parsed.success) {
+ out.push(parsed.data as CommentTriggerOutcome);
+ }
+ }
+ return out;
+}
+
+// The only success-shaped outcome statuses: the mention WAS handled (a run was
+// queued, coalesced into an existing run, or intentionally deferred). Success is
+// a WHITELIST, not "anything that isn't blocked", so an unknown/future status —
+// or the empty status the schema defaults for a malformed entry — never passes
+// as success (MUL-4525; mirrors the Run now whitelist).
+const HANDLED_TRIGGER_STATUSES = new Set(["queued", "coalesced", "deferred"]);
+
+// The explicit @agent / @squad mentions that did NOT clearly trigger, so the
+// "posted, but N not triggered" warning must cover them: `blocked` plus any
+// unknown/future/empty status. Never assume an unrecognized status succeeded.
+export function unhandledCommentTriggerOutcomes(raw: unknown): CommentTriggerOutcome[] {
+ return parseCommentTriggerOutcomes(raw).filter((o) => !HANDLED_TRIGGER_STATUSES.has(o.status));
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index fec0f807e9..a8f6ffecc8 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -31,6 +31,7 @@
"./issues/queries": "./issues/queries.ts",
"./issues/mutations": "./issues/mutations.ts",
"./issues/timeline-sort": "./issues/timeline-sort.ts",
+ "./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts",
"./issues/date": "./issues/date.ts",
"./issues/ws-updaters": "./issues/ws-updaters.ts",
"./issues/surface/*": "./issues/surface/*.ts",
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 05c5bda9cc..efe90379b1 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -196,6 +196,50 @@ export interface AgentRunCount {
run_count: number;
}
+/**
+ * A departed-member-safe user ref resolved from the global user table. `name` /
+ * `email` / `avatar_url` are absent until the server hydrates them (present on
+ * user-facing task surfaces). Render defensively — fall back to a generic label
+ * when only `id` is available. See MUL-4302 §9.
+ */
+export interface AttributionUser {
+ id: string;
+ name?: string;
+ email?: string;
+ avatar_url?: string;
+}
+
+/** The kind-tagged handle to a run's direct cause (comment, autopilot run, ...). */
+export interface TaskEvidence {
+ kind: string;
+ ref_id: string;
+}
+
+/**
+ * The resolved accountable-human provenance of an agent run (MUL-4302 §9). Free-text
+ * `source` (server may add new levels), so switch on it with a default branch.
+ */
+export interface TaskAttribution {
+ /**
+ * Waterfall level that resolved the accountable human:
+ * `direct_human` | `delegation` | `comment_source` | `rule_owner` |
+ * `owner_fallback` | `backfill` | `unattributed`. Never blank.
+ */
+ source: string;
+ /** False for degraded sources (owner_fallback / backfill / unattributed). */
+ precise: boolean;
+ /** The accountable human ("on behalf of"). Absent when unattributed. */
+ initiator?: AttributionUser;
+ /** The authorization human; absent for autopilot runs (rule_owner / owner_fallback). */
+ originator?: AttributionUser;
+ /** The direct cause of the run, for a jump-to-evidence affordance. */
+ evidence?: TaskEvidence;
+ rule_version_id?: string;
+ delegated_from_task_id?: string;
+ retry_of_task_id?: string;
+ rerun_of_task_id?: string;
+}
+
export interface AgentTask {
id: string;
agent_id: string;
@@ -294,6 +338,12 @@ export interface AgentTask {
* shares and screenshots also stay safe).
*/
relative_work_dir?: string;
+ /**
+ * Resolved accountable-human provenance of this run (MUL-4302 §9): who it ran
+ * "on behalf of", how that was resolved, and the evidence/lineage. Present on
+ * user-facing task surfaces; older backends omit it — render conditionally.
+ */
+ attribution?: TaskAttribution;
}
export interface Agent {
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index e26c2b2a04..5b768e4899 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -122,6 +122,11 @@ export interface AutopilotRun {
triggered_at: string;
completed_at: string | null;
failure_reason: string | null;
+ // Stable, localizable, enumeration-safe classification of a non-success run
+ // (skipped/failed), derived server-side from failure_reason (MUL-4525). The
+ // "run now" UI localizes this instead of echoing the raw English reason.
+ // Older servers omit it.
+ reason_code?: string;
trigger_payload: unknown;
result: unknown;
created_at: string;
diff --git a/packages/core/types/comment.ts b/packages/core/types/comment.ts
index 02c1b65ac2..f4a837de8c 100644
--- a/packages/core/types/comment.ts
+++ b/packages/core/types/comment.ts
@@ -30,6 +30,25 @@ export interface Comment {
resolved_by_type: CommentAuthorType | null;
resolved_by_id: string | null;
source_task_id?: string | null;
+ // Per-target result of every explicit @agent / @squad mention in this comment
+ // (MUL-4525 §2). Present only on create/edit responses; older servers omit it.
+ trigger_outcomes?: CommentTriggerOutcome[];
+}
+
+// The domain result of one explicitly-mentioned trigger target. Success-shaped
+// statuses (queued/coalesced/deferred) mean the mention was handled; `blocked`
+// means it was refused with an enumeration-safe reason_code.
+export type CommentTriggerStatus =
+ | "queued"
+ | "coalesced"
+ | "deferred"
+ | "blocked";
+
+export interface CommentTriggerOutcome {
+ target_type: string; // "agent" | "squad"
+ target_id: string;
+ status: CommentTriggerStatus | string;
+ reason_code: string;
}
export type CommentTriggerSource =
@@ -47,4 +66,7 @@ export interface CommentTriggerPreviewAgent {
export interface CommentTriggerPreview {
agents: CommentTriggerPreviewAgent[];
+ // Explicit @agent / @squad mentions that will NOT trigger if posted as-is
+ // (MUL-4525 §2). Additive: older servers omit it.
+ blocked?: CommentTriggerOutcome[];
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 0cb0ec61c3..0714f228cb 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -8,6 +8,9 @@ export type {
AgentInvocationTarget,
AgentInvocationTargetInput,
AgentTask,
+ TaskAttribution,
+ AttributionUser,
+ TaskEvidence,
AgentActivityBucket,
AgentRunCount,
TaskFailureReason,
@@ -68,7 +71,7 @@ export { RUNTIME_PROFILE_PROTOCOL_FAMILIES } from "./agent";
export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
-export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, Reaction } from "./comment";
+export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
export type {
TimelineEntry,
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
index 9018b42fb0..44770704e4 100644
--- a/packages/views/agents/components/tabs/activity-tab.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -37,6 +37,7 @@ import { useWorkspacePaths } from "@multica/core/paths";
import { issueDetailOptions } from "@multica/core/issues/queries";
import { AppLink } from "../../../navigation";
import { TranscriptButton } from "../../../common/task-transcript";
+import { AttributionBadge } from "../../../issues/components/attribution-badge";
import { taskStatusConfig } from "../../config";
import { failureReasonLabel } from "./task-failure";
import { Sparkline } from "../sparkline";
@@ -639,6 +640,14 @@ function TaskRow({
<span className="text-destructive">{failureLabel}</span>
</>
)}
+ {/* Accountable member (MUL-4302 §9): whose behalf this run is on.
+ Avatar-only keeps the meta line tight; renders nothing when the
+ run has no resolved responsible member. */}
+ <AttributionBadge
+ attribution={task.attribution}
+ variant="avatar"
+ className="ml-0.5"
+ />
</div>
</div>
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 14d78485c3..ce06b12b57 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -62,6 +62,7 @@ import type { AgentTask } from "@multica/core/types/agent";
import { ReadonlyContent } from "../../editor";
import { TranscriptButton } from "../../common/task-transcript";
import { AutopilotDialog } from "./autopilot-dialog";
+import { runNowToastKind, runNowBlockedKey } from "./run-now-toast";
import { WebhookPayloadPreview } from "./webhook-payload-preview";
import { WebhookDeliveriesSection } from "./webhook-deliveries-section";
import { ProjectIcon } from "../../projects/components/project-icon";
@@ -697,8 +698,24 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
const handleRunNow = async () => {
try {
- await triggerAutopilot.mutateAsync(autopilotId);
- toast.success(t(($) => $.detail.toast_triggered));
+ const run = await triggerAutopilot.mutateAsync(autopilotId);
+ // Manual "run now" returns 200 even when admission blocks the run, so the
+ // toast is driven by the run's domain status, not the HTTP 2xx (MUL-4525).
+ // Success is a whitelist (issue_created/running) — a skipped run warns, a
+ // failed or unknown/future status errors — never a false "triggered".
+ const kind = runNowToastKind(run?.status);
+ if (kind === "success") {
+ toast.success(t(($) => $.detail.toast_triggered));
+ return;
+ }
+ // reason_code is the stable, typed cause the server decided at admission
+ // time; an unknown/absent code degrades to a generic "not triggered".
+ const message = t(($) => $.detail[runNowBlockedKey(run?.reason_code)]);
+ if (kind === "warning") {
+ toast.warning(message);
+ } else {
+ toast.error(message);
+ }
} catch (e: any) {
toast.error(e?.message || t(($) => $.detail.toast_trigger_failed));
}
diff --git a/packages/views/autopilots/components/run-now-toast.test.ts b/packages/views/autopilots/components/run-now-toast.test.ts
new file mode 100644
index 0000000000..58f0728485
--- /dev/null
+++ b/packages/views/autopilots/components/run-now-toast.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { runNowToastKind, runNowBlockedKey } from "./run-now-toast";
+
+// Elon must-fix 1 (MUL-4525): the "run now" toast must be a whitelist — only
+// explicit start statuses are success; every other class (including an unknown
+// future status) must NOT show a false "triggered".
+describe("runNowToastKind", () => {
+ it("shows success only for explicit start statuses", () => {
+ expect(runNowToastKind("issue_created")).toBe("success");
+ expect(runNowToastKind("running")).toBe("success");
+ });
+
+ it("warns on a skipped (admission-blocked) run", () => {
+ expect(runNowToastKind("skipped")).toBe("warning");
+ });
+
+ it("errors on a failed run", () => {
+ expect(runNowToastKind("failed")).toBe("error");
+ });
+
+ it("errors on an unknown/future status instead of claiming success", () => {
+ expect(runNowToastKind("blocked")).toBe("error");
+ expect(runNowToastKind("deferred")).toBe("error");
+ expect(runNowToastKind("")).toBe("error");
+ expect(runNowToastKind(undefined)).toBe("error");
+ });
+});
+
+describe("runNowBlockedKey", () => {
+ it("maps each known reason_code to its localized message key", () => {
+ expect(runNowBlockedKey("invocation_not_allowed")).toBe("run_blocked_invocation_not_allowed");
+ expect(runNowBlockedKey("runtime_offline")).toBe("run_blocked_runtime_offline");
+ expect(runNowBlockedKey("target_unavailable")).toBe("run_blocked_target_unavailable");
+ expect(runNowBlockedKey("attribution_blocked")).toBe("run_blocked_attribution");
+ expect(runNowBlockedKey("already_active")).toBe("run_blocked_already_active");
+ });
+
+ it("degrades an unknown or absent code to the generic message", () => {
+ expect(runNowBlockedKey("some_future_code")).toBe("run_blocked_generic");
+ expect(runNowBlockedKey(undefined)).toBe("run_blocked_generic");
+ });
+});
diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.ts
new file mode 100644
index 0000000000..ebe9103a39
--- /dev/null
+++ b/packages/views/autopilots/components/run-now-toast.ts
@@ -0,0 +1,55 @@
+// Classifies a manual "run now" outcome into a toast (MUL-4525). Pure so it can
+// be unit-tested across every run-status class without mounting the page.
+//
+// The response schema deliberately accepts any status string for forward
+// compatibility, so success must be a WHITELIST — never "anything that isn't
+// skipped/failed". A future or anomalous-but-parseable status (e.g. "blocked",
+// "deferred") must degrade to an error toast, never a false "triggered".
+
+export type RunNowToastKind = "success" | "warning" | "error";
+
+// Only explicit start statuses count as success. Everything else is a
+// non-success outcome the user must be warned/errored about.
+export function runNowToastKind(status: string | undefined): RunNowToastKind {
+ switch (status) {
+ case "issue_created":
+ case "running":
+ return "success";
+ case "skipped":
+ // Admission blocked / target not ready — recoverable, informational.
+ return "warning";
+ case "failed":
+ return "error";
+ default:
+ // Unknown / future status: never claim success.
+ return "error";
+ }
+}
+
+// The i18n key (under the autopilots `detail` namespace) describing why a
+// non-success run did not trigger, keyed on the stable server reason_code. An
+// unknown/absent code degrades to a generic message.
+export type RunNowBlockedKey =
+ | "run_blocked_invocation_not_allowed"
+ | "run_blocked_runtime_offline"
+ | "run_blocked_target_unavailable"
+ | "run_blocked_attribution"
+ | "run_blocked_already_active"
+ | "run_blocked_generic";
+
+export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKey {
+ switch (reasonCode) {
+ case "invocation_not_allowed":
+ return "run_blocked_invocation_not_allowed";
+ case "runtime_offline":
+ return "run_blocked_runtime_offline";
+ case "target_unavailable":
+ return "run_blocked_target_unavailable";
+ case "attribution_blocked":
+ return "run_blocked_attribution";
+ case "already_active":
+ return "run_blocked_already_active";
+ default:
+ return "run_blocked_generic";
+ }
+}
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 5c19dc17d9..90eedaac5c 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -12,7 +12,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useAuthStore } from "@multica/core/auth";
import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";
import { canAssignAgent } from "@multica/views/issues/components";
-import { api } from "@multica/core/api";
+import { api, dispatchReasonCode } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import {
@@ -461,7 +461,13 @@ export function useChatController(opts?: { isActive?: boolean }) {
sessionId = await ensureSession(finalContent);
} catch (err) {
apiLogger.error("sendChatMessage.ensureSession.error", err);
- toast.error(t(($) => $.input.send_failed_toast));
+ // A revoked invoke permission blocks session create with a structured
+ // 403 (MUL-4525) — name the cause instead of a generic failure.
+ toast.error(
+ dispatchReasonCode(err) === "invocation_not_allowed"
+ ? t(($) => $.input.send_blocked_toast)
+ : t(($) => $.input.send_failed_toast),
+ );
return false;
}
if (!sessionId) {
@@ -513,7 +519,15 @@ export function useChatController(opts?: { isActive?: boolean }) {
attachments: draftAttachments,
sessionId,
});
- toast.error(t(($) => $.input.send_failed_toast));
+ // Invoke permission can be revoked mid-session; the send is refused with
+ // a structured 403 before anything persists (MUL-4525). Surface the
+ // specific cause so the user knows it is a permission change, not a
+ // transient failure they should retry.
+ toast.error(
+ dispatchReasonCode(err) === "invocation_not_allowed"
+ ? t(($) => $.input.send_blocked_toast)
+ : t(($) => $.input.send_failed_toast),
+ );
return false;
}
apiLogger.info("sendChatMessage.success", {
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 4fa8078862..c44b60a580 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -34,6 +34,7 @@ import {
DropdownMenuItem,
} from "@multica/ui/components/ui/dropdown-menu";
import { ActorAvatar } from "../actor-avatar";
+import { AttributionBadge } from "../../issues/components/attribution-badge";
import { api } from "@multica/core/api";
import {
useTranscriptViewStore,
@@ -500,6 +501,9 @@ export function AgentTranscriptDialog({
{statusBadge}
+ {/* Accountable member (MUL-4302 §9): whose behalf this run is on. */}
+ <AttributionBadge attribution={task.attribution} className="shrink-0" />
+
<div className="flex w-full max-w-full flex-wrap items-center justify-end gap-1 sm:ml-auto sm:w-auto">
{detailSeqs.length > 0 && (
<button
diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.ts
new file mode 100644
index 0000000000..651a1fa707
--- /dev/null
+++ b/packages/views/issues/blocked-trigger-copy.ts
@@ -0,0 +1,37 @@
+import type { useT } from "../i18n";
+
+// Localized copy for a blocked @agent / @squad trigger outcome (MUL-4525 §2),
+// shared by the composer preview chip and the post-send toast so both name the
+// same reason the same way. `reason_code` is the enumeration-safe wire code; the
+// label it maps to never reveals the target's identity — the caller supplies the
+// name it already has from the user's own mention markup.
+type IssuesT = ReturnType<typeof useT<"issues">>["t"];
+
+// Full sentence — for tooltips and other surfaces with room to explain.
+export function blockedReasonLabel(reasonCode: string, t: IssuesT): string {
+ switch (reasonCode) {
+ case "invocation_not_allowed":
+ return t(($) => $.comment.trigger_blocked_invocation_not_allowed);
+ case "target_unavailable":
+ return t(($) => $.comment.trigger_blocked_target_unavailable);
+ case "runtime_offline":
+ return t(($) => $.comment.trigger_blocked_runtime_offline);
+ default:
+ return t(($) => $.comment.trigger_blocked_generic);
+ }
+}
+
+// Short badge — for the inline chip and toast where the target name carries the
+// "who" and the reason only needs to say why in a couple of words.
+export function blockedShortReasonLabel(reasonCode: string, t: IssuesT): string {
+ switch (reasonCode) {
+ case "invocation_not_allowed":
+ return t(($) => $.comment.trigger_blocked_short_invocation_not_allowed);
+ case "target_unavailable":
+ return t(($) => $.comment.trigger_blocked_short_target_unavailable);
+ case "runtime_offline":
+ return t(($) => $.comment.trigger_blocked_short_runtime_offline);
+ default:
+ return t(($) => $.comment.trigger_blocked_short_generic);
+ }
+}
diff --git a/packages/views/issues/components/attribution-badge.test.tsx b/packages/views/issues/components/attribution-badge.test.tsx
new file mode 100644
index 0000000000..6cb92cb8d5
--- /dev/null
+++ b/packages/views/issues/components/attribution-badge.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+
+import { cleanup, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { TaskAttribution } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+
+// The avatar is presentational plumbing here; stub it so the tests assert the
+// badge's own text/tone rather than the shared avatar's fallback behavior.
+vi.mock("@multica/ui/components/common/actor-avatar", () => ({
+ ActorAvatar: ({ name }: { name: string }) => (
+ <span data-testid="actor-avatar">{name}</span>
+ ),
+}));
+
+import { AttributionBadge } from "./attribution-badge";
+
+afterEach(cleanup);
+
+describe("AttributionBadge", () => {
+ it("renders nothing when the task has no attribution", () => {
+ const { container } = renderWithI18n(<AttributionBadge />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("shows who the run is on behalf of, with the source as a tooltip", () => {
+ const attribution: TaskAttribution = {
+ source: "direct_human",
+ precise: true,
+ initiator: { id: "u1", name: "Ada Lovelace" },
+ };
+ renderWithI18n(<AttributionBadge attribution={attribution} />);
+
+ expect(screen.getByText("on behalf of Ada Lovelace")).toBeInTheDocument();
+ expect(screen.getByTitle("Direct member action")).toBeInTheDocument();
+ });
+
+ it("marks degraded (non-precise) attribution with a warning tone", () => {
+ const attribution: TaskAttribution = {
+ source: "owner_fallback",
+ precise: false,
+ initiator: { id: "u2", name: "Grace" },
+ };
+ const { container } = renderWithI18n(
+ <AttributionBadge attribution={attribution} />,
+ );
+
+ expect(screen.getByText("on behalf of Grace")).toBeInTheDocument();
+ expect(container.querySelector(".text-warning")).not.toBeNull();
+ expect(screen.getByTitle("No precise owner — attributed to the agent owner"))
+ .toBeInTheDocument();
+ });
+
+ it("falls back to a generic name when the initiator has no display name", () => {
+ const attribution: TaskAttribution = {
+ source: "delegation",
+ precise: true,
+ initiator: { id: "u3" },
+ };
+ renderWithI18n(<AttributionBadge attribution={attribution} />);
+
+ expect(screen.getByText("on behalf of someone")).toBeInTheDocument();
+ });
+
+ it("renders an unattributed chip when no responsible member resolved", () => {
+ const attribution: TaskAttribution = {
+ source: "unattributed",
+ precise: false,
+ };
+ const { container } = renderWithI18n(
+ <AttributionBadge attribution={attribution} />,
+ );
+
+ expect(screen.getByText("No responsible member")).toBeInTheDocument();
+ expect(container.querySelector(".text-warning")).not.toBeNull();
+ });
+
+ it("degrades gracefully for an unknown source label", () => {
+ const attribution: TaskAttribution = {
+ source: "future_source",
+ precise: true,
+ initiator: { id: "u4", name: "Ada" },
+ };
+ renderWithI18n(<AttributionBadge attribution={attribution} />);
+
+ // Unknown sources fall through to the raw label so nothing renders blank.
+ expect(screen.getByTitle("future_source")).toBeInTheDocument();
+ });
+
+ it("avatar variant renders just the accountable member's avatar", () => {
+ const attribution: TaskAttribution = {
+ source: "direct_human",
+ precise: true,
+ initiator: { id: "u1", name: "Ada Lovelace" },
+ };
+ renderWithI18n(
+ <AttributionBadge attribution={attribution} variant="avatar" />,
+ );
+
+ // Only the avatar (name plumbs through the stub) — no "on behalf of" chip.
+ expect(screen.getByTestId("actor-avatar")).toHaveTextContent("Ada Lovelace");
+ expect(screen.queryByText("on behalf of Ada Lovelace")).toBeNull();
+ });
+
+ it("avatar variant renders nothing without an accountable member", () => {
+ const attribution: TaskAttribution = {
+ source: "unattributed",
+ precise: false,
+ };
+ const { container } = renderWithI18n(
+ <AttributionBadge attribution={attribution} variant="avatar" />,
+ );
+
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/views/issues/components/attribution-badge.tsx b/packages/views/issues/components/attribution-badge.tsx
new file mode 100644
index 0000000000..469d84048a
--- /dev/null
+++ b/packages/views/issues/components/attribution-badge.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import type { TaskAttribution } from "@multica/core/types";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+
+/** First + last initial, for the avatar fallback when there's no picture. */
+function initialsOf(name: string): string {
+ const parts = name.trim().split(/\s+/).filter(Boolean);
+ const first = parts[0];
+ if (!first) return "?";
+ const last = parts[parts.length - 1];
+ if (parts.length === 1 || !last) return first.slice(0, 2).toUpperCase();
+ return (first.charAt(0) + last.charAt(0)).toUpperCase();
+}
+
+/**
+ * AttributionBadge renders who an agent run is accountable to (MUL-4302 §9):
+ * the "on behalf of <member>" provenance, with the resolution source and a
+ * distinct warning tone for degraded (non-precise) attribution.
+ *
+ * Two shapes:
+ * - `variant="badge"` (default): the full "on behalf of <name>" chip, with an
+ * explicit "unattributed" chip when no responsible member resolved.
+ * - `variant="avatar"`: just the accountable member's avatar, with the name +
+ * source in a hover tooltip. Compact enough for a dense task row. Renders
+ * nothing when there's no accountable member — an avatar-only surface has
+ * nothing meaningful to show for an unattributed run.
+ *
+ * Renders nothing when the task has no attribution at all (older backends) —
+ * the caller should optional-chain `task.attribution`.
+ */
+export function AttributionBadge({
+ attribution,
+ className,
+ variant = "badge",
+}: {
+ attribution?: TaskAttribution;
+ className?: string;
+ variant?: "badge" | "avatar";
+}) {
+ const { t } = useT("issues");
+ if (!attribution) return null;
+
+ // Human-readable resolution source, defaulting to the raw label so a
+ // server-added source degrades gracefully instead of showing blank.
+ let sourceLabel: string;
+ switch (attribution.source) {
+ case "direct_human":
+ sourceLabel = t(($) => $.execution_log.attribution.source_direct_human);
+ break;
+ case "delegation":
+ sourceLabel = t(($) => $.execution_log.attribution.source_delegation);
+ break;
+ case "comment_source":
+ sourceLabel = t(($) => $.execution_log.attribution.source_comment_source);
+ break;
+ case "trigger_owner":
+ sourceLabel = t(($) => $.execution_log.attribution.source_trigger_owner);
+ break;
+ case "rule_owner":
+ sourceLabel = t(($) => $.execution_log.attribution.source_rule_owner);
+ break;
+ case "owner_fallback":
+ sourceLabel = t(($) => $.execution_log.attribution.source_owner_fallback);
+ break;
+ case "backfill":
+ sourceLabel = t(($) => $.execution_log.attribution.source_backfill);
+ break;
+ case "unattributed":
+ sourceLabel = t(($) => $.execution_log.attribution.source_unattributed);
+ break;
+ default:
+ sourceLabel = attribution.source;
+ }
+
+ // Degraded attribution (owner_fallback / backfill / unattributed) is marked
+ // distinctly so it never reads as a compliance-grade "who is responsible".
+ const degraded = attribution.precise === false;
+ const initiator = attribution.initiator;
+
+ // Avatar-only shape: just the accountable member's face, with the name +
+ // source in a hover tooltip. Nothing to show without an accountable member.
+ if (variant === "avatar") {
+ if (!initiator) return null;
+ const name = initiator.name || t(($) => $.execution_log.attribution.someone);
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className={cn(
+ "inline-flex shrink-0",
+ // A subtle ring flags degraded attribution so an owner-fallback
+ // face never silently reads as a precise responsible member.
+ degraded && "rounded-full ring-1 ring-warning/60",
+ className
+ )}
+ >
+ <ActorAvatar
+ name={name}
+ initials={initialsOf(name)}
+ avatarUrl={initiator.avatar_url}
+ size="xs"
+ />
+ </span>
+ }
+ />
+ <TooltipContent>
+ <div className="flex flex-col">
+ <span>
+ {t(($) => $.execution_log.attribution.on_behalf_of, { name })}
+ </span>
+ <span
+ className={cn(
+ "text-[11px]",
+ degraded ? "text-warning" : "text-muted-foreground"
+ )}
+ >
+ {sourceLabel}
+ </span>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ if (!initiator) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn("max-w-40 min-w-0 gap-1 font-normal text-warning", className)}
+ title={sourceLabel}
+ >
+ <span className="min-w-0 truncate">
+ {t(($) => $.execution_log.attribution.unattributed)}
+ </span>
+ </Badge>
+ );
+ }
+
+ const name = initiator.name || t(($) => $.execution_log.attribution.someone);
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ "max-w-40 min-w-0 gap-1 font-normal",
+ degraded ? "text-warning" : "text-muted-foreground",
+ className
+ )}
+ title={sourceLabel}
+ >
+ <ActorAvatar
+ name={name}
+ initials={initialsOf(name)}
+ avatarUrl={initiator.avatar_url}
+ size="xs"
+ className="shrink-0"
+ />
+ <span className="min-w-0 truncate">
+ {t(($) => $.execution_log.attribution.on_behalf_of, { name })}
+ </span>
+ </Badge>
+ );
+}
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index a6fba76ce1..a722ef9f35 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -33,7 +33,7 @@ import { useTimeAgo } from "../../i18n";
import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { api } from "@multica/core/api";
+import { api, dispatchReasonCode } from "@multica/core/api";
import { ReplyInput } from "./reply-input";
import { CommentTriggerChips } from "./comment-trigger-chips";
import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";
@@ -278,7 +278,15 @@ function TaskCommentRetryButton({
try {
await api.rerunIssue(issueId, taskId);
} catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.execution_log.retry_failed));
+ // Rerun re-checks the operator's invoke permission (MUL-4525); a
+ // structured 403 is a permission block, not a transient failure.
+ toast.error(
+ dispatchReasonCode(e) === "invocation_not_allowed"
+ ? t(($) => $.execution_log.retry_blocked)
+ : e instanceof Error
+ ? e.message
+ : t(($) => $.execution_log.retry_failed),
+ );
} finally {
setRetrying(false);
}
@@ -453,6 +461,7 @@ function useEditAttachmentState(
isDragOver,
dropZoneProps,
triggerPreview,
+ content,
suppressedAgentIds,
toggleSuppressedAgent,
draftKey,
@@ -647,6 +656,8 @@ function CommentRow({
<div className="min-w-0 flex-1">
<CommentTriggerChips
agents={edit.triggerPreview.agents}
+ blocked={edit.triggerPreview.blocked}
+ draftContent={edit.content}
suppressedAgentIds={edit.suppressedAgentIds}
onToggle={edit.toggleSuppressedAgent}
/>
@@ -937,6 +948,8 @@ function CommentCardImpl({
)}
<CommentTriggerChips
agents={edit.triggerPreview.agents}
+ blocked={edit.triggerPreview.blocked}
+ draftContent={edit.content}
suppressedAgentIds={edit.suppressedAgentIds}
onToggle={edit.toggleSuppressedAgent}
/>
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index f80f84fa5a..defb001831 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -182,6 +182,8 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
<div className="absolute bottom-1 left-2 right-28 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
+ blocked={triggerPreview.blocked}
+ draftContent={content}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
diff --git a/packages/views/issues/components/comment-trigger-chips.test.tsx b/packages/views/issues/components/comment-trigger-chips.test.tsx
index 07afeafaad..3444159feb 100644
--- a/packages/views/issues/components/comment-trigger-chips.test.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.test.tsx
@@ -119,4 +119,72 @@ describe("CommentTriggerChips", () => {
fireEvent.click(row);
expect(onToggle).toHaveBeenCalledWith("agent-2");
});
+
+ it("names a blocked mention with an error reason instead of a count", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[]}
+ blocked={[
+ {
+ target_type: "agent",
+ target_id: "deadbeef-0001",
+ status: "blocked",
+ reason_code: "invocation_not_allowed",
+ },
+ ]}
+ draftContent="[@Go](mention://agent/deadbeef-0001) hi"
+ suppressedAgentIds={new Set()}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ // The name the user typed (not a "1 mention won't trigger" count) plus the
+ // short no-permission reason.
+ expect(screen.getByText("Go")).toBeInTheDocument();
+ expect(screen.getByText("No permission")).toBeInTheDocument();
+ expect(screen.queryByText(/won't trigger/i)).not.toBeInTheDocument();
+ });
+
+ it("falls back to the reason alone when the label can't be correlated", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[]}
+ blocked={[
+ {
+ target_type: "agent",
+ target_id: "deadbeef-0001",
+ status: "blocked",
+ reason_code: "invocation_not_allowed",
+ },
+ ]}
+ // No matching mention markup for the blocked target → no label available.
+ draftContent="plain text"
+ suppressedAgentIds={new Set()}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText("No permission")).toBeInTheDocument();
+ expect(screen.queryByText("Go")).not.toBeInTheDocument();
+ });
+
+ it("renders one named chip per blocked mention", () => {
+ renderWithI18n(
+ <CommentTriggerChips
+ agents={[]}
+ blocked={[
+ { target_type: "agent", target_id: "deadbeef-0001", status: "blocked", reason_code: "invocation_not_allowed" },
+ { target_type: "squad", target_id: "cafef00d-0002", status: "blocked", reason_code: "runtime_offline" },
+ ]}
+ draftContent="[@Go](mention://agent/deadbeef-0001) [@Ops](mention://squad/cafef00d-0002)"
+ suppressedAgentIds={new Set()}
+ onToggle={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByText("Go")).toBeInTheDocument();
+ expect(screen.getByText("No permission")).toBeInTheDocument();
+ expect(screen.getByText("Ops")).toBeInTheDocument();
+ expect(screen.getByText("Runtime offline")).toBeInTheDocument();
+ });
});
diff --git a/packages/views/issues/components/comment-trigger-chips.tsx b/packages/views/issues/components/comment-trigger-chips.tsx
index d03084f446..e5c2f924ed 100644
--- a/packages/views/issues/components/comment-trigger-chips.tsx
+++ b/packages/views/issues/components/comment-trigger-chips.tsx
@@ -1,8 +1,10 @@
"use client";
-import { useState } from "react";
-import type { CommentTriggerPreviewAgent } from "@multica/core/types";
+import { useMemo, useState } from "react";
+import { TriangleAlert } from "lucide-react";
+import type { CommentTriggerPreviewAgent, CommentTriggerOutcome } from "@multica/core/types";
import { useAgentPresenceDetail } from "@multica/core/agents";
+import { mentionLabelsByTarget } from "@multica/core/issues/comment-trigger-outcomes";
import { useCurrentWorkspace } from "@multica/core/paths";
import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
import { AVATAR_SIZE_PX } from "@multica/ui/lib/avatar-size";
@@ -15,6 +17,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/
import { cn } from "@multica/ui/lib/utils";
import { AgentStatusDot } from "../../common/actor-avatar";
import { useT } from "../../i18n";
+import { blockedReasonLabel, blockedShortReasonLabel } from "../blocked-trigger-copy";
// One agent renders in full ("Walt will start working", avatar + presence
// dot, click toggles). Several agents collapse to an overlapping avatar
@@ -31,6 +34,14 @@ const MAX_STACK_HEADS = 4;
interface CommentTriggerChipsProps {
agents: CommentTriggerPreviewAgent[];
+ // Explicit @agent / @squad mentions that will NOT trigger if posted as-is
+ // (MUL-4525 §2). Each renders as a named warning chip so the user sees WHICH
+ // target won't run and why, not a silent no-op after sending.
+ blocked?: CommentTriggerOutcome[];
+ // The draft markdown, used only to label each blocked target with the name the
+ // user typed in its mention markup. The server omits blocked target names
+ // (enumeration-safety); this is the user's own text, so it discloses nothing new.
+ draftContent?: string;
suppressedAgentIds: Set<string>;
onToggle: (agentId: string) => void;
}
@@ -114,34 +125,96 @@ function TriggerAgentTooltipBody({
export function CommentTriggerChips({
agents,
+ blocked = [],
+ draftContent = "",
suppressedAgentIds,
onToggle,
}: CommentTriggerChipsProps) {
const { t } = useT("issues");
+ // Blocked outcomes carry no name (enumeration-safety); recover the label the
+ // user typed from their own draft so each chip can say which target it is.
+ const blockedLabels = useMemo(() => mentionLabelsByTarget(draftContent), [draftContent]);
// Loading and errors render nothing: the preview is an enhancement, and
// any interim chrome here reads as composer noise.
- if (agents.length === 0) return null;
+ if (agents.length === 0 && blocked.length === 0) return null;
- if (agents.length === 1) {
- const agent = agents[0]!;
- return (
+ const allowed =
+ agents.length === 1 ? (
<SingleTriggerChip
- agent={agent}
- suppressed={suppressedAgentIds.has(agent.id)}
+ agent={agents[0]!}
+ suppressed={suppressedAgentIds.has(agents[0]!.id)}
onToggle={onToggle}
t={t}
/>
- );
- }
+ ) : agents.length > 1 ? (
+ <MultiTriggerChip
+ agents={agents}
+ suppressedAgentIds={suppressedAgentIds}
+ onToggle={onToggle}
+ t={t}
+ />
+ ) : null;
+
+ if (blocked.length === 0) return allowed;
return (
- <MultiTriggerChip
- agents={agents}
- suppressedAgentIds={suppressedAgentIds}
- onToggle={onToggle}
- t={t}
- />
+ <div className="flex flex-wrap items-center gap-1.5">
+ {allowed}
+ {blocked.map((outcome) => (
+ <BlockedTriggerChip
+ key={`${outcome.target_type}:${outcome.target_id}`}
+ outcome={outcome}
+ label={blockedLabels.get(`${outcome.target_type}:${outcome.target_id}`)}
+ t={t}
+ />
+ ))}
+ </div>
+ );
+}
+
+// One blocked mention: named like an allowed chip ("Go"), but with an error
+// indicator and a short reason ("No permission") instead of "will start", so a
+// refused @mention reads as a clear, specific error rather than a vague count.
+function BlockedTriggerChip({
+ outcome,
+ label,
+ t,
+}: {
+ outcome: CommentTriggerOutcome;
+ label?: string;
+ t: IssuesT;
+}) {
+ const shortReason = blockedShortReasonLabel(outcome.reason_code, t);
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className="inline-flex h-6 min-w-0 max-w-full animate-in fade-in items-center gap-1.5 rounded-md px-1.5 text-[11px] font-medium text-destructive"
+ aria-label={
+ label
+ ? t(($) => $.comment.trigger_blocked_chip_aria, { name: label, reason: shortReason })
+ : shortReason
+ }
+ >
+ <TriangleAlert className="size-3 shrink-0" />
+ {label ? (
+ <span className="inline-flex min-w-0 items-center gap-1">
+ <span className="truncate">{label}</span>
+ <span className="shrink-0">·</span>
+ <span className="shrink-0">{shortReason}</span>
+ </span>
+ ) : (
+ <span className="truncate">{shortReason}</span>
+ )}
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="max-w-72 text-xs">
+ {blockedReasonLabel(outcome.reason_code, t)}
+ </TooltipContent>
+ </Tooltip>
);
}
diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsx
index 1dbc5d0765..849befc91c 100644
--- a/packages/views/issues/components/execution-log-section.tsx
+++ b/packages/views/issues/components/execution-log-section.tsx
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Ban, CheckCircle2, ChevronRight, Loader2, RotateCcw, Square, XCircle } from "lucide-react";
import { toast } from "sonner";
-import { api } from "@multica/core/api";
+import { api, dispatchReasonCode } from "@multica/core/api";
import { issueKeys } from "@multica/core/issues/queries";
import type { AgentTask, TaskFailureReason } from "@multica/core/types";
import { useTimeAgo } from "../../i18n";
@@ -18,6 +18,7 @@ import { formatDuration } from "../../agents/components/agent-activity-hover-con
import { TranscriptButton } from "../../common/task-transcript";
import { failureReasonLabel } from "../../agents/components/tabs/task-failure";
import { useT } from "../../i18n";
+import { AttributionBadge } from "./attribution-badge";
import { TerminateTaskConfirmDialog } from "./terminate-task-confirm-dialog";
// Right-panel section that lists every agent run for this issue. Active
@@ -305,6 +306,7 @@ export function ActiveTaskRow({
return (
<RowShell task={task}>
<TriggerText text={trigger} />
+ <AttributionBadge attribution={task.attribution} className="shrink-0" />
<TaskCommentCoverage task={task} />
<RowStatus title={label}>
{task.status === "running" ? (
@@ -387,7 +389,16 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
try {
await api.rerunIssue(issueId, task.id);
} catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.execution_log.retry_failed));
+ // A rerun is now re-gated on the operator's invoke permission (MUL-4525):
+ // a structured 403 means the agent can't be triggered, not a transient
+ // failure — localize it instead of echoing the server's generic message.
+ toast.error(
+ dispatchReasonCode(e) === "invocation_not_allowed"
+ ? t(($) => $.execution_log.retry_blocked)
+ : e instanceof Error
+ ? e.message
+ : t(($) => $.execution_log.retry_failed),
+ );
} finally {
// Reset on both success and failure: the past row stays mounted
// (its task.id is unchanged), so leaving `retrying` true on success
@@ -399,6 +410,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
return (
<RowShell task={task}>
<TriggerText text={trigger} />
+ <AttributionBadge attribution={task.attribution} className="shrink-0" />
<TaskCommentCoverage task={task} />
<RowStatus title={failureLabel ?? label}>
<TaskStatusIcon status={task.status} />
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 06ae790ac9..433ed639b0 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -203,6 +203,8 @@ function ReplyInput({
<div className="absolute bottom-0 left-0 right-24 min-w-0">
<CommentTriggerChips
agents={triggerPreview.agents}
+ blocked={triggerPreview.blocked}
+ draftContent={content}
suppressedAgentIds={suppressedAgentIds}
onToggle={toggleSuppressedAgent}
/>
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
index 04e619c2bc..e3c653d9a1 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.test.ts
@@ -251,7 +251,7 @@ describe("useCommentTriggerPreview", () => {
await advancePreviewDebounce();
- expect(result.current).toEqual({ agents: [] });
+ expect(result.current).toEqual({ agents: [], blocked: [] });
expect(previewCommentTriggers).not.toHaveBeenCalled();
});
});
diff --git a/packages/views/issues/hooks/use-comment-trigger-preview.ts b/packages/views/issues/hooks/use-comment-trigger-preview.ts
index 6764ea2ef5..decd938aae 100644
--- a/packages/views/issues/hooks/use-comment-trigger-preview.ts
+++ b/packages/views/issues/hooks/use-comment-trigger-preview.ts
@@ -4,14 +4,17 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import { issueKeys } from "@multica/core/issues/queries";
-import type { CommentTriggerPreviewAgent } from "@multica/core/types";
+import { parseMentions } from "@multica/core/issues/comment-trigger-outcomes";
+import type { CommentTriggerPreviewAgent, CommentTriggerOutcome } from "@multica/core/types";
const COMMENT_TRIGGER_PREVIEW_DEBOUNCE_MS = 300;
-const MENTION_RE = /\[@?(.+?)\]\(mention:\/\/(member|agent|squad|issue|all)\/([0-9a-fA-F-]+|all)\)/g;
const NOTE_COMMAND_RE = /^\/note(?:$|\s)/i;
export interface UseCommentTriggerPreviewResult {
agents: CommentTriggerPreviewAgent[];
+ // Explicit @agent / @squad mentions that will NOT trigger if posted as-is
+ // (MUL-4525 §2), so the composer can warn before sending.
+ blocked: CommentTriggerOutcome[];
}
export function isNoteCommentDraft(content: string): boolean {
@@ -23,10 +26,8 @@ export function commentTriggerPreviewSignature(content: string): string {
const seen = new Set<string>();
const tokens: string[] = [];
- for (const match of content.matchAll(MENTION_RE)) {
- const type = match[2];
- const id = match[3];
- if (!type || !id || type === "issue") continue;
+ for (const { type, id } of parseMentions(content)) {
+ if (type === "issue") continue;
const token = `${type}:${id}`;
if (seen.has(token)) continue;
seen.add(token);
@@ -113,8 +114,11 @@ export function useCommentTriggerPreview({
// Loading and errors intentionally surface as "no agents": the preview is
// an enhancement, and the composer renders nothing for an empty list.
if (signature === "empty" || debouncedSignature === "empty") {
- return { agents: [] };
+ return { agents: [], blocked: [] };
}
- return { agents: previewQuery.data?.agents ?? [] };
+ return {
+ agents: previewQuery.data?.agents ?? [],
+ blocked: previewQuery.data?.blocked ?? [],
+ };
}
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index 8319904ee7..d874ddec56 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -34,9 +34,14 @@ import {
type ToggleCommentReactionVars,
} from "@multica/core/issues/mutations";
import { sortTimelineEntriesAsc } from "@multica/core/issues/timeline-sort";
+import {
+ unhandledCommentTriggerOutcomes,
+ mentionLabelsByTarget,
+} from "@multica/core/issues/comment-trigger-outcomes";
import { useWSEvent, useWSReconnect } from "@multica/core/realtime";
import { toast } from "sonner";
import { useT } from "../../i18n";
+import { blockedShortReasonLabel } from "../blocked-trigger-copy";
type TLCache = TimelineEntry[];
@@ -259,6 +264,39 @@ export function useIssueTimeline(issueId: string, userId?: string) {
// --- Mutation functions ---
+ // The comment saved, but a mention did not clearly trigger (blocked, or an
+ // unknown/future status we must not assume succeeded). Warn instead of a
+ // silent no-op (MUL-4525 §2): the comment IS posted, but N explicitly-named
+ // targets were not triggered.
+ const warnUnhandledTriggers = useCallback(
+ (triggerOutcomes: unknown, content?: string) => {
+ const unhandled = unhandledCommentTriggerOutcomes(triggerOutcomes);
+ if (unhandled.length === 0) return;
+ // Name the target when a single mention was refused — the posted comment's
+ // markup carries the label the user typed (the wire outcome omits it for
+ // enumeration-safety). Several refusals fall back to a count.
+ if (unhandled.length === 1) {
+ const outcome = unhandled[0]!;
+ const name = mentionLabelsByTarget(content ?? "").get(
+ `${outcome.target_type}:${outcome.target_id}`,
+ );
+ if (name) {
+ toast.warning(
+ t(($) => $.comment.posted_partial_trigger_named, {
+ name,
+ reason: blockedShortReasonLabel(outcome.reason_code, t),
+ }),
+ );
+ return;
+ }
+ }
+ toast.warning(
+ t(($) => $.comment.posted_partial_trigger, { count: unhandled.length }),
+ );
+ },
+ [t],
+ );
+
// Returns true on success, false on failure. The composer keeps the user's
// text (editor locked + button spinning) until this settles and clears only
// on success — so a slow send no longer leaves the box full next to an
@@ -267,7 +305,8 @@ export function useIssueTimeline(issueId: string, userId?: string) {
async (content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<boolean> => {
if (!content.trim() || !userId) return false;
try {
- await createComment({ content, attachmentIds, suppressAgentIds });
+ const comment = await createComment({ content, attachmentIds, suppressAgentIds });
+ warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);
return true;
} catch (err) {
toast.error(
@@ -278,20 +317,21 @@ export function useIssueTimeline(issueId: string, userId?: string) {
return false;
}
},
- [userId, createComment, t],
+ [userId, createComment, warnUnhandledTriggers, t],
);
const submitReply = useCallback(
async (parentId: string, content: string, attachmentIds?: string[], suppressAgentIds?: string[]): Promise<boolean> => {
if (!content.trim() || !userId) return false;
try {
- await createComment({
+ const comment = await createComment({
content,
type: "comment",
parentId,
attachmentIds,
suppressAgentIds,
});
+ warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);
return true;
} catch (err) {
toast.error(
@@ -302,13 +342,14 @@ export function useIssueTimeline(issueId: string, userId?: string) {
return false;
}
},
- [userId, createComment, t],
+ [userId, createComment, warnUnhandledTriggers, t],
);
const editComment = useCallback(
async (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => {
try {
- await updateComment({ commentId, content, attachmentIds, suppressAgentIds });
+ const comment = await updateComment({ commentId, content, attachmentIds, suppressAgentIds });
+ warnUnhandledTriggers(comment?.trigger_outcomes, comment?.content);
} catch (err) {
toast.error(
err instanceof Error && err.message
@@ -317,7 +358,7 @@ export function useIssueTimeline(issueId: string, userId?: string) {
);
}
},
- [updateComment, t],
+ [updateComment, warnUnhandledTriggers, t],
);
const deleteComment = useCallback(
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 347ae66e48..e0943124ba 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -74,6 +74,12 @@
"running": "Running...",
"toast_triggered": "Autopilot triggered",
"toast_trigger_failed": "Failed to trigger autopilot",
+ "run_blocked_invocation_not_allowed": "Not triggered — you don't have permission to use this autopilot's agent",
+ "run_blocked_runtime_offline": "Not triggered — the agent's runtime is offline",
+ "run_blocked_target_unavailable": "Not triggered — the agent is unavailable",
+ "run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member",
+ "run_blocked_already_active": "Not triggered — a recent run already covers this",
+ "run_blocked_generic": "Not triggered — the run was blocked",
"section_properties": "Properties",
"section_triggers": "Triggers",
"section_run_history": "Run History",
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 1aae491205..5b7f268fa7 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -19,6 +19,7 @@
"send_tooltip": "Send",
"stop_tooltip": "Stop",
"send_failed_toast": "Failed to send message",
+ "send_blocked_toast": "Message not sent — you no longer have permission to use this agent",
"attachment_bind_failed_toast": "Message sent, but files were not attached. Please try again in a moment.",
"add_tooltip": "Add",
"upload_file": "Image or files"
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 3234e46960..8e40c739df 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -292,6 +292,18 @@
"edit_action": "Edit",
"update_failed": "Failed to update comment",
"send_failed": "Failed to send comment",
+ "posted_partial_trigger_one": "Comment posted, but {{count}} mention wasn't triggered",
+ "posted_partial_trigger_other": "Comment posted, but {{count}} mentions weren't triggered",
+ "posted_partial_trigger_named": "Comment posted, but {{name}} wasn't triggered ({{reason}})",
+ "trigger_blocked_chip_aria": "{{name}} won't be triggered — {{reason}}",
+ "trigger_blocked_invocation_not_allowed": "You don't have permission to use this target",
+ "trigger_blocked_target_unavailable": "This target is unavailable",
+ "trigger_blocked_runtime_offline": "This target's runtime is offline",
+ "trigger_blocked_generic": "This target won't be triggered",
+ "trigger_blocked_short_invocation_not_allowed": "No permission",
+ "trigger_blocked_short_target_unavailable": "Unavailable",
+ "trigger_blocked_short_runtime_offline": "Runtime offline",
+ "trigger_blocked_short_generic": "Won't start",
"send_reply_failed": "Failed to send reply",
"delete_failed": "Failed to delete comment",
"reply_count_one": "{{count}} reply",
@@ -372,6 +384,7 @@
"retry_task_tooltip": "Retry task",
"retry_task_aria": "Retry task",
"retry_failed": "Failed to retry task",
+ "retry_blocked": "Not retried — you don't have permission to use this agent",
"transcript_tooltip": "View transcript",
"cancel_failed": "Failed to cancel task",
"trigger_retry": "Retry",
@@ -390,7 +403,20 @@
"status_running": "Working",
"status_completed": "Completed",
"status_failed": "Failed",
- "status_cancelled": "Cancelled"
+ "status_cancelled": "Cancelled",
+ "attribution": {
+ "on_behalf_of": "on behalf of {{name}}",
+ "someone": "someone",
+ "unattributed": "No responsible member",
+ "source_direct_human": "Direct member action",
+ "source_delegation": "Delegated from another run",
+ "source_comment_source": "From a comment thread",
+ "source_trigger_owner": "Autopilot trigger creator",
+ "source_rule_owner": "Autopilot rule publisher",
+ "source_owner_fallback": "No precise owner — attributed to the agent owner",
+ "source_backfill": "Backfilled attribution",
+ "source_unattributed": "No responsible member resolved"
+ }
},
"terminate_dialog": {
"title": "Stop this task?",
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index 514ebea7a9..94c0af89bc 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -74,6 +74,12 @@
"running": "実行中...",
"toast_triggered": "オートパイロットを実行しました",
"toast_trigger_failed": "オートパイロットを実行できませんでした",
+ "run_blocked_invocation_not_allowed": "実行されませんでした — このオートパイロットのエージェントを使用する権限がありません",
+ "run_blocked_runtime_offline": "実行されませんでした — エージェントのランタイムがオフラインです",
+ "run_blocked_target_unavailable": "実行されませんでした — エージェントを利用できません",
+ "run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした",
+ "run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています",
+ "run_blocked_generic": "実行されませんでした — 実行がブロックされました",
"section_properties": "プロパティ",
"section_triggers": "トリガー",
"section_run_history": "実行履歴",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index a945a93991..75f3277b5f 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -18,6 +18,7 @@
"send_tooltip": "送信",
"stop_tooltip": "停止",
"send_failed_toast": "メッセージを送信できませんでした",
+ "send_blocked_toast": "メッセージは送信されませんでした — このエージェントを使用する権限がありません",
"attachment_bind_failed_toast": "メッセージは送信されましたが、ファイルを添付できませんでした。しばらくしてからもう一度お試しください。",
"add_tooltip": "追加",
"upload_file": "画像・ファイル"
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 6926734aec..216fddfc0e 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -285,6 +285,17 @@
"edit_action": "編集",
"update_failed": "コメントを更新できませんでした",
"send_failed": "コメントを送信できませんでした",
+ "posted_partial_trigger_other": "コメントを投稿しましたが、{{count}} 件のメンションはトリガーされませんでした",
+ "posted_partial_trigger_named": "コメントを投稿しましたが、{{name}} はトリガーされませんでした({{reason}})",
+ "trigger_blocked_chip_aria": "{{name}} はトリガーされません — {{reason}}",
+ "trigger_blocked_invocation_not_allowed": "この対象を使用する権限がありません",
+ "trigger_blocked_target_unavailable": "この対象は利用できません",
+ "trigger_blocked_runtime_offline": "この対象のランタイムがオフラインです",
+ "trigger_blocked_generic": "この対象はトリガーされません",
+ "trigger_blocked_short_invocation_not_allowed": "権限がありません",
+ "trigger_blocked_short_target_unavailable": "利用不可",
+ "trigger_blocked_short_runtime_offline": "ランタイム オフライン",
+ "trigger_blocked_short_generic": "トリガーされません",
"send_reply_failed": "返信を送信できませんでした",
"delete_failed": "コメントを削除できませんでした",
"reply_count_other": "返信 {{count}} 件",
@@ -356,6 +367,7 @@
"retry_task_tooltip": "タスクを再試行",
"retry_task_aria": "タスクを再試行",
"retry_failed": "タスクを再試行できませんでした",
+ "retry_blocked": "再試行されませんでした — このエージェントを使用する権限がありません",
"transcript_tooltip": "トランスクリプトを表示",
"cancel_failed": "タスクをキャンセルできませんでした",
"trigger_retry": "再試行",
@@ -373,7 +385,20 @@
"status_running": "作業中",
"status_completed": "完了",
"status_failed": "失敗",
- "status_cancelled": "キャンセル済み"
+ "status_cancelled": "キャンセル済み",
+ "attribution": {
+ "on_behalf_of": "{{name}} の代理として",
+ "someone": "あるメンバー",
+ "unattributed": "責任メンバーなし",
+ "source_direct_human": "メンバーの直接操作",
+ "source_delegation": "別の実行から委任",
+ "source_comment_source": "コメントスレッドから",
+ "source_trigger_owner": "オートパイロットのトリガー作成者",
+ "source_rule_owner": "オートパイロットのルール公開者",
+ "source_owner_fallback": "正確な責任者なし — エージェント所有者に帰属",
+ "source_backfill": "バックフィルされた帰属",
+ "source_unattributed": "責任メンバーを解決できません"
+ }
},
"terminate_dialog": {
"title": "このタスクを停止しますか?",
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index ddeb199015..736037dab1 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -74,6 +74,12 @@
"running": "실행 중...",
"toast_triggered": "오토파일럿을 실행했습니다",
"toast_trigger_failed": "오토파일럿을 실행하지 못했습니다",
+ "run_blocked_invocation_not_allowed": "실행되지 않음 — 이 오토파일럿의 에이전트를 사용할 권한이 없습니다",
+ "run_blocked_runtime_offline": "실행되지 않음 — 에이전트의 런타임이 오프라인입니다",
+ "run_blocked_target_unavailable": "실행되지 않음 — 에이전트를 사용할 수 없습니다",
+ "run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다",
+ "run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다",
+ "run_blocked_generic": "실행되지 않음 — 실행이 차단되었습니다",
"section_properties": "속성",
"section_triggers": "트리거",
"section_run_history": "실행 기록",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 7ac9974f32..aaed57e118 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -18,6 +18,7 @@
"send_tooltip": "보내기",
"stop_tooltip": "중지",
"send_failed_toast": "메시지를 보내지 못했습니다",
+ "send_blocked_toast": "메시지가 전송되지 않았습니다 — 이 에이전트를 사용할 권한이 없습니다",
"attachment_bind_failed_toast": "메시지는 보냈지만 파일이 첨부되지 않았습니다. 잠시 후 다시 시도해 주세요.",
"add_tooltip": "추가",
"upload_file": "이미지 또는 파일"
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 673a0e22aa..646fb29863 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -285,6 +285,17 @@
"edit_action": "수정",
"update_failed": "댓글을 업데이트하지 못했습니다",
"send_failed": "댓글을 보내지 못했습니다",
+ "posted_partial_trigger_other": "댓글이 게시되었지만 {{count}}개의 멘션이 트리거되지 않았습니다",
+ "posted_partial_trigger_named": "댓글이 게시되었지만 {{name}}이(가) 트리거되지 않았습니다 ({{reason}})",
+ "trigger_blocked_chip_aria": "{{name}}은(는) 트리거되지 않습니다 — {{reason}}",
+ "trigger_blocked_invocation_not_allowed": "이 대상을 사용할 권한이 없습니다",
+ "trigger_blocked_target_unavailable": "이 대상을 사용할 수 없습니다",
+ "trigger_blocked_runtime_offline": "이 대상의 런타임이 오프라인입니다",
+ "trigger_blocked_generic": "이 대상은 트리거되지 않습니다",
+ "trigger_blocked_short_invocation_not_allowed": "권한 없음",
+ "trigger_blocked_short_target_unavailable": "사용 불가",
+ "trigger_blocked_short_runtime_offline": "런타임 오프라인",
+ "trigger_blocked_short_generic": "트리거 안 됨",
"send_reply_failed": "답글을 보내지 못했습니다",
"delete_failed": "댓글을 삭제하지 못했습니다",
"reply_count_other": "답글 {{count}}개",
@@ -356,6 +367,7 @@
"retry_task_tooltip": "작업 다시 시도",
"retry_task_aria": "작업 다시 시도",
"retry_failed": "작업을 다시 시도하지 못했습니다",
+ "retry_blocked": "다시 시도되지 않음 — 이 에이전트를 사용할 권한이 없습니다",
"transcript_tooltip": "트랜스크립트 보기",
"cancel_failed": "작업을 취소하지 못했습니다",
"trigger_retry": "다시 시도",
@@ -373,7 +385,20 @@
"status_running": "작업 중",
"status_completed": "완료됨",
"status_failed": "실패함",
- "status_cancelled": "취소됨"
+ "status_cancelled": "취소됨",
+ "attribution": {
+ "on_behalf_of": "{{name}} 님을 대신하여",
+ "someone": "어떤 멤버",
+ "unattributed": "책임 멤버 없음",
+ "source_direct_human": "멤버 직접 작업",
+ "source_delegation": "다른 실행에서 위임됨",
+ "source_comment_source": "댓글 스레드에서",
+ "source_trigger_owner": "오토파일럿 트리거 작성자",
+ "source_rule_owner": "오토파일럿 규칙 게시자",
+ "source_owner_fallback": "정확한 담당자 없음 — 에이전트 소유자에게 귀속",
+ "source_backfill": "백필된 귀속",
+ "source_unattributed": "책임 멤버를 확인할 수 없음"
+ }
},
"terminate_dialog": {
"title": "이 작업을 중지할까요?",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index b514d31963..f5be556639 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -74,6 +74,12 @@
"running": "运行中...",
"toast_triggered": "已触发自动化",
"toast_trigger_failed": "触发自动化失败",
+ "run_blocked_invocation_not_allowed": "未触发——你没有该自动化所用智能体的使用权限",
+ "run_blocked_runtime_offline": "未触发——该智能体的运行时已离线",
+ "run_blocked_target_unavailable": "未触发——该智能体不可用",
+ "run_blocked_attribution": "未触发——无法确定本次运行的负责成员",
+ "run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次",
+ "run_blocked_generic": "未触发——本次运行已被拦截",
"section_properties": "属性",
"section_triggers": "触发器",
"section_run_history": "运行历史",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index b7afa89e56..640def09fa 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -18,6 +18,7 @@
"send_tooltip": "发送",
"stop_tooltip": "停止",
"send_failed_toast": "发送消息失败",
+ "send_blocked_toast": "消息未发送——你已没有该智能体的使用权限",
"attachment_bind_failed_toast": "消息已发送,但文件未能附加。请稍后重试。",
"add_tooltip": "添加",
"upload_file": "图片或文件"
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index c20ab47bf9..762a463783 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -285,6 +285,17 @@
"edit_action": "编辑",
"update_failed": "更新评论失败",
"send_failed": "发送评论失败",
+ "posted_partial_trigger_other": "评论已发布,但有 {{count}} 个提及未触发",
+ "posted_partial_trigger_named": "评论已发布,但 {{name}} 未触发({{reason}})",
+ "trigger_blocked_chip_aria": "{{name}} 不会被触发 —— {{reason}}",
+ "trigger_blocked_invocation_not_allowed": "你没有该目标的使用权限",
+ "trigger_blocked_target_unavailable": "该目标不可用",
+ "trigger_blocked_runtime_offline": "该目标的运行时已离线",
+ "trigger_blocked_generic": "该目标不会被触发",
+ "trigger_blocked_short_invocation_not_allowed": "无使用权限",
+ "trigger_blocked_short_target_unavailable": "不可用",
+ "trigger_blocked_short_runtime_offline": "运行时离线",
+ "trigger_blocked_short_generic": "不会触发",
"send_reply_failed": "发送回复失败",
"delete_failed": "删除评论失败",
"reply_count_other": "{{count}} 条回复",
@@ -356,6 +367,7 @@
"retry_task_tooltip": "重试 task",
"retry_task_aria": "重试 task",
"retry_failed": "重试 task 失败",
+ "retry_blocked": "未重试——你没有该智能体的使用权限",
"transcript_tooltip": "查看记录",
"cancel_failed": "取消 task 失败",
"trigger_retry": "重试",
@@ -373,7 +385,20 @@
"status_running": "处理中",
"status_completed": "已完成",
"status_failed": "失败",
- "status_cancelled": "已取消"
+ "status_cancelled": "已取消",
+ "attribution": {
+ "on_behalf_of": "代表 {{name}}",
+ "someone": "某位成员",
+ "unattributed": "无责任成员",
+ "source_direct_human": "成员直接操作",
+ "source_delegation": "由其他运行委托",
+ "source_comment_source": "来自评论线程",
+ "source_trigger_owner": "Autopilot 触发器创建者",
+ "source_rule_owner": "Autopilot 规则发布者",
+ "source_owner_fallback": "无精确责任人 —— 归到 agent 所有者",
+ "source_backfill": "回填的归因",
+ "source_unattributed": "未解析到责任成员"
+ }
},
"terminate_dialog": {
"title": "确定停止该 task?",
diff --git a/server/cmd/server/autopilot_failure_monitor.go b/server/cmd/server/autopilot_failure_monitor.go
index 3c0cc410e4..14d5f65f17 100644
--- a/server/cmd/server/autopilot_failure_monitor.go
+++ b/server/cmd/server/autopilot_failure_monitor.go
@@ -14,6 +14,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -147,6 +148,17 @@ func tickAutopilotFailureMonitor(ctx context.Context, queries *db.Queries, bus *
continue
}
+ // A system auto-pause is a substantive status change (MUL-4302 §3.4).
+ // Record it as a rule-version publish with a 'system' publisher (no member
+ // actor). Best-effort: the monitor is a background sweep, a paused autopilot
+ // does not dispatch (so this version is never the active version at a real
+ // run — a later member resume would supersede it), and a failed write must
+ // not abort the sweep.
+ if verr := service.RecordAutopilotRuleVersion(ctx, queries, paused, "system", pgtype.UUID{}); verr != nil {
+ slog.Warn("autopilot failure monitor: record rule version failed",
+ "autopilot_id", util.UUIDToString(paused.ID), "error", verr)
+ }
+
failPct := 100.0
if c.TotalRuns > 0 {
failPct = math.Round(float64(c.FailedRuns)/float64(c.TotalRuns)*1000) / 10 // one decimal place
diff --git a/server/cmd/server/comment_at_least_once_test.go b/server/cmd/server/comment_at_least_once_test.go
index 680ea3edff..bc3460369c 100644
--- a/server/cmd/server/comment_at_least_once_test.go
+++ b/server/cmd/server/comment_at_least_once_test.go
@@ -222,8 +222,8 @@ func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *t
}
// Seed a queued task originated by testUserID and triggered by cidA.
if _, err := testPool.Exec(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, originator_user_id)
- VALUES ($1, $2, $3, $4, 'queued', 0, $5)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, $3, $4, 'queued', 0, $5, $5)
`, agentID, runtimeID, issueID, cidA, testUserID); err != nil {
t.Fatalf("seed queued task: %v", err)
}
@@ -234,11 +234,12 @@ func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *t
// A DIFFERENT originator (userB) now MERGES (no gate): trigger repointed to
// cidB, originator re-stamped to userB, cidA preserved as coalesced.
if _, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
- IssueID: pgIssue,
- AgentID: pgAgent,
- NewTriggerCommentID: toPgUUID(t, cidB),
- NewOriginatorUserID: toPgUUID(t, otherUserID),
- NewTriggerSummary: pgtype.Text{String: "second, folds in", Valid: true},
+ IssueID: pgIssue,
+ AgentID: pgAgent,
+ NewTriggerCommentID: toPgUUID(t, cidB),
+ NewOriginatorUserID: toPgUUID(t, otherUserID),
+ NewAccountableUserID: toPgUUID(t, otherUserID),
+ NewTriggerSummary: pgtype.Text{String: "second, folds in", Valid: true},
}); err != nil {
t.Fatalf("recompute merge should succeed for a different originator, got %v", err)
}
@@ -260,11 +261,12 @@ func TestMergeCommentIntoPendingTask_RecomputesOriginatorAndSkipsDispatched(t *t
}
cidC := insertCommentAt(t, issueID, "member", testUserID, "third, arrives after dispatch", now)
if _, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
- IssueID: pgIssue,
- AgentID: pgAgent,
- NewTriggerCommentID: toPgUUID(t, cidC),
- NewOriginatorUserID: toPgUUID(t, testUserID),
- NewTriggerSummary: pgtype.Text{String: "third", Valid: true},
+ IssueID: pgIssue,
+ AgentID: pgAgent,
+ NewTriggerCommentID: toPgUUID(t, cidC),
+ NewOriginatorUserID: toPgUUID(t, testUserID),
+ NewAccountableUserID: toPgUUID(t, testUserID),
+ NewTriggerSummary: pgtype.Text{String: "third", Valid: true},
}); err != pgx.ErrNoRows {
t.Fatalf("merge into a dispatched task must return pgx.ErrNoRows, got %v", err)
}
@@ -365,11 +367,12 @@ func TestMergeCommentIntoPendingTask_TargetsQueuedNotDeferred(t *testing.T) {
}
row, err := queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
- IssueID: toPgUUID(t, issueID),
- AgentID: toPgUUID(t, agentID),
- NewTriggerCommentID: toPgUUID(t, cidNew),
- NewOriginatorUserID: toPgUUID(t, testUserID),
- NewTriggerSummary: pgtype.Text{String: "new comment", Valid: true},
+ IssueID: toPgUUID(t, issueID),
+ AgentID: toPgUUID(t, agentID),
+ NewTriggerCommentID: toPgUUID(t, cidNew),
+ NewOriginatorUserID: toPgUUID(t, testUserID),
+ NewAccountableUserID: toPgUUID(t, testUserID),
+ NewTriggerSummary: pgtype.Text{String: "new comment", Valid: true},
})
if err != nil {
t.Fatalf("merge should target the queued task, got %v", err)
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index 3ef5632ba9..48486a43ad 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -407,7 +407,7 @@ func TestRerunIssueSetsForceFreshSession(t *testing.T) {
bus := events.New()
taskService := service.NewTaskService(queries, nil, hub, bus)
- task, err := taskService.RerunIssue(ctx, pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true}, pgtype.UUID{}, pgtype.UUID{})
+ task, err := taskService.RerunIssue(ctx, pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true}, pgtype.UUID{}, pgtype.UUID{}, pgtype.UUID{}, nil)
if err != nil {
t.Fatalf("RerunIssue failed: %v", err)
}
@@ -482,6 +482,8 @@ func TestRerunIssueTargetsSourceTaskAgent(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},
pgtype.UUID{Bytes: parseUUIDBytes(sourceTaskID), Valid: true},
pgtype.UUID{},
+ pgtype.UUID{},
+ nil,
)
if err != nil {
t.Fatalf("RerunIssue failed: %v", err)
@@ -553,6 +555,8 @@ func TestRerunIssueRejectsCrossIssueTask(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(issueAID), Valid: true},
pgtype.UUID{Bytes: parseUUIDBytes(crossTaskID), Valid: true},
pgtype.UUID{},
+ pgtype.UUID{},
+ nil,
)
if err == nil {
t.Fatal("expected RerunIssue to reject a source task from a different issue")
@@ -616,6 +620,8 @@ func TestRerunIssueInheritsTriggerCommentFromSourceTask(t *testing.T) {
pgtype.UUID{Bytes: parseUUIDBytes(issueID), Valid: true},
pgtype.UUID{Bytes: parseUUIDBytes(sourceTaskID), Valid: true},
pgtype.UUID{},
+ pgtype.UUID{},
+ nil,
)
if err != nil {
t.Fatalf("RerunIssue failed: %v", err)
diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.go
new file mode 100644
index 0000000000..3f7c0a0349
--- /dev/null
+++ b/server/internal/attribution/attribution.go
@@ -0,0 +1,414 @@
+// Package attribution implements the accountable-human resolution contract for
+// agent task runs (MUL-4302, "Human Attribution"). Every run enqueued into
+// agent_task_queue must be traceable to exactly one accountable human, and the
+// attribution must be EXPLAINABLE: it records not just who, but at which
+// waterfall level the human was resolved (a direct member action, a delegation
+// copy across an agent hop, the comment-source chain, an autopilot rule owner,
+// or a degraded owner fallback).
+//
+// This package owns the vocabulary (Source, EvidenceKind, TriggerKind) and the
+// PURE classification rules. The database reads that gather the facts stay in
+// the caller (service.TaskService); the caller passes already-fetched facts
+// into the Classify* functions so the rules remain side-effect-free and fully
+// unit-testable without a database.
+//
+// Hard invariant (MUL-4302 §1.3): attribution is "on behalf of", never blame
+// and never authorization. Nothing in this package is consulted for permission
+// decisions — it labels provenance for visibility, audit, and cost only. In
+// particular the accountable-human value stamped here mirrors the existing
+// originator_user_id, which is computed by the caller; this package never
+// widens or narrows who that human is.
+package attribution
+
+import "github.com/jackc/pgx/v5/pgtype"
+
+// Source is the waterfall level that resolved the accountable human for a run.
+// Stored verbatim in agent_task_queue.originator_source. Kept as free strings
+// (no DB CHECK) so a newly-modeled trigger path can introduce a source without
+// a schema migration (MUL-4302 §7).
+type Source string
+
+const (
+ // SourceDirectHuman — a member's own action enqueued the run (comment,
+ // mention, assign, promote, manual trigger, rerun). The member IS the
+ // accountable human.
+ SourceDirectHuman Source = "direct_human"
+ // SourceDelegation — an agent running on behalf of a human caused the
+ // enqueue (agent @-mentions another agent, agent creates a sub-issue,
+ // stage-completion wakeup). The parent task's accountable human is COPIED,
+ // not chained, so delegation cycles stay harmless (MUL-4302 §3.2).
+ SourceDelegation Source = "delegation"
+ // SourceCommentSource — the issue's standing assignee reacted to an
+ // agent/system-authored comment; the human is resolved through
+ // comment.source_task_id (a special case of delegation, MUL-4302 §3.3).
+ SourceCommentSource Source = "comment_source"
+ // SourceTriggerOwner — an autopilot schedule/webhook trigger enqueued the run;
+ // the accountable human is the member who CREATED that specific trigger (set up
+ // the schedule / registered the webhook). Preferred over rule_owner: a run is
+ // accountable to whoever armed the trigger that fired it, not to whoever last
+ // published the rule (MUL-4302; Bohan's refinement). originator stays NULL — an
+ // autonomous fire carries no human authorization — so this is the same authz-safe
+ // audit-only divergence as rule_owner.
+ SourceTriggerOwner Source = "trigger_owner"
+ // SourceRuleOwner — an autopilot trigger enqueued the run but its creator is not
+ // recoverable (a trigger created before per-trigger creators were recorded); the
+ // accountable human degrades to the publisher of the rule's active version
+ // (MUL-4302 §3.4). Precise, but coarser than trigger_owner.
+ SourceRuleOwner Source = "rule_owner"
+ // SourceOwnerFallback — nothing above resolved a human, so attribution
+ // degrades to the agent owner. This is DEGRADED, not compliance-grade, and
+ // must be surfaced distinctly (MUL-4302 §3.5).
+ SourceOwnerFallback Source = "owner_fallback"
+ // SourceBackfill — a historical row attributed after the fact by the
+ // backfill command; never impersonates a real-time attribution.
+ SourceBackfill Source = "backfill"
+ // SourceUnattributed — no human could be resolved and no fallback was
+ // applied. Distinct from a NULL (pre-migration) source: it is an explicit
+ // "we looked and found no human in the chain" marker.
+ SourceUnattributed Source = "unattributed"
+)
+
+// Precise reports whether src is a compliance-grade (non-degraded) attribution.
+// owner_fallback, backfill, and unattributed are degraded and count against the
+// attribution-coverage health metric (MUL-4302 §9).
+func (src Source) Precise() bool {
+ switch src {
+ case SourceDirectHuman, SourceDelegation, SourceCommentSource, SourceTriggerOwner, SourceRuleOwner:
+ return true
+ default:
+ return false
+ }
+}
+
+// String returns the raw source label (defaults to unattributed when empty) so
+// callers never stamp a zero value.
+func (src Source) String() string {
+ if src == "" {
+ return string(SourceUnattributed)
+ }
+ return string(src)
+}
+
+// EvidenceKind tags the direct cause of a run so every attribution can jump to
+// its evidence row. Free strings, paired with an evidence ref id.
+type EvidenceKind string
+
+const (
+ EvidenceComment EvidenceKind = "comment"
+ EvidenceIssueAssignment EvidenceKind = "issue_assignment"
+ EvidenceAutopilotRun EvidenceKind = "autopilot_run"
+ EvidenceRuleVersion EvidenceKind = "rule_version"
+ EvidenceRerun EvidenceKind = "rerun"
+ // EvidenceChat points the uniform evidence pair at the chat session that
+ // triggered the run — the chat analogue of autopilot_run/issue_assignment.
+ // The dedicated chat_session_id column still exists for its own consumers;
+ // this makes the attribution UI's jump-to-evidence path uniform (MUL-4302 §2).
+ EvidenceChat EvidenceKind = "chat"
+)
+
+// TriggerKind enumerates every path that can enqueue a run. Kept as an explicit
+// taxonomy so that adding a new trigger path is a visible, deliberate change
+// that has to declare its attribution rule (MUL-4302 §2 architecture
+// invariant: no enqueue path may exist without a declared attribution).
+type TriggerKind string
+
+const (
+ KindMemberComment TriggerKind = "member_comment"
+ KindMemberMention TriggerKind = "member_mention"
+ KindMemberAssign TriggerKind = "member_assign"
+ KindAgentMention TriggerKind = "agent_mention"
+ KindAgentComment TriggerKind = "agent_comment"
+ KindSubIssueCreate TriggerKind = "sub_issue_create"
+ KindStageWakeup TriggerKind = "stage_wakeup"
+ KindQuickCreate TriggerKind = "quick_create"
+ KindChat TriggerKind = "chat"
+ KindAutopilotSchedule TriggerKind = "autopilot_schedule"
+ KindAutopilotWebhook TriggerKind = "autopilot_webhook"
+ KindAutopilotManual TriggerKind = "autopilot_manual"
+ KindRetry TriggerKind = "retry"
+ KindRerun TriggerKind = "rerun"
+ KindDeferredFallback TriggerKind = "deferred_fallback"
+)
+
+// Result is the attribution stamped onto a queued run.
+//
+// - UserID is the AUTHORIZATION human the caller writes into
+// originator_user_id. It is the value canInvokeAgent and the Composio overlay
+// read; it is legitimately invalid (NULL) when no human authorized the run.
+// - AccountableUserID is the AUDIT human written into accountable_user_id. The
+// one-way invariant (enforced by finalizeAttribution): when UserID is valid,
+// AccountableUserID equals it. When UserID is NULL (no human authorized the
+// run), the two may diverge — rule_owner names the rule publisher and
+// owner_fallback names the agent owner as the accountable human while
+// authorization correctly carries none.
+//
+// The remaining fields are audit metadata written into the Phase 1 provenance
+// columns. Construct a Result through ClassifyComment / ClassifyDirect /
+// DirectHumanRun / Unattributed / RuleOwner so AccountableUserID is always
+// finalized; never stamp a hand-built literal onto the queue.
+type Result struct {
+ UserID pgtype.UUID
+ AccountableUserID pgtype.UUID
+ Source Source
+ DelegatedFromTaskID pgtype.UUID
+ RuleVersionID pgtype.UUID
+ RetryOfTaskID pgtype.UUID
+ RerunOfTaskID pgtype.UUID
+ EvidenceKind EvidenceKind
+ EvidenceRefID pgtype.UUID
+}
+
+// finalizeAttribution enforces the one-way Phase 1 accountability invariant
+// (MUL-4302 §11): a resolved originator IS the accountable human, so
+// `originator_user_id IS NOT NULL ⟹ accountable_user_id = originator_user_id`.
+// Every Result flows through here. It mirrors UserID onto AccountableUserID
+// whenever UserID is valid; when UserID is NULL (no human authorized the run) it
+// leaves AccountableUserID exactly as the caller set it — the single divergence
+// point where rule_owner (rule publisher) and owner_fallback (agent owner) name an
+// accountable human for audit while authorization correctly carries none. The
+// enqueue call sites never special-case this.
+func finalizeAttribution(r Result) Result {
+ if r.UserID.Valid {
+ r.AccountableUserID = r.UserID
+ }
+ return r
+}
+
+// CommentFacts are the already-fetched facts about a trigger comment, gathered
+// by the caller from the DB and passed in so classification stays pure.
+type CommentFacts struct {
+ CommentID pgtype.UUID
+ AuthorType string // "member" | "agent" | other
+ AuthorID pgtype.UUID
+
+ // For agent-authored comments: the source task the comment was written
+ // from (comment.source_task_id) and that task's originator_user_id. The
+ // caller resolves ParentOriginator by loading the source task; it is left
+ // invalid when the source task is missing or itself unattributed.
+ SourceTaskID pgtype.UUID
+ ParentOriginator pgtype.UUID
+
+ // ParentAccountable is the source task's accountable_user_id (MUL-4302 §3.2).
+ // It lets an autopilot-rooted chain — where the parent has NO authorizing human
+ // (ParentOriginator NULL) but IS accountable to someone (trigger creator / rule
+ // publisher) — copy that responsible human down the delegation, instead of
+ // dropping the chain root to unattributed. Loaded by the caller alongside
+ // ParentOriginator; invalid when the parent has no accountable human either.
+ ParentAccountable pgtype.UUID
+}
+
+// ClassifyComment resolves attribution for a comment-triggered run from
+// already-fetched comment facts. agentAuthoredSource selects the label used
+// when the trigger comment is agent-authored: SourceCommentSource for the
+// issue-assignee-reacting path, SourceDelegation for an explicit mention /
+// thread-parent / squad-leader path. The returned UserID is byte-identical to
+// the legacy originator resolution so authorization behavior is unchanged.
+func ClassifyComment(f CommentFacts, agentAuthoredSource Source) Result {
+ switch f.AuthorType {
+ case "member":
+ return finalizeAttribution(Result{
+ UserID: f.AuthorID,
+ Source: SourceDirectHuman,
+ EvidenceKind: EvidenceComment,
+ EvidenceRefID: f.CommentID,
+ })
+ case "agent":
+ r := Result{EvidenceKind: EvidenceComment, EvidenceRefID: f.CommentID}
+ if !f.SourceTaskID.Valid {
+ // Agent comment with no source task: cannot walk the chain.
+ r.Source = SourceUnattributed
+ return finalizeAttribution(r)
+ }
+ r.DelegatedFromTaskID = f.SourceTaskID
+ if f.ParentOriginator.Valid {
+ r.UserID = f.ParentOriginator
+ r.Source = agentAuthoredSource
+ } else if f.ParentAccountable.Valid {
+ // The parent had no authorizing human (autopilot-rooted chain:
+ // originator NULL, accountable = trigger creator / rule publisher) but
+ // IS accountable to someone. Copy that accountable down so the
+ // responsibility chain root stays stable at any depth (MUL-4302 §3.2);
+ // originator stays NULL so authorization is unchanged and a fail-closed
+ // workspace does not reject a fan-out that has a precise responsible human.
+ r.AccountableUserID = f.ParentAccountable
+ r.Source = agentAuthoredSource
+ } else {
+ // Source task exists but has no human at its own top of chain.
+ r.Source = SourceUnattributed
+ }
+ return finalizeAttribution(r)
+ default:
+ return finalizeAttribution(Result{Source: SourceUnattributed, EvidenceKind: EvidenceComment, EvidenceRefID: f.CommentID})
+ }
+}
+
+// DirectFacts are the facts for a run with no trigger comment: a direct issue
+// assignment/creation, or an agent-created issue with a quick-create origin.
+type DirectFacts struct {
+ IssueID pgtype.UUID
+ CreatorType string
+ CreatorID pgtype.UUID
+
+ // ActorUserID is the member who PERFORMED the action that enqueued this run
+ // (assigned the issue, promoted the backlog child, created-with-assignee).
+ // When valid it is the accountable human per MUL-4302 §4 ("执行 assign /
+ // promote 的成员") and takes precedence over the issue creator: the person who
+ // acted, not whoever happened to file the issue, is on the hook. Left invalid
+ // by non-actor paths (comment chain, rerun, autopilot) which resolve the human
+ // elsewhere and fall back to the creator. Because a direct action is the human
+ // lending authority, the actor becomes BOTH originator (authorization) and
+ // accountable — finalizeAttribution keeps them equal, honoring the invariant.
+ ActorUserID pgtype.UUID
+
+ // OriginType/OriginTaskID describe an agent-created issue's provenance
+ // ("quick_create" or "agent_create"); OriginOriginator is that origin task's
+ // originator_user_id, loaded by the caller. Empty OriginType means none.
+ OriginType string
+ OriginTaskID pgtype.UUID
+ OriginOriginator pgtype.UUID
+
+ // OriginAccountable is the origin task's accountable_user_id — the DirectFacts
+ // analogue of CommentFacts.ParentAccountable (MUL-4302 §3.2). An agent-created
+ // sub-issue whose origin task is autopilot-rooted (OriginOriginator NULL,
+ // accountable set) inherits that accountable via delegation instead of dropping
+ // to unattributed.
+ OriginAccountable pgtype.UUID
+}
+
+// ClassifyDirect resolves attribution for a run with no trigger comment.
+func ClassifyDirect(f DirectFacts) Result {
+ // A member who directly assigned/promoted the issue is the accountable human,
+ // ahead of the issue's creator (MUL-4302 §4). Evidence points at the issue the
+ // action targeted.
+ if f.ActorUserID.Valid {
+ return finalizeAttribution(Result{
+ UserID: f.ActorUserID,
+ Source: SourceDirectHuman,
+ EvidenceKind: EvidenceIssueAssignment,
+ EvidenceRefID: f.IssueID,
+ })
+ }
+ if f.CreatorType == "member" && f.CreatorID.Valid {
+ return finalizeAttribution(Result{
+ UserID: f.CreatorID,
+ Source: SourceDirectHuman,
+ EvidenceKind: EvidenceIssueAssignment,
+ EvidenceRefID: f.IssueID,
+ })
+ }
+ switch f.OriginType {
+ case "quick_create", "agent_create":
+ r := Result{
+ DelegatedFromTaskID: f.OriginTaskID,
+ EvidenceKind: EvidenceIssueAssignment,
+ EvidenceRefID: f.IssueID,
+ }
+ if f.OriginOriginator.Valid {
+ r.UserID = f.OriginOriginator
+ r.Source = SourceDelegation
+ } else if f.OriginAccountable.Valid {
+ // Autopilot-rooted origin task: no authorizing human, but accountable
+ // to the trigger creator / rule publisher. Copy accountable down so the
+ // chain root stays stable; originator stays NULL (MUL-4302 §3.2).
+ r.AccountableUserID = f.OriginAccountable
+ r.Source = SourceDelegation
+ } else {
+ r.Source = SourceUnattributed
+ }
+ return finalizeAttribution(r)
+ default:
+ return finalizeAttribution(Result{Source: SourceUnattributed, EvidenceKind: EvidenceIssueAssignment, EvidenceRefID: f.IssueID})
+ }
+}
+
+// DirectHumanRun builds attribution for a run a member triggered directly through
+// a path that carries no issue and no trigger comment — a chat message or a
+// quick-create request. userID is the member who acted (the chat sender / the
+// quick-create requester) and becomes both originator and accountable. An invalid
+// userID (e.g. a Lark group message whose sender could not be resolved) yields an
+// explicit unattributed result rather than a NULL-source bypass.
+func DirectHumanRun(userID pgtype.UUID, evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {
+ if !userID.Valid {
+ return finalizeAttribution(Result{Source: SourceUnattributed, EvidenceKind: evidenceKind, EvidenceRefID: evidenceRefID})
+ }
+ return finalizeAttribution(Result{
+ UserID: userID,
+ Source: SourceDirectHuman,
+ EvidenceKind: evidenceKind,
+ EvidenceRefID: evidenceRefID,
+ })
+}
+
+// Unattributed builds an explicit "no human resolved" result for an enqueue path
+// that currently carries no accountable human — today only the autopilot run_only
+// dispatch, whose precise rule_owner attribution (accountable = the active rule
+// version's publisher) lands with the rule-version snapshot table in a later
+// Phase 1 increment. Stamping SourceUnattributed with real evidence keeps the row
+// off the NULL-source bypass and distinguishes "classified, no human" from a
+// pre-migration NULL, while leaving originator/accountable NULL so authorization
+// still correctly says "no human authorized this run".
+func Unattributed(evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {
+ return finalizeAttribution(Result{Source: SourceUnattributed, EvidenceKind: evidenceKind, EvidenceRefID: evidenceRefID})
+}
+
+// RuleOwner builds attribution for an autopilot-triggered run (MUL-4302 §3.4).
+// No human authorized it, so UserID (originator, the authorization value) stays
+// NULL and canInvokeAgent / the Composio overlay keep seeing "no human"; the
+// AUDIT-accountable human is publisherUserID — the member who published the active
+// rule version — which is THE divergence the two-column split exists for
+// (accountable set, originator NULL). ruleVersionID records which snapshot
+// resolved it; evidence points the caller supplies (autopilot_run for run_only,
+// the issue for create_issue). A missing publisher (system-published rule, or no
+// version resolved yet) degrades to unattributed so we never fabricate a human.
+func RuleOwner(publisherUserID, ruleVersionID pgtype.UUID, evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {
+ r := Result{
+ RuleVersionID: ruleVersionID,
+ EvidenceKind: evidenceKind,
+ EvidenceRefID: evidenceRefID,
+ }
+ if publisherUserID.Valid {
+ r.Source = SourceRuleOwner
+ r.AccountableUserID = publisherUserID
+ } else {
+ r.Source = SourceUnattributed
+ }
+ return finalizeAttribution(r)
+}
+
+// TriggerOwner builds attribution for an autopilot schedule/webhook run keyed to
+// the human who created the firing trigger (MUL-4302; Bohan's refinement). Like
+// RuleOwner, no human authorized the run, so UserID (originator) stays NULL and
+// only the audit-accountable side is set — to creatorUserID, the trigger's member
+// creator. Evidence is caller-supplied (autopilot_run for run_only, the issue for
+// create_issue). An invalid creator degrades to unattributed so callers that lost
+// the creator fall back to rule_owner rather than fabricating a human.
+func TriggerOwner(creatorUserID pgtype.UUID, evidenceKind EvidenceKind, evidenceRefID pgtype.UUID) Result {
+ r := Result{
+ EvidenceKind: evidenceKind,
+ EvidenceRefID: evidenceRefID,
+ }
+ if creatorUserID.Valid {
+ r.Source = SourceTriggerOwner
+ r.AccountableUserID = creatorUserID
+ } else {
+ r.Source = SourceUnattributed
+ }
+ return finalizeAttribution(r)
+}
+
+// OwnerFallback degrades an UNATTRIBUTED result to owner_fallback (MUL-4302 §3.5):
+// the agent owner becomes the accountable human so no run is left without one, but
+// this is a DEGRADED label (Source.Precise() == false) and must be surfaced
+// distinctly in reporting. It is audit-only — originator (UserID) stays NULL, so
+// authorization is unaffected. Applied at the enqueue boundary ONLY when the
+// resolved source is unattributed and the workspace has not opted into fail-closed;
+// a precise result, or an invalid ownerUserID (nothing to fall back to), passes
+// through unchanged so a human is never fabricated.
+func OwnerFallback(r Result, ownerUserID pgtype.UUID) Result {
+ if r.Source != SourceUnattributed || !ownerUserID.Valid {
+ return r
+ }
+ r.Source = SourceOwnerFallback
+ r.AccountableUserID = ownerUserID
+ return r
+}
diff --git a/server/internal/attribution/attribution_test.go b/server/internal/attribution/attribution_test.go
new file mode 100644
index 0000000000..155c43c232
--- /dev/null
+++ b/server/internal/attribution/attribution_test.go
@@ -0,0 +1,497 @@
+package attribution
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// uid builds a valid, deterministic pgtype.UUID from a single seed byte so the
+// tests can assert on identity without importing the util package.
+func uid(seed byte) pgtype.UUID {
+ var u pgtype.UUID
+ for i := range u.Bytes {
+ u.Bytes[i] = seed
+ }
+ u.Valid = true
+ return u
+}
+
+var (
+ human = uid(0x11)
+ other = uid(0x22)
+ comment = uid(0xC0)
+ srcTask = uid(0x5A)
+ issue = uid(0x15)
+ originTk = uid(0x0A)
+ ruleVer = uid(0x4E)
+)
+
+func TestClassifyComment_MemberAuthoredIsDirectHuman(t *testing.T) {
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "member",
+ AuthorID: human,
+ }, SourceCommentSource)
+
+ if got.Source != SourceDirectHuman {
+ t.Fatalf("source = %q, want direct_human", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("accountable user mismatch")
+ }
+ if got.EvidenceKind != EvidenceComment || got.EvidenceRefID != comment {
+ t.Errorf("evidence = %q/%v, want comment/%v", got.EvidenceKind, got.EvidenceRefID, comment)
+ }
+ if got.DelegatedFromTaskID.Valid {
+ t.Errorf("member-authored comment must not set delegated_from")
+ }
+}
+
+func TestClassifyComment_AgentAuthoredInheritsParentAsDelegation(t *testing.T) {
+ // Explicit mention path: an agent @-mentions another agent → delegation,
+ // copying the parent task's human and recording the delegation source task.
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "agent",
+ AuthorID: other,
+ SourceTaskID: srcTask,
+ ParentOriginator: human,
+ }, SourceDelegation)
+
+ if got.Source != SourceDelegation {
+ t.Fatalf("source = %q, want delegation", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("delegation must copy the parent's human, got %v", got.UserID)
+ }
+ if got.DelegatedFromTaskID != srcTask {
+ t.Errorf("delegated_from = %v, want %v", got.DelegatedFromTaskID, srcTask)
+ }
+}
+
+func TestClassifyComment_AutopilotRootedParentInheritsAccountableOnly(t *testing.T) {
+ // The parent task is autopilot-rooted: it has NO authorizing human
+ // (ParentOriginator NULL) but IS accountable to the trigger creator
+ // (ParentAccountable = human). Delegating from it must copy accountable down —
+ // keeping the chain root stable and precise — while leaving originator NULL so
+ // authorization is unchanged and a fail-closed workspace does not reject the
+ // fan-out (MUL-4302 §3.2).
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "agent",
+ SourceTaskID: srcTask,
+ ParentAccountable: human,
+ }, SourceDelegation)
+
+ if got.Source != SourceDelegation {
+ t.Fatalf("source = %q, want delegation (not unattributed)", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("originator must stay NULL (autopilot-rooted, no human authorized), got %v", got.UserID)
+ }
+ if got.AccountableUserID != human {
+ t.Errorf("accountable must inherit the parent's trigger creator, got %v", got.AccountableUserID)
+ }
+ if !got.Source.Precise() {
+ t.Errorf("delegation is a precise source; fail-closed must not reject it")
+ }
+ if got.DelegatedFromTaskID != srcTask {
+ t.Errorf("delegated_from = %v, want %v", got.DelegatedFromTaskID, srcTask)
+ }
+}
+
+func TestClassifyDirect_AutopilotRootedOriginInheritsAccountableOnly(t *testing.T) {
+ // agent_create sub-issue whose origin task is autopilot-rooted: inherit the
+ // origin's accountable via delegation, originator stays NULL.
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ OriginType: "agent_create",
+ OriginTaskID: srcTask,
+ OriginAccountable: human,
+ })
+
+ if got.Source != SourceDelegation {
+ t.Fatalf("source = %q, want delegation (not unattributed)", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("originator must stay NULL, got %v", got.UserID)
+ }
+ if got.AccountableUserID != human {
+ t.Errorf("accountable must inherit the origin's accountable, got %v", got.AccountableUserID)
+ }
+}
+
+func TestClassifyComment_AgentAuthoredUsesCommentSourceLabelForAssigneePath(t *testing.T) {
+ // Same facts, but the issue-assignee-reacting path passes comment_source.
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "agent",
+ SourceTaskID: srcTask,
+ ParentOriginator: human,
+ }, SourceCommentSource)
+
+ if got.Source != SourceCommentSource {
+ t.Fatalf("source = %q, want comment_source", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("comment_source must inherit the parent's human")
+ }
+}
+
+func TestClassifyComment_AgentAuthoredNoSourceTaskIsUnattributed(t *testing.T) {
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "agent",
+ }, SourceDelegation)
+
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("no source task must yield no human")
+ }
+}
+
+func TestClassifyComment_AgentAuthoredParentWithoutHumanIsUnattributed(t *testing.T) {
+ // Source task exists but has no human at its own top of chain (e.g. an
+ // autopilot-originated parent). Must not fabricate a human, but should still
+ // record the delegation lineage for evidence.
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "agent",
+ SourceTaskID: srcTask,
+ }, SourceDelegation)
+
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("must not fabricate a human when the parent has none")
+ }
+ if got.DelegatedFromTaskID != srcTask {
+ t.Errorf("delegation lineage should still be recorded as evidence")
+ }
+}
+
+func TestClassifyComment_SystemAuthoredIsUnattributed(t *testing.T) {
+ got := ClassifyComment(CommentFacts{
+ CommentID: comment,
+ AuthorType: "system",
+ }, SourceCommentSource)
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+}
+
+func TestClassifyDirect_MemberCreatorIsDirectHuman(t *testing.T) {
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "member",
+ CreatorID: human,
+ })
+ if got.Source != SourceDirectHuman {
+ t.Fatalf("source = %q, want direct_human", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("member-created issue must attribute to its creator")
+ }
+ if got.EvidenceKind != EvidenceIssueAssignment || got.EvidenceRefID != issue {
+ t.Errorf("evidence should point at the issue")
+ }
+}
+
+func TestClassifyDirect_QuickCreateInheritsOriginAsDelegation(t *testing.T) {
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ OriginType: "quick_create",
+ OriginTaskID: originTk,
+ OriginOriginator: human,
+ })
+ if got.Source != SourceDelegation {
+ t.Fatalf("source = %q, want delegation", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("quick-create issue must inherit the origin task's human")
+ }
+ if got.DelegatedFromTaskID != originTk {
+ t.Errorf("delegated_from = %v, want %v", got.DelegatedFromTaskID, originTk)
+ }
+}
+
+func TestClassifyDirect_QuickCreateWithoutHumanIsUnattributed(t *testing.T) {
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ OriginType: "quick_create",
+ OriginTaskID: originTk,
+ })
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("must not fabricate a human")
+ }
+}
+
+func TestClassifyDirect_AgentCreatedNoOriginIsUnattributed(t *testing.T) {
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ })
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("agent-created issue with no origin has no human")
+ }
+}
+
+func TestClassifyDirect_ActorOverridesCreator(t *testing.T) {
+ // A member directly assigned/promoted an issue someone else created: the
+ // acting member is accountable, ahead of the creator (MUL-4302 §4).
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "member",
+ CreatorID: other,
+ ActorUserID: human,
+ })
+ if got.Source != SourceDirectHuman {
+ t.Fatalf("source = %q, want direct_human", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("actor should be attributed, got %v want %v", got.UserID, human)
+ }
+ if got.EvidenceKind != EvidenceIssueAssignment || got.EvidenceRefID != issue {
+ t.Errorf("evidence should point at the assigned issue")
+ }
+}
+
+func TestClassifyDirect_ActorOverridesAgentOriginInheritance(t *testing.T) {
+ // Even when the issue carries an agent origin link, a real member actor wins:
+ // a human directly acted on it, so we do not fall through to origin delegation.
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ OriginType: "agent_create",
+ OriginTaskID: originTk,
+ OriginOriginator: other,
+ ActorUserID: human,
+ })
+ if got.Source != SourceDirectHuman {
+ t.Fatalf("source = %q, want direct_human", got.Source)
+ }
+ if got.UserID != human {
+ t.Errorf("actor should win over origin inheritance, got %v", got.UserID)
+ }
+ if got.DelegatedFromTaskID.Valid {
+ t.Errorf("actor path is not a delegation; delegated_from must stay empty")
+ }
+}
+
+func TestClassifyDirect_AgentCreateInheritsOriginAsDelegation(t *testing.T) {
+ // agent_create (an agent's ordinary `issue create`, MUL-4305) inherits the
+ // origin task's human exactly like quick_create.
+ got := ClassifyDirect(DirectFacts{
+ IssueID: issue,
+ CreatorType: "agent",
+ OriginType: "agent_create",
+ OriginTaskID: originTk,
+ OriginOriginator: human,
+ })
+ if got.Source != SourceDelegation {
+ t.Fatalf("source = %q, want delegation", got.Source)
+ }
+ if got.UserID != human || got.DelegatedFromTaskID != originTk {
+ t.Errorf("agent_create must inherit origin human + lineage")
+ }
+}
+
+// TestAccountableMirrorsOriginatorInvariant is the MUL-4302 §11 acceptance check
+// at the classification layer: EVERY result the resolver produces must satisfy the
+// ONE-WAY invariant `originator (UserID) IS NOT NULL ⟹ accountable == originator`.
+// When UserID is NULL the two MAY diverge (rule_owner / owner_fallback name an
+// accountable human while authorization carries none), so the invariant only
+// constrains the valid-originator direction. finalizeAttribution centralizes this;
+// the test guards against a future Classify path forgetting to route through it.
+func TestAccountableMirrorsOriginatorInvariant(t *testing.T) {
+ results := []Result{
+ ClassifyComment(CommentFacts{CommentID: comment, AuthorType: "member", AuthorID: human}, SourceCommentSource),
+ ClassifyComment(CommentFacts{CommentID: comment, AuthorType: "agent", SourceTaskID: srcTask, ParentOriginator: human}, SourceDelegation),
+ ClassifyComment(CommentFacts{CommentID: comment, AuthorType: "agent"}, SourceDelegation),
+ ClassifyComment(CommentFacts{CommentID: comment, AuthorType: "system"}, SourceCommentSource),
+ ClassifyDirect(DirectFacts{IssueID: issue, CreatorType: "member", CreatorID: human}),
+ ClassifyDirect(DirectFacts{IssueID: issue, CreatorType: "member", CreatorID: other, ActorUserID: human}),
+ ClassifyDirect(DirectFacts{IssueID: issue, CreatorType: "agent", OriginType: "quick_create", OriginTaskID: originTk, OriginOriginator: human}),
+ ClassifyDirect(DirectFacts{IssueID: issue, CreatorType: "agent"}),
+ DirectHumanRun(human, EvidenceComment, comment),
+ DirectHumanRun(pgtype.UUID{}, "", pgtype.UUID{}),
+ Unattributed(EvidenceAutopilotRun, srcTask),
+ RuleOwner(human, ruleVer, EvidenceAutopilotRun, srcTask), // divergent: accountable set, originator NULL
+ RuleOwner(pgtype.UUID{}, ruleVer, EvidenceAutopilotRun, srcTask), // no publisher → unattributed
+ }
+ for i, r := range results {
+ // One-way invariant: a valid originator must equal accountable.
+ if r.UserID.Valid && r.AccountableUserID != r.UserID {
+ t.Errorf("result[%d]: originator %v valid but accountable %v differs — invariant violated", i, r.UserID, r.AccountableUserID)
+ }
+ // Authorization must never be forged from the audit side: a non-NULL
+ // accountable with a NULL originator is allowed (divergence), but the
+ // reverse — originator set from accountable — must never happen implicitly.
+ if r.AccountableUserID.Valid && !r.UserID.Valid &&
+ r.Source != SourceRuleOwner && r.Source != SourceTriggerOwner && r.Source != SourceOwnerFallback &&
+ r.Source != SourceDelegation && r.Source != SourceCommentSource {
+ t.Errorf("result[%d]: accountable set with NULL originator only allowed for delegation/comment_source/trigger_owner/rule_owner/owner_fallback, got source=%q", i, r.Source)
+ }
+ }
+}
+
+func TestDirectHumanRun(t *testing.T) {
+ got := DirectHumanRun(human, EvidenceComment, comment)
+ if got.Source != SourceDirectHuman || got.UserID != human || got.AccountableUserID != human {
+ t.Errorf("valid member should be a direct_human originator+accountable, got %+v", got)
+ }
+ if got.EvidenceKind != EvidenceComment || got.EvidenceRefID != comment {
+ t.Errorf("evidence should be carried through")
+ }
+
+ unresolved := DirectHumanRun(pgtype.UUID{}, "", pgtype.UUID{})
+ if unresolved.Source != SourceUnattributed {
+ t.Errorf("invalid user must degrade to unattributed, got %q", unresolved.Source)
+ }
+ if unresolved.UserID.Valid || unresolved.AccountableUserID.Valid {
+ t.Errorf("invalid user must not fabricate a human")
+ }
+}
+
+func TestRuleOwner(t *testing.T) {
+ // The divergence case: an autopilot run has NO authorizing human (originator
+ // NULL) but IS accountable to the rule publisher.
+ got := RuleOwner(human, ruleVer, EvidenceAutopilotRun, issue)
+ if got.Source != SourceRuleOwner {
+ t.Fatalf("source = %q, want rule_owner", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("rule_owner must NOT set originator (authorization stays NULL), got %v", got.UserID)
+ }
+ if got.AccountableUserID != human {
+ t.Errorf("accountable should be the rule publisher, got %v", got.AccountableUserID)
+ }
+ if got.RuleVersionID != ruleVer {
+ t.Errorf("rule_version_id = %v, want %v", got.RuleVersionID, ruleVer)
+ }
+ if got.EvidenceKind != EvidenceAutopilotRun || got.EvidenceRefID != issue {
+ t.Errorf("evidence should be carried through")
+ }
+
+ // No publisher (system-published / unresolved) must not fabricate a human.
+ none := RuleOwner(pgtype.UUID{}, ruleVer, EvidenceAutopilotRun, issue)
+ if none.Source != SourceUnattributed {
+ t.Errorf("missing publisher must degrade to unattributed, got %q", none.Source)
+ }
+ if none.UserID.Valid || none.AccountableUserID.Valid {
+ t.Errorf("missing publisher must carry no human on either side")
+ }
+}
+
+func TestTriggerOwner(t *testing.T) {
+ // The divergence case (MUL-4302; Bohan): an autopilot schedule/webhook run has
+ // NO authorizing human (originator NULL) but IS accountable to the member who
+ // created the firing trigger.
+ got := TriggerOwner(human, EvidenceAutopilotRun, issue)
+ if got.Source != SourceTriggerOwner {
+ t.Fatalf("source = %q, want trigger_owner", got.Source)
+ }
+ if !got.Source.Precise() {
+ t.Errorf("trigger_owner must be a precise source")
+ }
+ if got.UserID.Valid {
+ t.Errorf("trigger_owner must NOT set originator (authorization stays NULL), got %v", got.UserID)
+ }
+ if got.AccountableUserID != human {
+ t.Errorf("accountable should be the trigger creator, got %v", got.AccountableUserID)
+ }
+ if got.EvidenceKind != EvidenceAutopilotRun || got.EvidenceRefID != issue {
+ t.Errorf("evidence should be carried through")
+ }
+
+ // No creator (unrecoverable) must not fabricate a human — degrades to
+ // unattributed so the caller can fall back to rule_owner.
+ none := TriggerOwner(pgtype.UUID{}, EvidenceAutopilotRun, issue)
+ if none.Source != SourceUnattributed {
+ t.Errorf("missing creator must degrade to unattributed, got %q", none.Source)
+ }
+ if none.UserID.Valid || none.AccountableUserID.Valid {
+ t.Errorf("missing creator must carry no human on either side")
+ }
+}
+
+func TestOwnerFallback(t *testing.T) {
+ // Unattributed → owner_fallback: accountable = owner, originator stays NULL,
+ // source is degraded (not precise).
+ base := Unattributed(EvidenceIssueAssignment, issue)
+ got := OwnerFallback(base, other)
+ if got.Source != SourceOwnerFallback {
+ t.Fatalf("source = %q, want owner_fallback", got.Source)
+ }
+ if got.Source.Precise() {
+ t.Errorf("owner_fallback must be a degraded (non-precise) source")
+ }
+ if got.UserID.Valid {
+ t.Errorf("owner_fallback is audit-only; originator must stay NULL")
+ }
+ if got.AccountableUserID != other {
+ t.Errorf("accountable = %v, want owner %v", got.AccountableUserID, other)
+ }
+
+ // Precise results are untouched.
+ precise := ClassifyDirect(DirectFacts{IssueID: issue, CreatorType: "member", CreatorID: human})
+ if OwnerFallback(precise, other) != precise {
+ t.Errorf("owner_fallback must not alter a precise attribution")
+ }
+
+ // Invalid owner → stays unattributed, never fabricates a human.
+ noOwner := OwnerFallback(Unattributed(EvidenceIssueAssignment, issue), pgtype.UUID{})
+ if noOwner.Source != SourceUnattributed || noOwner.AccountableUserID.Valid {
+ t.Errorf("invalid owner must leave the result unattributed with no human, got %+v", noOwner)
+ }
+}
+
+func TestUnattributed(t *testing.T) {
+ got := Unattributed(EvidenceAutopilotRun, srcTask)
+ if got.Source != SourceUnattributed {
+ t.Fatalf("source = %q, want unattributed", got.Source)
+ }
+ if got.UserID.Valid || got.AccountableUserID.Valid {
+ t.Errorf("unattributed must carry no human on either side")
+ }
+ if got.EvidenceKind != EvidenceAutopilotRun || got.EvidenceRefID != srcTask {
+ t.Errorf("evidence should be carried so the row is not a NULL-source bypass")
+ }
+}
+
+func TestSourcePrecise(t *testing.T) {
+ precise := []Source{SourceDirectHuman, SourceDelegation, SourceCommentSource, SourceTriggerOwner, SourceRuleOwner}
+ degraded := []Source{SourceOwnerFallback, SourceBackfill, SourceUnattributed, Source("")}
+ for _, s := range precise {
+ if !s.Precise() {
+ t.Errorf("%q should be precise", s)
+ }
+ }
+ for _, s := range degraded {
+ if s.Precise() {
+ t.Errorf("%q should be degraded", s)
+ }
+ }
+}
+
+func TestSourceStringDefaultsToUnattributed(t *testing.T) {
+ if Source("").String() != string(SourceUnattributed) {
+ t.Errorf("empty source must stringify to unattributed, got %q", Source("").String())
+ }
+ if SourceDirectHuman.String() != "direct_human" {
+ t.Errorf("unexpected string for direct_human: %q", SourceDirectHuman.String())
+ }
+}
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
new file mode 100644
index 0000000000..ea953ac32d
--- /dev/null
+++ b/server/internal/dispatch/reason.go
@@ -0,0 +1,48 @@
+// Package dispatch holds the canonical, cross-layer vocabulary for execution
+// admission outcomes (MUL-4525). It is a leaf package (no internal deps) so both
+// the service layer — which MAKES the admission/skip decision and therefore owns
+// the reason at its source — and the handler layer — which serializes it to the
+// wire — share one enum and can never drift.
+//
+// A ReasonCode is decided at the branch that blocks/skips a run and carried
+// through to the response verbatim; it is never reverse-engineered from a
+// human-readable failure string. Codes are stable, localizable by clients, and
+// enumeration-safe: a code never reveals whether a private agent exists, its
+// name, or its owner.
+package dispatch
+
+// ReasonCode is a stable, client-localizable admission/dispatch reason.
+type ReasonCode string
+
+const (
+ // ReasonQueued / ReasonCoalesced / ReasonDeferred are the success-path codes.
+ ReasonQueued ReasonCode = "queued"
+ ReasonCoalesced ReasonCode = "coalesced"
+ ReasonDeferred ReasonCode = "deferred"
+
+ // ReasonInvocationNotAllowed: the acting principal may not trigger this
+ // target under the invocation-permission model. Deliberately generic — it
+ // does not distinguish "target is private" from "target does not exist".
+ ReasonInvocationNotAllowed ReasonCode = "invocation_not_allowed"
+ // ReasonTargetUnavailable: the target cannot run (archived agent, deleted /
+ // archived squad, unresolvable leader, or no assignee).
+ ReasonTargetUnavailable ReasonCode = "target_unavailable"
+ // ReasonRuntimeOffline: the target is permitted but its runtime is not bound
+ // / not online at dispatch time.
+ ReasonRuntimeOffline ReasonCode = "runtime_offline"
+ // ReasonAttributionBlocked: a fail-closed workspace could not resolve a
+ // responsible human for the run, so it was refused.
+ ReasonAttributionBlocked ReasonCode = "attribution_blocked"
+ // ReasonAlreadyActive: a run is already active/pending for this target and
+ // this trigger did not coalesce.
+ ReasonAlreadyActive ReasonCode = "already_active"
+ // ReasonSelfTriggerSuppressed: the target was intentionally not (re-)triggered
+ // because doing so would be a self-trigger the guard suppresses, and no active
+ // run remains to cover it — e.g. a squad leader's own @mention of its squad
+ // whose latest task is already terminal. Not a permission block, but NOT
+ // success: nothing new runs. (Named to avoid implying the NEW comment was
+ // already processed.)
+ ReasonSelfTriggerSuppressed ReasonCode = "self_trigger_suppressed"
+ // ReasonInternalError: an unexpected server error prevented a clean decision.
+ ReasonInternalError ReasonCode = "internal_error"
+)
diff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.go
new file mode 100644
index 0000000000..1b57b8c0d6
--- /dev/null
+++ b/server/internal/handler/admission.go
@@ -0,0 +1,125 @@
+package handler
+
+import (
+ "net/http"
+
+ "github.com/multica-ai/multica/server/internal/dispatch"
+)
+
+// Unified execution-admission contract (MUL-4525).
+//
+// Every synchronous enqueue entry point (comment mention, autopilot manual
+// "run now", issue assign / promotion / batch, manual rerun, direct chat) needs
+// to answer the SAME question in the SAME shape: given a user who explicitly
+// named an execution target, did the run get `queued`, `coalesced` onto an
+// existing task, `deferred`, or `blocked`? A silent no-op is never acceptable.
+//
+// Two invariants this contract exists to protect:
+//
+// 1. Whether the business object was written (comment saved, issue updated)
+// and whether the agent was actually triggered are DIFFERENT facts. A
+// comment can persist while one of its mentions is blocked — callers must
+// be able to express partial success.
+// 2. The reason a target was blocked is exposed ONLY as a stable, localizable,
+// enumeration-safe code. It must never leak whether a private agent exists,
+// its name, or its owner to a caller who cannot see the target. The precise
+// cause goes to restricted server logs, not the wire.
+
+// DispatchStatus is the domain-level outcome of one admission/enqueue attempt.
+type DispatchStatus string
+
+const (
+ // DispatchQueued: a new run was enqueued.
+ DispatchQueued DispatchStatus = "queued"
+ // DispatchCoalesced: the trigger merged into an already-pending task for
+ // the same target instead of creating a duplicate run.
+ DispatchCoalesced DispatchStatus = "coalesced"
+ // DispatchDeferred: admitted but intentionally not started yet (e.g. a
+ // backlog issue parked until promotion, or suppress_run).
+ DispatchDeferred DispatchStatus = "deferred"
+ // DispatchBlocked: the run was refused. ReasonCode carries why.
+ DispatchBlocked DispatchStatus = "blocked"
+)
+
+// DispatchReasonCode is the wire-facing admission reason. It aliases the
+// canonical, cross-layer enum in the dispatch package so the service (which
+// decides the reason at its source) and the handler (which serializes it) can
+// never drift. New codes may be added; clients must treat an unknown code as a
+// generic failure (they switch with a default branch). A code NEVER encodes the
+// existence, name, or owner of a target the caller is not allowed to see.
+type DispatchReasonCode = dispatch.ReasonCode
+
+const (
+ ReasonQueued = dispatch.ReasonQueued
+ ReasonCoalesced = dispatch.ReasonCoalesced
+ ReasonDeferred = dispatch.ReasonDeferred
+ ReasonInvocationNotAllowed = dispatch.ReasonInvocationNotAllowed
+ ReasonTargetUnavailable = dispatch.ReasonTargetUnavailable
+ ReasonRuntimeOffline = dispatch.ReasonRuntimeOffline
+ ReasonAttributionBlocked = dispatch.ReasonAttributionBlocked
+ ReasonAlreadyActive = dispatch.ReasonAlreadyActive
+ ReasonSelfTriggerSuppressed = dispatch.ReasonSelfTriggerSuppressed
+ ReasonInternalError = dispatch.ReasonInternalError
+)
+
+// DispatchTarget is the caller-visible reference to an execution target. Name
+// is populated ONLY when the caller is allowed to see the target; a blocked
+// private-agent invoke returns Type/ID (already known to the caller from their
+// own request) but never a Name they were not otherwise entitled to.
+type DispatchTarget struct {
+ Type string `json:"type"` // "agent" | "squad"
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+}
+
+// DispatchOutcome is the unified per-target result returned by every sync
+// enqueue entry point. It is additive on the wire: old clients that ignore it
+// keep working. TaskID / RunID are set when a run/task was produced.
+type DispatchOutcome struct {
+ Status DispatchStatus `json:"status"`
+ ReasonCode DispatchReasonCode `json:"reason_code"`
+ Target *DispatchTarget `json:"target,omitempty"`
+ TaskID *string `json:"task_id,omitempty"`
+ RunID *string `json:"run_id,omitempty"`
+}
+
+// dispatchBlockedResponse is the structured body of a blocked synchronous
+// enqueue (403/409). `error` is a generic, non-enumerating English fallback for
+// old clients that only read the legacy field; `reason_code` is the stable
+// machine-readable code new clients localize. Neither field leaks private
+// target details.
+type dispatchBlockedResponse struct {
+ Error string `json:"error"`
+ ReasonCode DispatchReasonCode `json:"reason_code"`
+}
+
+// writeDispatchBlocked writes a structured blocked-admission error. The HTTP
+// status conveys the class (403 permission, 409 conflict); reason_code conveys
+// the stable cause. Use this for any sync trigger the caller explicitly asked
+// for that is refused before mutation.
+func (h *Handler) writeDispatchBlocked(w http.ResponseWriter, status int, code DispatchReasonCode) {
+ writeJSON(w, status, dispatchBlockedResponse{
+ Error: dispatchBlockedFallbackMessage(code),
+ ReasonCode: code,
+ })
+}
+
+// dispatchBlockedFallbackMessage is the legacy `error` string paired with a
+// reason code. It is intentionally generic and non-enumerating: it must be safe
+// to show to a caller who is not allowed to know whether the target exists.
+func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {
+ switch code {
+ case ReasonInvocationNotAllowed:
+ return "you don't have permission to use this target"
+ case ReasonTargetUnavailable:
+ return "the target is unavailable"
+ case ReasonRuntimeOffline:
+ return "the target's runtime is offline"
+ case ReasonAttributionBlocked:
+ return "the run couldn't be attributed to a responsible member"
+ case ReasonAlreadyActive:
+ return "a run is already active for this target"
+ default:
+ return "the run was blocked"
+ }
+}
diff --git a/server/internal/handler/admission_security_mul4525_test.go b/server/internal/handler/admission_security_mul4525_test.go
new file mode 100644
index 0000000000..d28929498e
--- /dev/null
+++ b/server/internal/handler/admission_security_mul4525_test.go
@@ -0,0 +1,280 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/dispatch"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// seedSecurityTestOwner creates a throwaway workspace member to own an agent, so
+// the agent is NOT owned by testUserID (who must be able to VIEW but not INVOKE).
+func seedSecurityTestOwner(t *testing.T, label string) string {
+ t.Helper()
+ ctx := context.Background()
+ var ownerID string
+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ label, fmt.Sprintf("%s-%[email protected]", label, time.Now().UnixNano())).Scan(&ownerID); err != nil {
+ t.Fatalf("seed owner user: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, ownerID) })
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ testWorkspaceID, ownerID); err != nil {
+ t.Fatalf("seed owner member: %v", err)
+ }
+ return ownerID
+}
+
+// readReasonCode pulls the stable reason_code out of a structured blocked-admission
+// response body (MUL-4525).
+func readReasonCode(t *testing.T, body []byte) string {
+ t.Helper()
+ var resp struct {
+ Error string `json:"error"`
+ ReasonCode string `json:"reason_code"`
+ }
+ if err := json.Unmarshal(body, &resp); err != nil {
+ t.Fatalf("decode blocked response: %v (body=%s)", err, string(body))
+ }
+ return resp.ReasonCode
+}
+
+// TestSendChatMessage_InvokeRevokedAfterSessionCreate is the MUL-4525 must-fix 3
+// chat acceptance test: a session created while the user could invoke the agent
+// must stop sending the instant that invoke permission is revoked — even though
+// the user (a workspace owner) can still VIEW the transcript. The refusal is a
+// structured 403 with a stable reason_code, and NOTHING is persisted: no chat
+// message, no task.
+func TestSendChatMessage_InvokeRevokedAfterSessionCreate(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ ownerID := seedSecurityTestOwner(t, "chat-agent-owner")
+
+ // public_to agent owned by someone else, with testUserID on its member
+ // allow-list — so testUserID may invoke it while it is public_to.
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id,
+ instructions, custom_env, custom_args)
+ VALUES ($1, 'chat-revoke-agent', '', 'cloud', '{}'::jsonb, $2, 'private', 'public_to', 1, $3,
+ '', '{}'::jsonb, '[]'::jsonb)
+ RETURNING id`, testWorkspaceID, handlerTestRuntimeID(t), ownerID).Scan(&agentID); err != nil {
+ t.Fatalf("seed agent: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID) })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)
+ VALUES ($1, 'member', $2)`, agentID, testUserID); err != nil {
+ t.Fatalf("seed member invocation target: %v", err)
+ }
+
+ // Create the session as testUserID while they can still invoke the agent.
+ createW := httptest.NewRecorder()
+ createReq := withChatTestWorkspaceCtx(t, newRequest("POST", "/api/chat/sessions", map[string]any{
+ "agent_id": agentID,
+ "title": "revoke test",
+ }))
+ testHandler.CreateChatSession(createW, createReq)
+ if createW.Code != http.StatusCreated {
+ t.Fatalf("CreateChatSession while invokable: expected 201, got %d: %s", createW.Code, createW.Body.String())
+ }
+ var session struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal(createW.Body.Bytes(), &session); err != nil {
+ t.Fatalf("decode session: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, session.ID) })
+
+ // Revoke invoke permission: flip the agent to private. testUserID keeps VIEW
+ // access (workspace owner) but loses INVOKE access (not the agent owner).
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET permission_mode = 'private' WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("revoke invoke: %v", err)
+ }
+
+ // A valid, still-unbound attachment uploaded by the sender. A successful send
+ // would claim it into the session/message (LinkAttachmentsToChatMessage sets
+ // chat_session_id + chat_message_id); the blocked send must not — the invoke
+ // gate runs BEFORE attachment binding, so this guards against anyone later
+ // moving the binding ahead of the permission gate.
+ var attachmentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (workspace_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ VALUES ($1, 'member', $2, 'unbound.png', 'https://cdn.test/unbound.png', 'image/png', 10)
+ RETURNING id`, testWorkspaceID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("seed unbound attachment: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, attachmentID) })
+
+ countMessages := func() int {
+ var n int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1`, session.ID).Scan(&n); err != nil {
+ t.Fatalf("count messages: %v", err)
+ }
+ return n
+ }
+ countTasks := func() int {
+ var n int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, session.ID).Scan(&n); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ return n
+ }
+ if countMessages() != 0 || countTasks() != 0 {
+ t.Fatalf("precondition: session should have no messages/tasks yet")
+ }
+
+ // The send must be refused before anything is written — including the
+ // attachment binding.
+ sendW := httptest.NewRecorder()
+ sendReq := withChatTestWorkspaceCtx(t, newRequest("POST", "/api/chat/sessions/"+session.ID+"/messages", map[string]any{
+ "content": "are you still there?",
+ "attachment_ids": []string{attachmentID},
+ }))
+ sendReq = withURLParam(sendReq, "sessionId", session.ID)
+ testHandler.SendChatMessage(sendW, sendReq)
+
+ if sendW.Code != http.StatusForbidden {
+ t.Fatalf("SendChatMessage after revoke: expected 403, got %d: %s", sendW.Code, sendW.Body.String())
+ }
+ if code := readReasonCode(t, sendW.Body.Bytes()); code != string(dispatch.ReasonInvocationNotAllowed) {
+ t.Errorf("reason_code = %q, want invocation_not_allowed", code)
+ }
+ if got := countMessages(); got != 0 {
+ t.Errorf("blocked send persisted %d chat messages, want 0", got)
+ }
+ if got := countTasks(); got != 0 {
+ t.Errorf("blocked send persisted %d tasks, want 0", got)
+ }
+ // The attachment must remain unbound: neither claimed into the session nor
+ // linked to a message.
+ var boundSession, boundMessage pgtype.UUID
+ if err := testPool.QueryRow(ctx, `SELECT chat_session_id, chat_message_id FROM attachment WHERE id = $1`, attachmentID).
+ Scan(&boundSession, &boundMessage); err != nil {
+ t.Fatalf("read attachment binding: %v", err)
+ }
+ if boundSession.Valid {
+ t.Errorf("blocked send set attachment chat_session_id = %s, want NULL", util.UUIDToString(boundSession))
+ }
+ if boundMessage.Valid {
+ t.Errorf("blocked send set attachment chat_message_id = %s, want NULL", util.UUIDToString(boundMessage))
+ }
+}
+
+// TestRerunIssue_PrivateHistoricalAgent is the MUL-4525 must-fix 3 rerun
+// acceptance test, driven through the REAL handler + canInvokeAgent (not an
+// injected callback): a user who can see the issue but cannot invoke its private
+// agent is refused with a structured 403 and mutates nothing; the agent's owner
+// is allowed.
+func TestRerunIssue_PrivateHistoricalAgent(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, ownerID, _ := privateAgentTestFixture(t) // private agent owned by ownerID
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority)
+ VALUES ($1, 'rerun private agent', 'member', $2, 'agent', $3, 'medium')
+ RETURNING id`, testWorkspaceID, ownerID, agentID).Scan(&issueID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ // A historical task run by the private agent.
+ orig, err := testHandler.TaskService.EnqueueTaskForIssue(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: util.MustParseUUID(ownerID),
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("enqueue original task: %v", err)
+ }
+ origID := util.UUIDToString(orig.ID)
+
+ // Reassign the issue to a SECOND agent that testUserID CAN invoke (a
+ // workspace-invocable public_to agent). Now the issue's CURRENT assignee and
+ // the source task's HISTORICAL agent differ: if the rerun wrongly validated
+ // the current assignee, testUserID would be allowed — so the 403 below proves
+ // the gate is keyed on the historical private agent named by task_id.
+ currentAgentID := createHandlerTestAgent(t, "RerunCurrentAssignee", []byte("[]"))
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET assignee_id = $1 WHERE id = $2`, currentAgentID, issueID); err != nil {
+ t.Fatalf("reassign issue to second agent: %v", err)
+ }
+
+ taskCount := func() int {
+ var n int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&n); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ return n
+ }
+ origStatus := func() string {
+ var s string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, origID).Scan(&s); err != nil {
+ t.Fatalf("read orig status: %v", err)
+ }
+ return s
+ }
+ beforeCount, beforeStatus := taskCount(), origStatus()
+
+ // DENY: testUserID (workspace owner) can view the issue AND can invoke the
+ // current assignee, but cannot invoke the HISTORICAL private agent named by
+ // task_id → structured 403, and nothing is cancelled or created.
+ denyW := httptest.NewRecorder()
+ denyReq := withURLParam(newRequest("POST", "/api/issues/"+issueID+"/rerun", map[string]any{"task_id": origID}), "id", issueID)
+ testHandler.RerunIssue(denyW, denyReq)
+ if denyW.Code != http.StatusForbidden {
+ t.Fatalf("RerunIssue as non-invoker of historical agent: expected 403, got %d: %s", denyW.Code, denyW.Body.String())
+ }
+ if code := readReasonCode(t, denyW.Body.Bytes()); code != string(dispatch.ReasonInvocationNotAllowed) {
+ t.Errorf("reason_code = %q, want invocation_not_allowed", code)
+ }
+ if got := taskCount(); got != beforeCount {
+ t.Errorf("blocked rerun changed task count: got %d, want %d", got, beforeCount)
+ }
+ if got := origStatus(); got != beforeStatus {
+ t.Errorf("blocked rerun changed original task status: got %q, want %q", got, beforeStatus)
+ }
+
+ // ALLOW: the HISTORICAL agent's owner may rerun it, and the new task must
+ // target the historical agent — not the issue's current assignee.
+ allowW := httptest.NewRecorder()
+ allowReq := withURLParam(newRequestAs(ownerID, "POST", "/api/issues/"+issueID+"/rerun", map[string]any{"task_id": origID}), "id", issueID)
+ testHandler.RerunIssue(allowW, allowReq)
+ if allowW.Code != http.StatusAccepted {
+ t.Fatalf("RerunIssue as historical agent owner: expected 202, got %d: %s", allowW.Code, allowW.Body.String())
+ }
+ var reran struct {
+ ID string `json:"id"`
+ AgentID string `json:"agent_id"`
+ }
+ if err := json.Unmarshal(allowW.Body.Bytes(), &reran); err != nil {
+ t.Fatalf("decode rerun response: %v", err)
+ }
+ if reran.AgentID != agentID {
+ t.Errorf("reran task agent_id = %q, want historical agent %q (not current assignee %q)", reran.AgentID, agentID, currentAgentID)
+ }
+ if reran.ID == origID {
+ t.Errorf("expected a new task id, got the original %q", origID)
+ }
+}
diff --git a/server/internal/handler/admission_test.go b/server/internal/handler/admission_test.go
new file mode 100644
index 0000000000..6e159c3ce8
--- /dev/null
+++ b/server/internal/handler/admission_test.go
@@ -0,0 +1,53 @@
+package handler
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestRunToResponseDoesNotReverseEngineerReasonCode pins Elon must-fix 2: the
+// serializer must NOT derive reason_code from a persisted run's English
+// failure_reason. The typed code is a decision-time value the manual "run now"
+// handler injects from the dispatch outcome; a run read back from the DB (list /
+// history) carries the human failure_reason but no guessed code.
+func TestRunToResponseDoesNotReverseEngineerReasonCode(t *testing.T) {
+ run := db.AutopilotRun{
+ Status: "skipped",
+ FailureReason: pgtype.Text{
+ String: "assignee agent lacks access to private assignee agent",
+ Valid: true,
+ },
+ }
+ resp := runToResponse(run)
+ if resp.ReasonCode != nil {
+ t.Fatalf("runToResponse should not synthesize a reason_code from failure_reason, got %q", *resp.ReasonCode)
+ }
+ if resp.FailureReason == nil || *resp.FailureReason == "" {
+ t.Errorf("failure_reason should still be surfaced for history rows")
+ }
+}
+
+// TestDispatchBlockedFallbackMessageIsNonEnumerating asserts the legacy `error`
+// string for every reason code stays generic — it must be safe to show to a
+// caller who is not allowed to know whether the target exists, so it must not
+// name a private agent, its owner, or reveal existence.
+func TestDispatchBlockedFallbackMessageIsNonEnumerating(t *testing.T) {
+ codes := []DispatchReasonCode{
+ ReasonInvocationNotAllowed, ReasonTargetUnavailable, ReasonRuntimeOffline,
+ ReasonAttributionBlocked, ReasonAlreadyActive, ReasonInternalError,
+ DispatchReasonCode("some_future_code"),
+ }
+ for _, c := range codes {
+ msg := dispatchBlockedFallbackMessage(c)
+ if msg == "" {
+ t.Errorf("reason %q: empty fallback message", c)
+ }
+ }
+ // invocation_not_allowed must be deliberately vague: it cannot distinguish
+ // "target is private" from "target does not exist".
+ if got := dispatchBlockedFallbackMessage(ReasonInvocationNotAllowed); got != "you don't have permission to use this target" {
+ t.Errorf("invocation_not_allowed fallback = %q, changed to something more revealing?", got)
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 4764170ff1..c2f4f4a60b 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -17,10 +17,12 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/runtimeapps"
"github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -365,6 +367,12 @@ type AgentTaskResponse struct {
InitiatorName string `json:"initiator_name,omitempty"` // display name of the initiator
InitiatorEmail string `json:"initiator_email,omitempty"` // member email; empty for agent initiators
Kind string `json:"kind"` // discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "direct" — used by the activity row to label tasks that have no linked issue
+ // Attribution is the resolved accountable-human provenance for this run
+ // (MUL-4302 §9): the source label + precise flag, the initiator (accountable)
+ // and originator refs, the evidence pointer, and lineage. Always present (the
+ // pure taskToResponse builds the labels + raw ids); initiator/originator names
+ // are hydrated from the global user table only on user-facing surfaces.
+ Attribution *TaskAttribution `json:"attribution,omitempty"`
// AuthToken is the task-scoped `mat_` token the daemon must inject as
// MULTICA_TOKEN in the agent process environment. The server binds it to
// this (agent_id, task_id) pair at claim time and treats any request
@@ -376,6 +384,142 @@ type AgentTaskResponse struct {
AuthToken string `json:"auth_token,omitempty"`
}
+// TaskAttribution is the wire shape of a run's accountable-human provenance
+// (MUL-4302 §9). Source/Precise/Evidence/lineage come straight from the row (pure);
+// Initiator/Originator carry the raw user id always and the display name/email/avatar
+// only after hydration on a user-facing surface.
+type TaskAttribution struct {
+ // Source is the waterfall level that resolved the accountable human:
+ // direct_human | delegation | comment_source | rule_owner | owner_fallback |
+ // backfill | unattributed. Never blank (a pre-migration NULL renders "unattributed").
+ Source string `json:"source"`
+ // Precise is false for degraded sources (owner_fallback / backfill / unattributed);
+ // the UI marks these distinctly and they count against the coverage metric.
+ Precise bool `json:"precise"`
+ // Initiator is the accountable human (accountable_user_id). Nil when unattributed.
+ Initiator *AttributionUser `json:"initiator,omitempty"`
+ // Originator is the authorization human (originator_user_id); nil for autopilot
+ // (rule_owner / owner_fallback), where no human authorized the run.
+ Originator *AttributionUser `json:"originator,omitempty"`
+ // Evidence points at the direct cause of the run so the UI can jump to it.
+ Evidence *TaskEvidence `json:"evidence,omitempty"`
+ RuleVersionID string `json:"rule_version_id,omitempty"`
+ DelegatedFromTaskID string `json:"delegated_from_task_id,omitempty"`
+ RetryOfTaskID string `json:"retry_of_task_id,omitempty"`
+ RerunOfTaskID string `json:"rerun_of_task_id,omitempty"`
+}
+
+// AttributionUser is a departed-member-safe user ref, resolved from the global user
+// table. Name/Email/AvatarURL are empty until hydrated.
+type AttributionUser struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ Email string `json:"email,omitempty"`
+ AvatarURL string `json:"avatar_url,omitempty"`
+}
+
+// TaskEvidence is the kind-tagged handle to a run's direct cause (a comment,
+// autopilot run, rule version, source task, ...).
+type TaskEvidence struct {
+ Kind string `json:"kind"`
+ RefID string `json:"ref_id"`
+}
+
+// taskAttributionBase builds the pure (no-DB) part of a run's attribution from the
+// row: the source label + precise flag, evidence, lineage, and the raw initiator /
+// originator user ids. Names are filled later by hydrateTaskAttributions.
+func taskAttributionBase(t db.AgentTaskQueue) *TaskAttribution {
+ src := attribution.Source(t.OriginatorSource.String)
+ attr := &TaskAttribution{
+ Source: src.String(), // empty (pre-migration) → "unattributed"
+ Precise: src.Precise(),
+ RuleVersionID: uuidToString(t.RuleVersionID),
+ DelegatedFromTaskID: uuidToString(t.DelegatedFromTaskID),
+ RetryOfTaskID: uuidToString(t.RetryOfTaskID),
+ RerunOfTaskID: uuidToString(t.RerunOfTaskID),
+ }
+ if t.AccountableUserID.Valid {
+ attr.Initiator = &AttributionUser{ID: uuidToString(t.AccountableUserID)}
+ }
+ if t.OriginatorUserID.Valid {
+ attr.Originator = &AttributionUser{ID: uuidToString(t.OriginatorUserID)}
+ }
+ if t.TriggerEvidenceKind.Valid && t.TriggerEvidenceKind.String != "" {
+ attr.Evidence = &TaskEvidence{Kind: t.TriggerEvidenceKind.String, RefID: uuidToString(t.TriggerEvidenceRefID)}
+ }
+ return attr
+}
+
+// hydrateTaskAttributions fills the display name / email / avatar on the initiator
+// and originator refs of the given attributions, resolving from the GLOBAL user
+// table in one batch (departed-safe, N+1-free). Best-effort: on a lookup failure the
+// raw user ids already present are left as-is — names are display sugar, not gating.
+func (h *Handler) hydrateTaskAttributions(ctx context.Context, attrs []*TaskAttribution) {
+ seen := make(map[string]struct{})
+ var ids []pgtype.UUID
+ add := func(ref *AttributionUser) {
+ if ref == nil || ref.ID == "" {
+ return
+ }
+ if _, ok := seen[ref.ID]; ok {
+ return
+ }
+ if u, err := util.ParseUUID(ref.ID); err == nil {
+ seen[ref.ID] = struct{}{}
+ ids = append(ids, u)
+ }
+ }
+ for _, a := range attrs {
+ if a == nil {
+ continue
+ }
+ add(a.Initiator)
+ add(a.Originator)
+ }
+ if len(ids) == 0 {
+ return
+ }
+ users, err := h.Queries.GetUsersByIDs(ctx, ids)
+ if err != nil {
+ return
+ }
+ byID := make(map[string]db.GetUsersByIDsRow, len(users))
+ for _, u := range users {
+ byID[uuidToString(u.ID)] = u
+ }
+ fill := func(ref *AttributionUser) {
+ if ref == nil {
+ return
+ }
+ if u, ok := byID[ref.ID]; ok {
+ ref.Name = u.Name
+ ref.Email = u.Email
+ if u.AvatarUrl.Valid {
+ ref.AvatarURL = u.AvatarUrl.String
+ }
+ }
+ }
+ for _, a := range attrs {
+ if a == nil {
+ continue
+ }
+ fill(a.Initiator)
+ fill(a.Originator)
+ }
+}
+
+// attributionsOf collects the (non-nil) TaskAttribution pointers from a slice of
+// task responses so a list endpoint can hydrate them all in one batch.
+func attributionsOf(resps []AgentTaskResponse) []*TaskAttribution {
+ out := make([]*TaskAttribution, 0, len(resps))
+ for i := range resps {
+ if resps[i].Attribution != nil {
+ out = append(out, resps[i].Attribution)
+ }
+ }
+ return out
+}
+
// ChatAttachmentMeta is the structured attachment metadata embedded in
// claim responses for chat tasks. The agent uses these to run
// `multica attachment download <id>` rather than guessing from the
@@ -483,6 +627,9 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
ChatSessionID: uuidToString(t.ChatSessionID),
AutopilotRunID: uuidToString(t.AutopilotRunID),
Kind: computeTaskKind(t),
+ // Attribution labels + evidence + lineage + raw user ids (pure). Names are
+ // hydrated separately on user-facing surfaces (MUL-4302 §9).
+ Attribution: taskAttributionBase(t),
}
}
@@ -1859,6 +2006,7 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {
for i, t := range tasks {
resp[i] = taskToResponse(t, workspaceID)
}
+ h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
writeJSON(w, http.StatusOK, resp)
}
@@ -1996,6 +2144,7 @@ func (h *Handler) ListWorkspaceAgentTaskSnapshot(w http.ResponseWriter, r *http.
}
resp = append(resp, taskToResponse(t, workspaceID))
}
+ h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/attribution_response_test.go b/server/internal/handler/attribution_response_test.go
new file mode 100644
index 0000000000..b302a3a387
--- /dev/null
+++ b/server/internal/handler/attribution_response_test.go
@@ -0,0 +1,180 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestTaskAttributionBase covers the pure row→attribution mapping (MUL-4302 §9):
+// source label + precise flag, initiator/originator raw refs, evidence, lineage —
+// no DB, no name hydration.
+func TestTaskAttributionBase(t *testing.T) {
+ member := parseUUID("11111111-1111-1111-1111-111111111111")
+ comment := parseUUID("22222222-2222-2222-2222-222222222222")
+ ruleVer := parseUUID("33333333-3333-3333-3333-333333333333")
+
+ t.Run("direct_human sets both refs + evidence", func(t *testing.T) {
+ got := taskAttributionBase(db.AgentTaskQueue{
+ OriginatorSource: pgtype.Text{String: "direct_human", Valid: true},
+ OriginatorUserID: member,
+ AccountableUserID: member,
+ TriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},
+ TriggerEvidenceRefID: comment,
+ })
+ if got.Source != "direct_human" || !got.Precise {
+ t.Fatalf("source/precise = %q/%v, want direct_human/true", got.Source, got.Precise)
+ }
+ if got.Initiator == nil || got.Initiator.ID != uuidToString(member) {
+ t.Errorf("initiator = %+v, want member", got.Initiator)
+ }
+ if got.Originator == nil || got.Originator.ID != uuidToString(member) {
+ t.Errorf("originator = %+v, want member", got.Originator)
+ }
+ if got.Evidence == nil || got.Evidence.Kind != "comment" || got.Evidence.RefID != uuidToString(comment) {
+ t.Errorf("evidence = %+v, want comment/%s", got.Evidence, uuidToString(comment))
+ }
+ if got.Initiator.Name != "" {
+ t.Errorf("base must not carry a name (hydration is separate), got %q", got.Initiator.Name)
+ }
+ })
+
+ t.Run("rule_owner: accountable set, originator NULL, rule_version present", func(t *testing.T) {
+ got := taskAttributionBase(db.AgentTaskQueue{
+ OriginatorSource: pgtype.Text{String: "rule_owner", Valid: true},
+ AccountableUserID: member, // originator left invalid (autopilot)
+ RuleVersionID: ruleVer,
+ })
+ if got.Source != "rule_owner" || !got.Precise {
+ t.Fatalf("source/precise = %q/%v, want rule_owner/true", got.Source, got.Precise)
+ }
+ if got.Initiator == nil || got.Initiator.ID != uuidToString(member) {
+ t.Errorf("initiator = %+v, want member (rule publisher)", got.Initiator)
+ }
+ if got.Originator != nil {
+ t.Errorf("rule_owner must have NULL originator, got %+v", got.Originator)
+ }
+ if got.RuleVersionID != uuidToString(ruleVer) {
+ t.Errorf("rule_version_id = %q, want %s", got.RuleVersionID, uuidToString(ruleVer))
+ }
+ })
+
+ t.Run("owner_fallback is degraded (not precise)", func(t *testing.T) {
+ got := taskAttributionBase(db.AgentTaskQueue{
+ OriginatorSource: pgtype.Text{String: "owner_fallback", Valid: true},
+ AccountableUserID: member,
+ })
+ if got.Source != "owner_fallback" || got.Precise {
+ t.Errorf("source/precise = %q/%v, want owner_fallback/false", got.Source, got.Precise)
+ }
+ })
+
+ t.Run("empty (pre-migration) source renders unattributed", func(t *testing.T) {
+ got := taskAttributionBase(db.AgentTaskQueue{}) // no attribution columns set
+ if got.Source != "unattributed" || got.Precise {
+ t.Errorf("source/precise = %q/%v, want unattributed/false", got.Source, got.Precise)
+ }
+ if got.Initiator != nil || got.Originator != nil || got.Evidence != nil {
+ t.Errorf("no ids/evidence should be set for an empty row, got %+v", got)
+ }
+ })
+}
+
+// TestHydrateTaskAttributionsFillsUserRef verifies the batch name hydration resolves
+// initiator/originator refs from the GLOBAL user table (departed-safe) and leaves an
+// unknown id un-filled without erroring (MUL-4302 §9).
+func TestHydrateTaskAttributionsFillsUserRef(t *testing.T) {
+ known := &AttributionUser{ID: testUserID}
+ unknown := &AttributionUser{ID: "44444444-4444-4444-4444-444444444444"}
+ attrs := []*TaskAttribution{
+ {Initiator: known, Originator: known}, // same id in both refs
+ {Initiator: unknown},
+ nil, // must be skipped without panic
+ }
+
+ testHandler.hydrateTaskAttributions(context.Background(), attrs)
+
+ if known.Name != handlerTestName || known.Email != handlerTestEmail {
+ t.Errorf("known ref = %q/%q, want %q/%q", known.Name, known.Email, handlerTestName, handlerTestEmail)
+ }
+ if unknown.Name != "" {
+ t.Errorf("unknown user id must stay un-filled, got name %q", unknown.Name)
+ }
+}
+
+// TestListTasksByIssueHydratesAttribution is the MUL-4302 §9 regression guard for
+// the execution-log surface: the issue task list (api.listTasksByIssue) drives the
+// "on behalf of <member>" badge, so it must resolve the initiator's display NAME,
+// not just its id. Before the fix ListTasksByIssue returned taskToResponse without
+// hydration and the badge fell back to "someone" on issue detail.
+func TestListTasksByIssueHydratesAttribution(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ agentID := createHandlerTestAgent(t, "AttributionListAgent", []byte("[]"))
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'attribution-list-issue', 'todo', 'medium', $2, 'member', 92777, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ // direct_human: accountable == originator == the fixture user, whose name
+ // lives in the global user table — so hydration has a name to fill.
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_source, originator_user_id, accountable_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'completed', 0, $2, 'direct_human', $3, $3)
+ RETURNING id
+ `, agentID, issueID, testUserID).Scan(&taskID); err != nil {
+ t.Fatalf("create attributed task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ req := newRequest("GET", "/api/issues/"+issueID+"/tasks", nil)
+ req = withURLParam(req, "id", issueID)
+ w := httptest.NewRecorder()
+ testHandler.ListTasksByIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp []AgentTaskResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode task list: %v", err)
+ }
+
+ var got *TaskAttribution
+ for i := range resp {
+ if resp[i].ID == taskID {
+ got = resp[i].Attribution
+ break
+ }
+ }
+ if got == nil {
+ t.Fatalf("task %s missing from response or has no attribution: %s", taskID, w.Body.String())
+ }
+ if got.Source != "direct_human" || !got.Precise {
+ t.Fatalf("source/precise = %q/%v, want direct_human/true", got.Source, got.Precise)
+ }
+ if got.Initiator == nil {
+ t.Fatal("initiator missing")
+ }
+ if got.Initiator.ID != testUserID {
+ t.Errorf("initiator id = %q, want %q", got.Initiator.ID, testUserID)
+ }
+ if got.Initiator.Name != handlerTestName {
+ t.Errorf("initiator name = %q, want %q (list endpoint must hydrate names)", got.Initiator.Name, handlerTestName)
+ }
+}
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index 1080889e72..a157bcfa04 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -1,6 +1,7 @@
package handler
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
@@ -141,16 +142,22 @@ type AutopilotTriggerResponse struct {
}
type AutopilotRunResponse struct {
- ID string `json:"id"`
- AutopilotID string `json:"autopilot_id"`
- TriggerID *string `json:"trigger_id"`
- Source string `json:"source"`
- Status string `json:"status"`
- IssueID *string `json:"issue_id"`
- TaskID *string `json:"task_id"`
- TriggeredAt string `json:"triggered_at"`
- CompletedAt *string `json:"completed_at"`
- FailureReason *string `json:"failure_reason"`
+ ID string `json:"id"`
+ AutopilotID string `json:"autopilot_id"`
+ TriggerID *string `json:"trigger_id"`
+ Source string `json:"source"`
+ Status string `json:"status"`
+ IssueID *string `json:"issue_id"`
+ TaskID *string `json:"task_id"`
+ TriggeredAt string `json:"triggered_at"`
+ CompletedAt *string `json:"completed_at"`
+ FailureReason *string `json:"failure_reason"`
+ // ReasonCode is a stable, localizable, enumeration-safe classification of a
+ // non-success run (skipped/failed), derived from FailureReason. The "run now"
+ // UI localizes it instead of echoing the raw English reason (which may name a
+ // private assignee agent). Additive: nil for success-path runs and ignored by
+ // old clients (MUL-4525).
+ ReasonCode *string `json:"reason_code,omitempty"`
TriggerPayload any `json:"trigger_payload"`
Result any `json:"result"`
CreatedAt string `json:"created_at"`
@@ -268,16 +275,20 @@ func runToResponse(r db.AutopilotRun) AutopilotRunResponse {
json.Unmarshal(r.Result, &result)
}
return AutopilotRunResponse{
- ID: uuidToString(r.ID),
- AutopilotID: uuidToString(r.AutopilotID),
- TriggerID: uuidToPtr(r.TriggerID),
- Source: r.Source,
- Status: r.Status,
- IssueID: uuidToPtr(r.IssueID),
- TaskID: uuidToPtr(r.TaskID),
- TriggeredAt: timestampToString(r.TriggeredAt),
- CompletedAt: timestampToPtr(r.CompletedAt),
- FailureReason: textToPtr(r.FailureReason),
+ ID: uuidToString(r.ID),
+ AutopilotID: uuidToString(r.AutopilotID),
+ TriggerID: uuidToPtr(r.TriggerID),
+ Source: r.Source,
+ Status: r.Status,
+ IssueID: uuidToPtr(r.IssueID),
+ TaskID: uuidToPtr(r.TaskID),
+ TriggeredAt: timestampToString(r.TriggeredAt),
+ CompletedAt: timestampToPtr(r.CompletedAt),
+ FailureReason: textToPtr(r.FailureReason),
+ // ReasonCode is left unset here: it is a decision-time value the manual
+ // "run now" handler injects from the typed dispatch outcome (MUL-4525).
+ // Persisted rows (list/history) surface the human failure_reason instead
+ // of a code reverse-engineered from that text.
TriggerPayload: payload,
Result: result,
CreatedAt: timestampToString(r.CreatedAt),
@@ -676,6 +687,14 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
return
}
+ // Creating an autopilot IS a substantive publish: append rule-version v1 with
+ // the creating member as publisher, so every autopilot has an accountable
+ // human at dispatch time (MUL-4302 §3.4).
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", parseUUID(userID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create autopilot")
+ return
+ }
+
for _, uid := range subscriberUUIDs {
if err := qtx.AddAutopilotSubscriber(r.Context(), db.AddAutopilotSubscriberParams{
AutopilotID: autopilot.ID,
@@ -887,6 +906,29 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
return
}
+ // A substantive change (target / enabled-state / execution mode) republishes the
+ // rule: append a new version with THIS member as publisher, so a later run
+ // attributes to whoever last changed what the rule does — not the original
+ // creator. Cosmetic edits (title / description / template) write no version and
+ // leave accountability with the previous publisher (MUL-4302 §3.4).
+ if autopilotRuleSubstantiveChange(prev, autopilot) {
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", parseUUID(userID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update autopilot")
+ return
+ }
+ // An autopilot-level substantive edit governs every trigger, so responsibility
+ // for each firing trigger transfers to this editor (source=trigger_owner). A
+ // trigger-scoped edit re-stamps only its own row (see UpdateAutopilotTrigger).
+ if err := qtx.SetAutopilotTriggerPublishersByAutopilot(r.Context(), db.SetAutopilotTriggerPublishersByAutopilotParams{
+ AutopilotID: autopilot.ID,
+ PublishedByType: pgtype.Text{String: "member", Valid: true},
+ PublishedByID: parseUUID(userID),
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update autopilot")
+ return
+ }
+ }
+
if replaceSubscribers {
if err := qtx.DeleteAutopilotSubscribersForAutopilot(r.Context(), autopilot.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to update subscribers")
@@ -918,6 +960,45 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+// autopilotRuleSubstantiveChange reports whether a substantive (publish-worthy)
+// field of the autopilot ROW changed between prev and next — a change that alters
+// WHAT the automation instructs the agent to do, or WHO / WHETHER it runs, and so
+// transfers accountability to the editor (MUL-4302 §3.4; boundary pinned with Elon):
+//
+// - assignee_type / assignee_id — who (agent / squad leader) executes;
+// - status — enabled state (active / paused / archived);
+// - execution_mode — run_only vs create_issue;
+// - description — the product surfaces this as the run PROMPT, i.e. the task
+// instruction itself, so editing it must transfer responsibility (the gap Elon
+// flagged: a fresh publisher of the instructions is the accountable human);
+// - issue_title_template — templates the created issue in create_issue mode; part
+// of the instruction / output spec the run produces.
+//
+// Deliberately NOT substantive (cosmetic / routing — they change neither the
+// instruction nor the executor): title (display label) and project_id (which project
+// created issues are filed under). The comparison is faithful because UpdateAutopilot
+// seeds every param from prev, so an omitted field round-trips unchanged.
+//
+// Trigger-table edits (cron / timezone / enabled / event_filters) are substantive PER
+// TRIGGER and handled in UpdateAutopilotTrigger; archive and system-pause republish in
+// their own paths.
+func autopilotRuleSubstantiveChange(prev, next db.Autopilot) bool {
+ return prev.AssigneeType != next.AssigneeType ||
+ prev.AssigneeID != next.AssigneeID ||
+ prev.Status != next.Status ||
+ prev.ExecutionMode != next.ExecutionMode ||
+ prev.Description != next.Description ||
+ prev.IssueTitleTemplate != next.IssueTitleTemplate
+}
+
+// recordAutopilotRuleVersion appends one rule-version snapshot for a substantive
+// publish (MUL-4302 §3.4). Thin handler wrapper over service.RecordAutopilotRuleVersion
+// (shared with the failure monitor); callers pass their tx-scoped Queries so the
+// version is atomic with the autopilot write.
+func (h *Handler) recordAutopilotRuleVersion(ctx context.Context, q *db.Queries, ap db.Autopilot, publishedByType string, publishedByID pgtype.UUID) error {
+ return service.RecordAutopilotRuleVersion(ctx, q, ap, publishedByType, publishedByID)
+}
+
func (h *Handler) parseAutopilotProjectID(
w http.ResponseWriter,
r *http.Request,
@@ -974,7 +1055,26 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {
// Product "delete" is archival: stop future triggers and hide the
// autopilot from default lists while preserving runs, tasks, webhook
// deliveries, subscribers, and collaborators as execution history.
- if err := h.Queries.ArchiveAutopilot(r.Context(), idUUID); err != nil {
+ // Archiving is a substantive status change (MUL-4302 §3.4), so republish the
+ // rule version with this member as publisher, atomically with the archive.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if err := qtx.ArchiveAutopilot(r.Context(), idUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ ap.Status = "archived" // reflect the post-archive state in the version snapshot
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
return
}
@@ -1113,6 +1213,17 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
if !h.requireAutopilotWrite(w, r, ap, workspaceID) {
return
}
+ // A new trigger changes what / when the rule fires — a substantive publish, so
+ // the acting member republishes the rule version ATOMICALLY with the trigger
+ // create (MUL-4302 §3.4). Resolved here so both the webhook and schedule create
+ // paths can write the version inside the same tx as the INSERT — a failed
+ // version write must roll the trigger back, never leave future dispatches
+ // attributed to the previous publisher.
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ publisherID := parseUUID(userID)
var req CreateAutopilotTriggerRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -1211,13 +1322,12 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to encode event_filters")
return
}
- trigger, err := h.createWebhookTriggerWithMintedToken(r, ap.ID, ptrToText(req.Label), provider, eventFiltersBytes)
+ trigger, err := h.createWebhookTriggerWithMintedToken(r, ap, ptrToText(req.Label), provider, eventFiltersBytes, publisherID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create trigger")
return
}
resp := h.triggerToResponse(trigger)
- userID, _ := requireUserID(w, r)
h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{
"autopilot_id": uuidToString(ap.ID),
"trigger": resp,
@@ -1226,7 +1336,16 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
return
}
- trigger, err := h.Queries.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{
+ // Schedule create: write the trigger and republish the rule version atomically.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create trigger")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ trigger, err := qtx.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{
AutopilotID: ap.ID,
Kind: req.Kind,
Enabled: true,
@@ -1235,14 +1354,26 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
NextRunAt: nextRunAt,
Label: ptrToText(req.Label),
WebhookToken: webhookToken,
+ // Seed the responsible publisher = creator; a later substantive edit re-stamps
+ // it to the editor so runs attribute to whoever last shaped this trigger
+ // (source=trigger_owner, MUL-4302).
+ PublishedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},
+ PublishedByID: publisherID,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create trigger")
return
}
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", publisherID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create trigger")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to create trigger")
+ return
+ }
resp := h.triggerToResponse(trigger)
- userID, _ := requireUserID(w, r)
h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{
"autopilot_id": uuidToString(ap.ID),
"trigger": resp,
@@ -1256,35 +1387,60 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
// kind=webhook row with NULL webhook_token visible in the UI if the second
// statement failed.
//
-// Retries on the unique-index collision case so a vanishingly-rare RNG
+// Each attempt runs in its OWN transaction so the trigger INSERT and the
+// rule-version republish (a webhook trigger is a substantive change to what fires,
+// MUL-4302 §3.4, published by publisherID) commit together — a version-write failure
+// rolls the trigger back rather than leaving future dispatches attributed to the
+// previous publisher. Retries on the unique-index collision case with a fresh token
+// (the collided attempt's tx is already rolled back), so a vanishingly-rare RNG
// collision turns into a clean retry rather than a 500.
func (h *Handler) createWebhookTriggerWithMintedToken(
r *http.Request,
- autopilotID pgtype.UUID,
+ ap db.Autopilot,
label pgtype.Text,
provider string,
eventFilters []byte,
+ publisherID pgtype.UUID,
) (db.AutopilotTrigger, error) {
+ ctx := r.Context()
for attempt := 0; attempt < 3; attempt++ {
token, err := generateWebhookToken()
if err != nil {
return db.AutopilotTrigger{}, err
}
- trigger, err := h.Queries.CreateAutopilotTrigger(r.Context(), db.CreateAutopilotTriggerParams{
- AutopilotID: autopilotID,
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.AutopilotTrigger{}, err
+ }
+ qtx := h.Queries.WithTx(tx)
+ trigger, err := qtx.CreateAutopilotTrigger(ctx, db.CreateAutopilotTriggerParams{
+ AutopilotID: ap.ID,
Kind: "webhook",
Enabled: true,
Label: label,
WebhookToken: pgtype.Text{String: token, Valid: true},
Provider: pgtype.Text{String: provider, Valid: provider != ""},
EventFilters: eventFilters,
+ // Seed the responsible publisher = creator; re-stamped to the editor on a
+ // later substantive edit (source=trigger_owner, MUL-4302).
+ PublishedByType: pgtype.Text{String: "member", Valid: publisherID.Valid},
+ PublishedByID: publisherID,
})
- if err == nil {
- return trigger, nil
+ if err != nil {
+ tx.Rollback(ctx)
+ if isUniqueViolation(err) {
+ continue // token collision: retry with a fresh token
+ }
+ return db.AutopilotTrigger{}, err
}
- if !isUniqueViolation(err) {
+ if err := h.recordAutopilotRuleVersion(ctx, qtx, ap, "member", publisherID); err != nil {
+ tx.Rollback(ctx)
return db.AutopilotTrigger{}, err
}
+ if err := tx.Commit(ctx); err != nil {
+ return db.AutopilotTrigger{}, err
+ }
+ return trigger, nil
}
return db.AutopilotTrigger{}, fmt.Errorf("could not mint unique webhook token")
}
@@ -1484,14 +1640,59 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
params.NextRunAt = pgtype.Timestamptz{Time: t, Valid: true}
}
- trigger, err := h.Queries.UpdateAutopilotTrigger(r.Context(), params)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update trigger")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ trigger, err := qtx.UpdateAutopilotTrigger(r.Context(), params)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to update trigger")
return
}
+ // Only a substantive edit republishes the rule version and transfers this
+ // trigger's accountability to the editor. cron / timezone / enabled / event_filters
+ // change WHAT or WHEN the trigger fires; label is a cosmetic display field, and a
+ // no-op PATCH changes nothing — neither should move responsibility (MUL-4302; the
+ // over-transfer Elon flagged). Comparing the persisted before/after rows captures a
+ // real change and ignores label-only / no-op PATCHes (next_run_at is derived from
+ // cron/timezone, so it is not an independent signal).
+ triggerSubstantiveChange := prev.Enabled != trigger.Enabled ||
+ prev.CronExpression != trigger.CronExpression ||
+ prev.Timezone != trigger.Timezone ||
+ !bytes.Equal(prev.EventFilters, trigger.EventFilters)
+ if triggerSubstantiveChange {
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update trigger")
+ return
+ }
+ // Responsibility for THIS trigger's runs transfers to the editor. Scoped to the
+ // single row so editing one trigger never reassigns another's accountability —
+ // the per-firing-trigger granularity the autopilot-scoped rule_version can't give.
+ if err := qtx.SetAutopilotTriggerPublisher(r.Context(), db.SetAutopilotTriggerPublisherParams{
+ ID: trigger.ID,
+ PublishedByType: pgtype.Text{String: "member", Valid: true},
+ PublishedByID: parseUUID(userID),
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update trigger")
+ return
+ }
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update trigger")
+ return
+ }
+
resp := h.triggerToResponse(trigger)
- userID, _ := requireUserID(w, r)
h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{
"autopilot_id": uuidToString(ap.ID),
"trigger": resp,
@@ -1540,7 +1741,26 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)
return
}
- if err := h.Queries.DeleteAutopilotTrigger(r.Context(), triggerUUID); err != nil {
+ // Removing a trigger changes what fires — a substantive publish (MUL-4302 §3.4).
+ // Republish the rule version with this member as publisher, atomically with the
+ // delete.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete trigger")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if err := qtx.DeleteAutopilotTrigger(r.Context(), triggerUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete trigger")
+ return
+ }
+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete trigger")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete trigger")
return
}
@@ -1788,11 +2008,29 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
return
}
- run, err := h.AutopilotService.DispatchAutopilot(r.Context(), autopilot, pgtype.UUID{}, "manual", nil)
+ // A manual "run now" is a direct human action, so the run is attributed
+ // direct_human to the triggering member (MUL-4302 §4). Resolve the actor the
+ // same way assign/promote does; only a member actor is a human — an agent
+ // triggering via A2A yields an invalid actor and falls back to rule_owner.
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+
+ run, reasonCode, err := h.AutopilotService.DispatchAutopilotManual(r.Context(), autopilot, pgtype.UUID{}, nil, memberActorUserID(actorType, actorID))
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to trigger autopilot: "+err.Error())
return
}
- writeJSON(w, http.StatusOK, runToResponse(*run))
+ // Carry the typed admission reason (decided at its source, MUL-4525) straight
+ // into the response — no reverse-engineering from failure_reason text. The
+ // UI branches on run status + this code for the "run now" toast.
+ resp := runToResponse(*run)
+ if reasonCode != "" {
+ c := string(reasonCode)
+ resp.ReasonCode = &c
+ }
+ writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/autopilot_attribution_transfer_test.go b/server/internal/handler/autopilot_attribution_transfer_test.go
new file mode 100644
index 0000000000..3d71603104
--- /dev/null
+++ b/server/internal/handler/autopilot_attribution_transfer_test.go
@@ -0,0 +1,174 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+// These tests drive the REAL autopilot update handlers to prove the substantive /
+// cosmetic edit boundary that decides when trigger_owner responsibility transfers
+// (MUL-4302; Elon must-fix). They deliberately go through UpdateAutopilot /
+// UpdateAutopilotTrigger rather than calling SetAutopilotTriggerPublisher* directly,
+// because the bug Elon flagged lived in the handler's decision of WHEN to call the
+// setter, not in the setter itself. testHandler / testUserID / testWorkspaceID /
+// testPool are wired in TestMain (handler_test.go).
+
+// seedTransferMember inserts a workspace member distinct from testUserID, modeling the
+// CREATOR of an automation whose responsibility a later editor (testUserID) inherits.
+func seedTransferMember(t *testing.T, label string) string {
+ t.Helper()
+ ctx := context.Background()
+ var uid string
+ if err := testPool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ label, fmt.Sprintf("%s-%[email protected]", label, time.Now().UnixNano())).Scan(&uid); err != nil {
+ t.Fatalf("seed %s user: %v", label, err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, uid) })
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ testWorkspaceID, uid); err != nil {
+ t.Fatalf("seed %s member: %v", label, err)
+ }
+ return uid
+}
+
+// seedScheduleTriggerPublishedBy inserts a schedule trigger whose responsible publisher
+// is memberID, so a later handler edit can be observed to transfer (or not) responsibility.
+func seedScheduleTriggerPublishedBy(t *testing.T, apID, memberID string) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
+ VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,
+ apID, memberID).Scan(&id); err != nil {
+ t.Fatalf("seed schedule trigger: %v", err)
+ }
+ return id
+}
+
+// triggerPublisherMember returns the member id currently recorded as the trigger's
+// responsible publisher, or "" if it is not a member.
+func triggerPublisherMember(t *testing.T, triggerID string) string {
+ t.Helper()
+ row, err := testHandler.Queries.GetAutopilotTrigger(context.Background(), parseUUID(triggerID))
+ if err != nil {
+ t.Fatalf("load trigger: %v", err)
+ }
+ if row.PublishedByType.Valid && row.PublishedByType.String == "member" && row.PublishedByID.Valid {
+ return uuidToString(row.PublishedByID)
+ }
+ return ""
+}
+
+func patchAutopilot(t *testing.T, apID string, body map[string]any) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, body)
+ req = withURLParam(req, "id", apID)
+ testHandler.UpdateAutopilot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func patchTrigger(t *testing.T, apID, triggerID string, body map[string]any) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+triggerID, body)
+ req = withURLParams(req, "id", apID, "triggerId", triggerID)
+ testHandler.UpdateAutopilotTrigger(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateAutopilotTrigger: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// TestUpdateAutopilot_PromptEditTransfersAllTriggers: the autopilot description IS the
+// run prompt (task instruction), so editing it transfers accountability for EVERY
+// trigger to the editor — the exact gap Elon flagged (description was omitted from the
+// substantive predicate, so a prompt rewrite left runs attributed to the creator).
+func TestUpdateAutopilot_PromptEditTransfersAllTriggers(t *testing.T) {
+ creatorA := seedTransferMember(t, "prompt-creator")
+ agentID := createWebhookTestAgent(t, "PromptEdit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig1 := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+ trig2 := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+
+ patchAutopilot(t, apID, map[string]any{"description": "Rewritten prompt: do the new thing"})
+
+ if got := triggerPublisherMember(t, trig1); got != testUserID {
+ t.Errorf("trigger1 publisher = %s, want editor %s (prompt edit must transfer)", got, testUserID)
+ }
+ if got := triggerPublisherMember(t, trig2); got != testUserID {
+ t.Errorf("trigger2 publisher = %s, want editor %s (prompt edit bumps all triggers)", got, testUserID)
+ }
+}
+
+// TestUpdateAutopilot_CosmeticTitleEditDoesNotTransfer: the title is a display label,
+// not an instruction — editing it alone must NOT move responsibility.
+func TestUpdateAutopilot_CosmeticTitleEditDoesNotTransfer(t *testing.T) {
+ creatorA := seedTransferMember(t, "title-creator")
+ agentID := createWebhookTestAgent(t, "TitleEdit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+
+ patchAutopilot(t, apID, map[string]any{"title": "Renamed automation"})
+
+ if got := triggerPublisherMember(t, trig); got != creatorA {
+ t.Errorf("trigger publisher = %s, want unchanged creator %s (cosmetic title edit must not transfer)", got, creatorA)
+ }
+}
+
+// TestUpdateAutopilotTrigger_SubstantiveEditTransfersOnlyThatTrigger: a cron/enabled
+// edit changes what/when THIS trigger fires, so it transfers only this trigger's
+// responsibility; a sibling trigger is untouched (per-firing-trigger granularity).
+func TestUpdateAutopilotTrigger_SubstantiveEditTransfersOnlyThatTrigger(t *testing.T) {
+ creatorA := seedTransferMember(t, "trig-creator")
+ agentID := createWebhookTestAgent(t, "TrigEdit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig1 := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+ trig2 := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+
+ patchTrigger(t, apID, trig1, map[string]any{"enabled": false})
+
+ if got := triggerPublisherMember(t, trig1); got != testUserID {
+ t.Errorf("trigger1 publisher = %s, want editor %s (substantive edit must transfer)", got, testUserID)
+ }
+ if got := triggerPublisherMember(t, trig2); got != creatorA {
+ t.Errorf("trigger2 publisher = %s, want unchanged creator %s (editing a sibling must not transfer)", got, creatorA)
+ }
+}
+
+// TestUpdateAutopilotTrigger_LabelOnlyEditDoesNotTransfer: label is cosmetic, so a
+// label-only PATCH must NOT transfer responsibility — the over-transfer Elon flagged
+// (any PATCH used to unconditionally re-stamp the publisher).
+func TestUpdateAutopilotTrigger_LabelOnlyEditDoesNotTransfer(t *testing.T) {
+ creatorA := seedTransferMember(t, "label-creator")
+ agentID := createWebhookTestAgent(t, "LabelEdit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+
+ patchTrigger(t, apID, trig, map[string]any{"label": "just a nickname"})
+
+ if got := triggerPublisherMember(t, trig); got != creatorA {
+ t.Errorf("trigger publisher = %s, want unchanged creator %s (label-only edit must not transfer)", got, creatorA)
+ }
+}
+
+// TestUpdateAutopilotTrigger_NoOpEditDoesNotTransfer: a PATCH that re-sends the trigger's
+// current values changes nothing, so responsibility must stay put.
+func TestUpdateAutopilotTrigger_NoOpEditDoesNotTransfer(t *testing.T) {
+ creatorA := seedTransferMember(t, "noop-creator")
+ agentID := createWebhookTestAgent(t, "NoOpEdit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := seedScheduleTriggerPublishedBy(t, apID, creatorA)
+
+ // Re-send the same cron the row already has.
+ patchTrigger(t, apID, trig, map[string]any{"cron_expression": "0 * * * *"})
+
+ if got := triggerPublisherMember(t, trig); got != creatorA {
+ t.Errorf("trigger publisher = %s, want unchanged creator %s (no-op edit must not transfer)", got, creatorA)
+ }
+}
diff --git a/server/internal/handler/autopilot_private_leader_test.go b/server/internal/handler/autopilot_private_leader_test.go
index d615dea3ac..89c19fee7f 100644
--- a/server/internal/handler/autopilot_private_leader_test.go
+++ b/server/internal/handler/autopilot_private_leader_test.go
@@ -193,9 +193,12 @@ func TestTriggerAutopilot_SquadPrivateLeader_OwnerCanDispatch(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)
})
- // Trigger — should succeed since owner created it.
+ // Trigger AS THE OWNER — manual "run now" admits on the current clicker's
+ // invoke permission (MUL-4525), so the owner (who can invoke the private
+ // leader) must be the one clicking. A non-owner clicker is covered by
+ // TestTriggerAutopilot_SquadPrivateLeader_NonOwnerClicker_Blocked below.
w = httptest.NewRecorder()
- r = newRequest("POST", "/api/autopilots/"+ap.ID+"/trigger?workspace_id="+testWorkspaceID, nil)
+ r = newRequestAs(ownerID, "POST", "/api/autopilots/"+ap.ID+"/trigger?workspace_id="+testWorkspaceID, nil)
r = withURLParam(r, "id", ap.ID)
testHandler.TriggerAutopilot(w, r)
if w.Code != http.StatusOK {
@@ -210,6 +213,82 @@ func TestTriggerAutopilot_SquadPrivateLeader_OwnerCanDispatch(t *testing.T) {
}
}
+// TestTriggerAutopilot_SquadPrivateLeader_NonOwnerClicker_Blocked pins the
+// MUL-4525 fork fix: manual "run now" admits on the CURRENT clicker, not the
+// autopilot creator. Even for an autopilot the OWNER created (so the creator
+// could invoke), a different member clicking Run now who cannot invoke the
+// private leader is blocked — surfaced as a 200 + status=skipped run carrying a
+// stable, enumeration-safe reason_code (not a silent success). This is the exact
+// case where the old creator-based admission and clicker-based attribution
+// forked.
+func TestTriggerAutopilot_SquadPrivateLeader_NonOwnerClicker_Blocked(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ agentID, ownerID, _ := privateAgentTestFixture(t)
+
+ var squadID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)
+ VALUES ($1, 'AP Private Leader Clicker Fork', '', $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)
+ })
+
+ // Owner creates a legitimate autopilot (creator CAN invoke the leader).
+ w := httptest.NewRecorder()
+ r := newRequestAs(ownerID, "POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "clicker fork private leader squad",
+ "assignee_type": "squad",
+ "assignee_id": squadID,
+ "execution_mode": "create_issue",
+ })
+ testHandler.CreateAutopilot(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var ap AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&ap); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM autopilot_run WHERE autopilot_id = $1`, ap.ID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE workspace_id = $1 AND title LIKE 'clicker fork private leader squad%'`, testWorkspaceID)
+ testPool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, ap.ID)
+ })
+
+ // The workspace owner (testUserID) — NOT the private agent's owner — clicks
+ // Run now. requireAutopilotWrite passes (workspace owner can manage), but the
+ // invoke gate keys on the clicker and denies them.
+ w = httptest.NewRecorder()
+ r = newRequest("POST", "/api/autopilots/"+ap.ID+"/trigger?workspace_id="+testWorkspaceID, nil)
+ r = withURLParam(r, "id", ap.ID)
+ testHandler.TriggerAutopilot(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("TriggerAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var run AutopilotRunResponse
+ if err := json.NewDecoder(w.Body).Decode(&run); err != nil {
+ t.Fatalf("decode run: %v", err)
+ }
+ if run.Status != "skipped" {
+ t.Fatalf("run status = %q, want skipped (non-owner clicker blocked)", run.Status)
+ }
+ if run.ReasonCode == nil || *run.ReasonCode != string(ReasonInvocationNotAllowed) {
+ got := "<nil>"
+ if run.ReasonCode != nil {
+ got = *run.ReasonCode
+ }
+ t.Fatalf("reason_code = %s, want %s", got, ReasonInvocationNotAllowed)
+ }
+}
+
// TestTriggerAutopilot_SquadPrivateLeader_PlainMemberCreator_Blocked verifies
// that if an autopilot pointing to a private-leader squad was somehow saved
// by a plain member (legacy data), dispatch is blocked at runtime.
diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.go
index a51f92a371..bc01edd751 100644
--- a/server/internal/handler/autopilot_webhook_handler_test.go
+++ b/server/internal/handler/autopilot_webhook_handler_test.go
@@ -77,6 +77,58 @@ func createWebhookTriggerViaHandler(t *testing.T, autopilotID string) AutopilotT
return resp
}
+// TestCreateTrigger_RepublishesRuleVersionAtomically verifies Elon's final Phase 1
+// must-fix: creating a trigger (a substantive change to what fires, MUL-4302 §3.4)
+// republishes the autopilot's rule version with the acting member as publisher,
+// written atomically in the same tx as the trigger INSERT — for BOTH the webhook
+// create path (mint-with-retry, whole attempt wrapped in a tx) and the schedule path.
+func TestCreateTrigger_RepublishesRuleVersionAtomically(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "TriggerVersion Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ ctx := context.Background()
+ verParams := db.GetActiveAutopilotRuleVersionParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AutopilotID: parseUUID(apID),
+ }
+
+ // The test autopilot is inserted directly (no v1), so no rule version exists yet.
+ if _, err := testHandler.Queries.GetActiveAutopilotRuleVersion(ctx, verParams); err == nil {
+ t.Fatal("expected no rule version before any trigger is created")
+ }
+
+ // Webhook create (mint-with-retry) republishes atomically.
+ createWebhookTriggerViaHandler(t, apID)
+ ver, err := testHandler.Queries.GetActiveAutopilotRuleVersion(ctx, verParams)
+ if err != nil {
+ t.Fatalf("webhook trigger create must republish a rule version: %v", err)
+ }
+ if ver.PublishedByType != "member" || uuidToString(ver.PublishedByID) != testUserID {
+ t.Errorf("webhook version published_by = %s/%s, want member/%s", ver.PublishedByType, uuidToString(ver.PublishedByID), testUserID)
+ }
+
+ // Schedule create appends a fresh version, also published by the acting member.
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{
+ "kind": "schedule",
+ "cron_expression": "0 0 * * *",
+ })
+ req = withURLParam(req, "id", apID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("schedule CreateAutopilotTrigger: got %d body=%s", w.Code, w.Body.String())
+ }
+ ver2, err := testHandler.Queries.GetActiveAutopilotRuleVersion(ctx, verParams)
+ if err != nil {
+ t.Fatalf("schedule trigger create must republish a rule version: %v", err)
+ }
+ if ver2.ID.Bytes == ver.ID.Bytes {
+ t.Error("schedule create must append a NEW rule version, not reuse the webhook one")
+ }
+ if ver2.PublishedByType != "member" || uuidToString(ver2.PublishedByID) != testUserID {
+ t.Errorf("schedule version published_by = %s/%s, want member/%s", ver2.PublishedByType, uuidToString(ver2.PublishedByID), testUserID)
+ }
+}
+
// createWebhookTriggerWithFilters builds the request body with a real JSON
// array — the same shape the frontend sends. Earlier revisions of this
// helper marshaled the filters separately and assigned the resulting
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index ca40725066..26458a6122 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -666,6 +666,21 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
return
}
+ // Re-run the INVOKE gate on every send, not just the softer view gate in
+ // gateChatSessionForUser (MUL-4525). canAccessPrivateAgent lets a workspace
+ // admin keep reading a transcript, but sending a message enqueues a run and
+ // must satisfy canInvokeAgent — which has no admin bypass. A session created
+ // while the user could invoke the agent must stop enqueuing work the instant
+ // that permission is revoked (agent flipped private, ownership moved, target
+ // removed from the allow-list), and it must fail BEFORE we persist the user
+ // message / attachments / task. Blocked returns a structured, enumeration-safe
+ // reason so the composer can explain it without leaking private-agent details.
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ if !h.canInvokeAgent(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
+
// Detect whether this is the very first human message in the session,
// BEFORE we insert the new row. This scopes LLM auto-titling (MUL-4295) to
// the opening turn: we upgrade the default/original title exactly once, off
@@ -683,8 +698,8 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// all commit together, and the daemon is only notified after the commit. For
// web chat the sender is the authenticated request user (sessions are
// creator-only), so they are the task initiator — surfaced to the agent
- // under `## Task Initiator`.
- actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ // under `## Task Initiator`. actorType/actorID were resolved above for the
+ // invoke gate.
sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
@@ -1340,6 +1355,7 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
resp := CancelTaskByUserResponse{
AgentTaskResponse: taskToResponse(cancelled.Task, workspaceID),
}
+ h.hydrateTaskAttributions(r.Context(), []*TaskAttribution{resp.AgentTaskResponse.Attribution})
if cancelled.CancelledChatMessage != nil {
attachments := make([]AttachmentResponse, 0, len(cancelled.CancelledChatMessage.Attachments))
for _, a := range cancelled.CancelledChatMessage.Attachments {
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index fee5b55b4f..5103460b77 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"sort"
@@ -58,6 +59,25 @@ type CommentResponse struct {
// pulls the folded comments back with `comment list --full`.
ThreadResolved *bool `json:"thread_resolved,omitempty"`
FoldedCount *int `json:"folded_count,omitempty"`
+ // TriggerOutcomes is the per-target result of every EXPLICIT @agent / @squad
+ // mention in this comment (MUL-4525 §2). It is additive and populated only on
+ // create/edit responses: old clients ignore it. A saved comment whose mention
+ // was blocked (no invoke permission, target unavailable, runtime offline) now
+ // reports that here instead of silently dropping the trigger, so the client
+ // can show "comment posted, but N targets were not triggered".
+ TriggerOutcomes []CommentTriggerOutcome `json:"trigger_outcomes,omitempty"`
+}
+
+// CommentTriggerOutcome is the per-target result of an explicit @agent / @squad
+// mention (MUL-4525 §2). target_id is the id the user mentioned — the agent id,
+// or the SQUAD id for a squad mention — so the client correlates it back to the
+// mention it rendered without the server echoing a private target's name/owner.
+// reason_code is the stable, enumeration-safe admission reason.
+type CommentTriggerOutcome struct {
+ TargetType string `json:"target_type"` // "agent" | "squad"
+ TargetID string `json:"target_id"`
+ Status DispatchStatus `json:"status"` // queued | coalesced | deferred | blocked
+ ReasonCode DispatchReasonCode `json:"reason_code"`
}
func commentToResponse(c db.Comment, reactions []ReactionResponse, attachments []AttachmentResponse) CommentResponse {
@@ -986,6 +1006,11 @@ type CommentTriggerPreviewRequest struct {
type CommentTriggerPreviewResponse struct {
Agents []CommentTriggerAgentResponse `json:"agents"`
+ // Blocked lists explicit @agent / @squad mentions that will NOT trigger if
+ // this comment is posted as-is (MUL-4525 §2). Additive: old clients ignore
+ // it. It lets the composer warn before sending instead of the user only
+ // discovering the silent no-op afterwards.
+ Blocked []CommentTriggerOutcome `json:"blocked,omitempty"`
}
type CommentTriggerAgentResponse struct {
@@ -1153,8 +1178,11 @@ func (h *Handler) PreviewCommentTriggers(w http.ResponseWriter, r *http.Request)
actorType, actorID := h.resolveActor(r, userID, uuidToString(issue.WorkspaceID))
opts.OriginatorUserID = h.invokeOriginatorFromRequest(r, actorType, actorID)
- triggers := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)
- resp := CommentTriggerPreviewResponse{Agents: make([]CommentTriggerAgentResponse, 0, len(triggers))}
+ triggers, targets := h.computeCommentAgentTriggers(r.Context(), issue, content, parentComment, actorType, actorID, opts)
+ resp := CommentTriggerPreviewResponse{
+ Agents: make([]CommentTriggerAgentResponse, 0, len(triggers)),
+ Blocked: commentBlockedTargetOutcomes(targets),
+ }
for _, trigger := range triggers {
resp.Agents = append(resp.Agents, commentAgentTriggerToResponse(trigger))
}
@@ -1371,7 +1399,10 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
}
originatorUserID := h.invokeOriginatorFromRequest(r, authorType, authorID)
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)
+ // The comment is already saved; a blocked mention must not fail the whole
+ // request. Surface the per-target outcomes so the client can show partial
+ // success instead of a silent no-op (MUL-4525 §2).
+ resp.TriggerOutcomes = h.triggerTasksForComment(r.Context(), issue, comment, parentComment, authorType, authorID, originatorUserID, suppressAgentIDs)
writeJSON(w, http.StatusCreated, resp)
}
@@ -1394,16 +1425,22 @@ func isNoteComment(content string) bool {
return strings.EqualFold(firstToken, noteCommentPrefix)
}
-func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs []pgtype.UUID) {
+// triggerTasksForComment resolves and enqueues the comment's agent triggers and
+// returns the per-target outcomes for explicit @agent / @squad mentions
+// (MUL-4525 §2): blocked mentions from resolution plus queued / coalesced /
+// deferred / blocked from enqueue. UI-suppressed triggers (the user unchecked
+// them) are removed before enqueue and produce no outcome.
+func (h *Handler) triggerTasksForComment(ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, actorType, actorID, originatorUserID string, suppressAgentIDs []pgtype.UUID) []CommentTriggerOutcome {
if isNoteComment(comment.Content) {
- return
+ return nil
}
- triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
+ triggers, targets := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
ExcludeTriggerCommentID: comment.ID,
OriginatorUserID: originatorUserID,
})
triggers = filterSuppressedCommentAgentTriggers(triggers, suppressAgentIDs)
- h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
+ enqueued := h.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
+ return commentTriggerOutcomes(targets, enqueued)
}
func filterSuppressedCommentAgentTriggers(triggers []commentAgentTrigger, suppressAgentIDs []pgtype.UUID) []commentAgentTrigger {
@@ -1429,7 +1466,24 @@ func filterSuppressedCommentAgentTriggers(triggers []commentAgentTrigger, suppre
return filtered
}
-func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) {
+// commentEnqueueResult is the domain outcome of enqueuing ONE executing agent.
+// execSquadID is the squad whose leader context the run actually carries (set
+// only for a squad-leader execution), so a DIFFERENT squad that shares this
+// leader can be reported honestly as coalesced rather than as if its own leader
+// context ran.
+type commentEnqueueResult struct {
+ status DispatchStatus
+ reason DispatchReasonCode
+ execSquadID string
+}
+
+// enqueueCommentAgentTriggers enqueues each resolved trigger (already deduped by
+// executing agent) and returns the result keyed by executing agent id
+// (MUL-4525 §2). Outcomes are later fanned from these to every explicit mention
+// target that resolved to the agent, so coalescing a run never drops a named
+// target's outcome. queued / coalesced / deferred are success-shaped (the run
+// was handled, no duplicate task); only a real enqueue failure is blocked.
+func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, triggers []commentAgentTrigger) map[string]commentEnqueueResult {
var escalationDelay time.Duration
escalationDelayLoaded := false
getEscalationDelay := func() time.Duration {
@@ -1439,6 +1493,14 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
}
return escalationDelay
}
+ results := make(map[string]commentEnqueueResult, len(triggers))
+ record := func(trigger commentAgentTrigger, status DispatchStatus, reason DispatchReasonCode) {
+ execSquadID := ""
+ if trigger.Squad != nil {
+ execSquadID = uuidToString(trigger.Squad.ID)
+ }
+ results[uuidToString(trigger.Agent.ID)] = commentEnqueueResult{status: status, reason: reason, execSquadID: execSquadID}
+ }
for _, trigger := range triggers {
if trigger.AlreadyPending {
// MUL-4195: a queued/dispatched task for this (issue, agent)
@@ -1447,7 +1509,16 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
// queued (not-yet-claimed) task so a single run still covers every
// comment, re-stamping the run's originator/overlay to the new
// comment (mergeCommentIntoPendingTask).
- if h.mergeCommentIntoPendingTask(ctx, issue, trigger, triggerCommentID) {
+ //
+ // The merge reports HOW it resolved: a real merge is coalesced, a
+ // fail-closed / failed merge is blocked (attribution_blocked /
+ // internal_error) — never mislabeled as success (MUL-4525 §2, Elon
+ // round 5). Only "no queued task to fold into" falls through to the
+ // active-task decision below.
+ if status, reason, terminal := commentMergeTerminalOutcome(
+ h.mergeCommentIntoPendingTask(ctx, issue, trigger, triggerCommentID),
+ ); terminal {
+ record(trigger, status, reason)
continue
}
// The merge found no queued task to fold into: the existing task
@@ -1459,23 +1530,94 @@ func (h *Handler) enqueueCommentAgentTriggers(ctx context.Context, issue db.Issu
// duplicate concurrent run. When an active task exists, its
// completion reconcile (reconcileCommentsOnCompletion) is what
// guarantees this comment earns a bounded follow-up. Only when NO
- // active task exists is a fresh enqueue both safe and necessary.
- if h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID) {
+ // active task exists is a fresh enqueue both safe and necessary. On a
+ // query failure we fail closed (no fresh enqueue) and report a
+ // non-success internal_error rather than a fabricated deferred.
+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, trigger.Agent.ID)
+ if status, reason, enqueueFresh := decidePostMergeMiss(active, activeErr); !enqueueFresh {
+ record(trigger, status, reason)
continue
}
}
- h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger, getEscalationDelay)
+ if err := h.enqueueSingleCommentTrigger(ctx, issue, triggerCommentID, trigger, getEscalationDelay); err != nil {
+ record(trigger, DispatchBlocked, commentEnqueueFailureReason(err))
+ continue
+ }
+ record(trigger, DispatchQueued, ReasonQueued)
}
+ return results
+}
+
+// commentTriggerOutcomes maps each explicit mention target to its final outcome
+// (MUL-4525 §2): a target that resolved to an executing agent takes that agent's
+// enqueue status, so several mentions coalescing into one run each still get
+// their own outcome; a terminal target (blocked / self-suppressed) carries its
+// own status. A target whose executing agent has no enqueue result — because the
+// composer suppressed (unchecked) it — yields no outcome, since the user opted
+// out deliberately.
+func commentTriggerOutcomes(targets []commentMentionTarget, enqueued map[string]commentEnqueueResult) []CommentTriggerOutcome {
+ if len(targets) == 0 {
+ return nil
+ }
+ outcomes := make([]CommentTriggerOutcome, 0, len(targets))
+ for _, t := range targets {
+ if t.ExecAgentID != "" {
+ res, ok := enqueued[t.ExecAgentID]
+ if !ok {
+ continue
+ }
+ status, reason := res.status, res.reason
+ // A @squad whose shared leader ran, but under a DIFFERENT squad's
+ // context, did not get its own leader briefing injected — the single
+ // leader run (one task per issue+agent) merely folds it in. Report
+ // coalesced, not queued, so we never claim this squad's leader
+ // context executed (MUL-4525, Elon round 3).
+ if t.TargetType == "squad" && res.execSquadID != "" && res.execSquadID != t.TargetID && status == DispatchQueued {
+ status, reason = DispatchCoalesced, ReasonCoalesced
+ }
+ outcomes = append(outcomes, CommentTriggerOutcome{TargetType: t.TargetType, TargetID: t.TargetID, Status: status, ReasonCode: reason})
+ continue
+ }
+ outcomes = append(outcomes, CommentTriggerOutcome{TargetType: t.TargetType, TargetID: t.TargetID, Status: t.Status, ReasonCode: t.ReasonCode})
+ }
+ return outcomes
+}
+
+// commentBlockedTargetOutcomes is the composer-preview projection: the explicit
+// mentions that will NOT trigger if the comment is posted as-is (MUL-4525 §2). A
+// resolvable/executing target instead appears in the preview `agents` list, so
+// only terminal blocked targets surface here.
+func commentBlockedTargetOutcomes(targets []commentMentionTarget) []CommentTriggerOutcome {
+ var blocked []CommentTriggerOutcome
+ for _, t := range targets {
+ if t.Status == DispatchBlocked {
+ blocked = append(blocked, CommentTriggerOutcome{TargetType: t.TargetType, TargetID: t.TargetID, Status: t.Status, ReasonCode: t.ReasonCode})
+ }
+ }
+ return blocked
+}
+
+// commentEnqueueFailureReason types an enqueue error that reached the response
+// (MUL-4525 §2). The admission gate (canInvokeAgent / archived / runtime) already
+// ran during resolution, so a failure here is either a fail-closed attribution
+// refusal (attribution_blocked, typed via errors.Is) or a rare race /
+// infrastructure error that stays an unclassified internal error rather than
+// leaking the raw message.
+func commentEnqueueFailureReason(err error) DispatchReasonCode {
+ if errors.Is(err, service.ErrAttributionFailClosed) {
+ return ReasonAttributionBlocked
+ }
+ return ReasonInternalError
}
// hasActiveTaskForIssueAndAgent reports whether the (issue, agent) pair has any
-// non-terminal task whose completion will drive completion reconciliation. Used
-// by the comment enqueue path to decide, after a merge miss, between deferring
-// to reconcile (an active task exists) and enqueuing a fresh follow-up (none
-// does). Fail-closed: on a DB error we return true so the caller does NOT
-// enqueue a possibly-colliding duplicate — worst case the comment is caught by
-// reconcile rather than double-run.
-func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID) bool {
+// non-terminal task whose completion will drive completion reconciliation. It
+// returns the query error rather than swallowing it (MUL-4525, Elon round 4):
+// callers must fail closed on error (never enqueue a possibly-colliding
+// duplicate) AND must not report a success — "cannot confirm whether a run is
+// active" is never the same as "a run is active". See decidePostMergeMiss /
+// decideSuppressedLeaderOutcome for the two decisions.
+func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, agentID pgtype.UUID) (bool, error) {
active, err := h.Queries.HasActiveTaskForIssueAndAgent(ctx, db.HasActiveTaskForIssueAndAgentParams{
IssueID: issueID,
AgentID: agentID,
@@ -1483,48 +1625,134 @@ func (h *Handler) hasActiveTaskForIssueAndAgent(ctx context.Context, issueID, ag
if err != nil {
slog.Warn("has active task for issue+agent check failed",
"issue_id", uuidToString(issueID), "agent_id", uuidToString(agentID), "error", err)
- return true
+ return false, err
+ }
+ return active, nil
+}
+
+// decidePostMergeMiss decides what to do after a comment merge missed on a
+// target that had a pending task (MUL-4525, Elon round 4). On a query failure
+// (activeErr != nil) it FAILS CLOSED: never enqueue a fresh task — a duplicate
+// concurrent run risk — and report a non-success internal_error, since we cannot
+// confirm a run is active. A confirmed active task defers to that run's
+// reconcile; only a confirmed-none enqueues a fresh follow-up.
+func decidePostMergeMiss(active bool, activeErr error) (status DispatchStatus, reason DispatchReasonCode, enqueueFresh bool) {
+ switch {
+ case activeErr != nil:
+ return DispatchBlocked, ReasonInternalError, false
+ case active:
+ return DispatchDeferred, ReasonDeferred, false
+ default:
+ return "", "", true
+ }
+}
+
+// decideSuppressedLeaderOutcome maps the self-trigger-suppressed squad leader's
+// active-task check to an honest outcome (MUL-4525, Elon round 4). A query
+// failure is never success — it is internal_error, not a fabricated deferred.
+// A confirmed active run defers (its reconcile covers the comment); otherwise
+// nothing runs and the outcome is self_trigger_suppressed.
+func decideSuppressedLeaderOutcome(active bool, activeErr error) (DispatchStatus, DispatchReasonCode) {
+ switch {
+ case activeErr != nil:
+ return DispatchBlocked, ReasonInternalError
+ case active:
+ return DispatchDeferred, ReasonAlreadyActive
+ default:
+ return DispatchBlocked, ReasonSelfTriggerSuppressed
+ }
+}
+
+// commentMergeResult distinguishes how a pending-task merge attempt resolved so
+// the caller can report an HONEST outcome (MUL-4525, Elon round 5). A real merge
+// is coalesced, but a REFUSED or FAILED merge — even when we correctly fail
+// closed by keeping the original task and not enqueuing a duplicate — must NOT
+// be reported as a success-shaped coalesced.
+type commentMergeResult int
+
+const (
+ // commentMergeSucceeded: the comment folded into the queued task → coalesced.
+ commentMergeSucceeded commentMergeResult = iota
+ // commentMergeNoPendingTask: no queued task to merge into anymore (it was
+ // claimed/started between the dedup check and now). The caller runs the
+ // active-task decision (defer vs fresh enqueue).
+ commentMergeNoPendingTask
+ // commentMergeAttributionBlocked: fail-closed attribution refused re-stamping
+ // the merge. The original task is kept and no fresh task is enqueued, but the
+ // re-attribution did NOT happen → outcome attribution_blocked, not success.
+ commentMergeAttributionBlocked
+ // commentMergeError: an unknown attribution/DB error. Fail closed (keep the
+ // task, no duplicate enqueue), but the merge did not complete → outcome
+ // internal_error, not success.
+ commentMergeError
+)
+
+// commentMergeTerminalOutcome maps a merge result that carries its own final
+// outcome (everything except commentMergeNoPendingTask, which needs the
+// active-task decision) to the reported (status, reason). terminal=false only
+// for commentMergeNoPendingTask.
+func commentMergeTerminalOutcome(result commentMergeResult) (status DispatchStatus, reason DispatchReasonCode, terminal bool) {
+ switch result {
+ case commentMergeSucceeded:
+ return DispatchCoalesced, ReasonCoalesced, true
+ case commentMergeAttributionBlocked:
+ return DispatchBlocked, ReasonAttributionBlocked, true
+ case commentMergeError:
+ return DispatchBlocked, ReasonInternalError, true
+ default: // commentMergeNoPendingTask
+ return "", "", false
}
- return active
}
-// mergeCommentIntoPendingTask folds a newly-arrived comment into an existing
-// not-yet-started task for (issue, agent) instead of dropping it (MUL-4195).
-// Returns true when the comment was HANDLED — either merged, or a non-fatal DB
-// error we deliberately do not convert into a duplicate task. Returns false
-// only when no pending task exists anymore (pgx.ErrNoRows: it was
-// claimed/started between the dedup check and now), so the caller enqueues a
-// fresh task and the deliberate comment is never lost.
-//
-// The merge is GATED on the originator being unchanged (MUL-4195 review
// mergeCommentIntoPendingTask folds a newly-arrived comment into the existing
// QUEUED (not-yet-claimed) task for (issue, agent) instead of dropping it
-// (MUL-4195). Returns true when the comment was handled (merged, or a
-// non-fatal DB error we deliberately do not turn into a duplicate). Returns
-// false only when no queued task exists to merge into (pgx.ErrNoRows) — the
-// existing task is already dispatched/running, or was just claimed — in which
-// case the caller decides between deferring to completion reconcile and a fresh
-// enqueue.
+// (MUL-4195). It reports HOW it resolved via commentMergeResult so the caller
+// never mislabels a refused/failed merge as success (MUL-4525 §2). No path here
+// enqueues a duplicate: on any failure the original task is kept intact, so the
+// comment is still read by that run and its instruction is not lost — only the
+// re-attribution / merge bookkeeping is declined, and that is surfaced honestly.
//
-// Recompute-on-merge (MUL-4195 review must-fix #1): the run's
+// Recompute-on-merge (MUL-4195 review must-fix #1): on success the run's
// originator_user_id, runtime_mcp_overlay and runtime_connected_apps are
// re-stamped to the NEW trigger comment's originator, and trigger_summary is
-// refreshed. This is what lets a different member's comment safely fold into a
-// task another member created: the single coalescing run then carries the
-// latest instruction's originator and the matching connected-app overlay,
-// instead of answering the new comment under the original user's capabilities
-// and audit identity. It also replaces the earlier originator gate + fresh
-// fallback, which could not create a second pending task anyway (the
-// one-pending-per-(issue,agent) unique index) and so silently dropped the
-// mismatched-originator comment.
-func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, newTriggerCommentID pgtype.UUID) bool {
- originator := h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, newTriggerCommentID)
- overlay, connectedApps := h.TaskService.BuildRuntimeMCPOverlayForMerge(ctx, originator, trigger.Agent)
+// refreshed — so a different member's comment safely folds into a task another
+// member created, the coalescing run carrying the latest instruction's
+// originator and matching connected-app overlay.
+func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issue, trigger commentAgentTrigger, newTriggerCommentID pgtype.UUID) commentMergeResult {
+ // Re-attribute the coalescing run to the new comment's human atomically: the
+ // whole attribution snapshot moves, not just the person columns (MUL-4302). An
+ // issue-assignee reaction is comment_source; a mention / thread-parent /
+ // conversation hop is delegation.
+ isMention := trigger.Source != commentTriggerSourceIssueAssignee
+ attr, err := h.TaskService.AttributionForMergedComment(ctx, issue.WorkspaceID, newTriggerCommentID, isMention, trigger.Agent)
+ if err != nil {
+ // The new comment cannot be re-attributed. REFUSE the merge — keep the
+ // existing queued task on its original (precise) snapshot rather than
+ // re-stamp it to a degraded owner_fallback, and never spawn a duplicate.
+ // A fail-closed refusal is a distinct, honest outcome (attribution_blocked);
+ // any other error is unclassified (internal_error) — neither is success.
+ slog.Warn("refused comment merge: attribution failed, keeping original task snapshot",
+ "issue_id", uuidToString(issue.ID),
+ "agent_id", uuidToString(trigger.Agent.ID),
+ "new_trigger_comment_id", uuidToString(newTriggerCommentID),
+ "error", err)
+ if errors.Is(err, service.ErrAttributionFailClosed) {
+ return commentMergeAttributionBlocked
+ }
+ return commentMergeError
+ }
+ overlay, connectedApps := h.TaskService.BuildRuntimeMCPOverlayForMerge(ctx, attr.UserID, trigger.Agent)
row, err := h.Queries.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
IssueID: issue.ID,
AgentID: trigger.Agent.ID,
NewTriggerCommentID: newTriggerCommentID,
- NewOriginatorUserID: originator,
+ NewOriginatorUserID: attr.UserID,
+ NewAccountableUserID: attr.AccountableUserID,
+ NewOriginatorSource: pgtype.Text{String: attr.Source.String(), Valid: true},
+ NewDelegatedFromTaskID: attr.DelegatedFromTaskID,
+ NewRuleVersionID: attr.RuleVersionID,
+ NewTriggerEvidenceKind: pgtype.Text{String: string(attr.EvidenceKind), Valid: attr.EvidenceKind != ""},
+ NewTriggerEvidenceRefID: attr.EvidenceRefID,
NewTriggerSummary: h.TaskService.BuildCommentTriggerSummary(ctx, issue.WorkspaceID, newTriggerCommentID),
NewRuntimeMcpOverlay: overlay,
NewRuntimeConnectedApps: connectedApps,
@@ -1534,15 +1762,16 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issu
// No pre-claim (queued/deferred) task to merge into. The caller
// defers to completion reconcile when an active task exists, or
// enqueues fresh when none does.
- return false
+ return commentMergeNoPendingTask
}
// Unknown error: the pending task most likely still exists, so do NOT
- // risk enqueuing a duplicate. Log and treat as handled.
+ // risk enqueuing a duplicate — but the merge did not happen, so this is
+ // not a success.
slog.Warn("merge comment into pending task failed",
"issue_id", uuidToString(issue.ID),
"agent_id", uuidToString(trigger.Agent.ID),
"error", err)
- return true
+ return commentMergeError
}
slog.Info("merged comment into pending task",
"task_id", uuidToString(row.ID),
@@ -1550,13 +1779,17 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issu
"agent_id", uuidToString(trigger.Agent.ID),
"new_trigger_comment_id", uuidToString(newTriggerCommentID),
"coalesced_count", len(row.CoalescedCommentIds))
- return true
+ return commentMergeSucceeded
}
// enqueueSingleCommentTrigger creates a fresh task for one computed trigger.
// Split out of enqueueCommentAgentTriggers so the merge-not-drop path
// (MUL-4195) can fall back to it when a pending task vanished mid-flight.
-func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, trigger commentAgentTrigger, getEscalationDelay func() time.Duration) {
+// enqueueSingleCommentTrigger enqueues one resolved trigger and returns the
+// PRIMARY enqueue error (nil on success) so the caller can surface a
+// trigger_outcome (MUL-4525 §2). Secondary work (the deferred escalation
+// fallback) stays best-effort logged and does not affect the returned error.
+func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, trigger commentAgentTrigger, getEscalationDelay func() time.Duration) error {
switch trigger.Source {
case commentTriggerSourceIssueAssignee:
if trigger.Squad != nil {
@@ -1566,11 +1799,13 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
"squad_id", uuidToString(trigger.Squad.ID),
"leader_id", uuidToString(trigger.Agent.ID),
"error", err)
+ return err
}
- return
+ return nil
}
if _, err := h.TaskService.EnqueueTaskForIssue(ctx, issue, triggerCommentID); err != nil {
slog.Warn("enqueue agent task on comment failed", "issue_id", uuidToString(issue.ID), "error", err)
+ return err
}
case commentTriggerSourceMentionSquadLeader:
if _, err := h.TaskService.EnqueueTaskForSquadLeader(ctx, issue, trigger.Agent.ID, trigger.Squad.ID, triggerCommentID); err != nil {
@@ -1578,6 +1813,7 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
"issue_id", uuidToString(issue.ID),
"agent_id", uuidToString(trigger.Agent.ID),
"error", err)
+ return err
}
case commentTriggerSourceMentionAgent:
if _, err := h.TaskService.EnqueueTaskForMention(ctx, issue, trigger.Agent.ID, triggerCommentID); err != nil {
@@ -1585,6 +1821,7 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
"issue_id", uuidToString(issue.ID),
"agent_id", uuidToString(trigger.Agent.ID),
"error", err)
+ return err
}
case commentTriggerSourceThreadParent, commentTriggerSourceConversation:
var task db.AgentTaskQueue
@@ -1600,10 +1837,10 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
"agent_id", uuidToString(trigger.Agent.ID),
"source", trigger.Source,
"error", err)
- return
+ return err
}
if trigger.EscalationFallback == nil || getEscalationDelay() <= 0 {
- return
+ return nil
}
var squadID pgtype.UUID
if trigger.EscalationFallback.Squad != nil {
@@ -1617,23 +1854,29 @@ func (h *Handler) enqueueSingleCommentTrigger(ctx context.Context, issue db.Issu
"error", err)
}
}
+ return nil
}
-func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
+// computeCommentAgentTriggers resolves which agents a comment triggers (deduped
+// by executing agent), plus the per-target list for every EXPLICIT @agent /
+// @squad mention (MUL-4525 §2). Targets come only from the explicit-mention path
+// — the implicit routing fallbacks (assignee, thread parent, conversation) were
+// never named by the user, so a no-route there is not a silent no-op.
+func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issue, content string, parentComment *db.Comment, actorType, actorID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, []commentMentionTarget) {
if isNoteComment(content) {
- return nil
+ return nil, nil
}
mentions := util.ParseMentions(content)
if util.HasMentionAll(mentions) {
- return nil
+ return nil, nil
}
if hasAgentOrSquadMention(mentions) {
return h.resolveMentionedAgentCommentTriggers(ctx, issue, mentions, actorType, actorID, opts)
}
if hasMemberMention(mentions) {
- return nil
+ return nil, nil
}
if actorType != "member" {
@@ -1649,16 +1892,16 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
// target alongside the assigned leader.
if issue.AssigneeType.Valid && issue.AssigneeType.String == "squad" {
if trigger, ok := h.routeAssignedSquadLeaderFallback(ctx, issue, actorType, actorID, opts); ok {
- return []commentAgentTrigger{trigger}
+ return []commentAgentTrigger{trigger}, nil
}
}
- return nil
+ return nil, nil
}
if parentComment != nil && parentComment.AuthorType == "agent" {
trigger, ok := h.routeReplyToParentAuthor(ctx, issue, parentComment, actorType, actorID, opts)
if !ok {
- return nil
+ return nil, nil
}
if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&
uuidToString(fallback.Agent.ID) != uuidToString(trigger.Agent.ID) {
@@ -1667,14 +1910,14 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
Squad: fallback.Squad,
}
}
- return []commentAgentTrigger{trigger}
+ return []commentAgentTrigger{trigger}, nil
}
if parentComment != nil {
triggers, handled := h.routeThreadRootOwners(ctx, issue, parentComment, actorID, opts)
if handled {
if len(triggers) == 0 {
- return nil
+ return nil, nil
}
if len(triggers) == 1 {
if fallback, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok &&
@@ -1685,14 +1928,14 @@ func (h *Handler) computeCommentAgentTriggers(ctx context.Context, issue db.Issu
}
}
}
- return triggers
+ return triggers, nil
}
}
if trigger, ok := h.routeAssigneeFallback(ctx, issue, actorType, actorID, opts); ok {
- return []commentAgentTrigger{trigger}
+ return []commentAgentTrigger{trigger}, nil
}
- return nil
+ return nil, nil
}
func hasAgentOrSquadMention(mentions []util.Mention) bool {
@@ -1938,18 +2181,67 @@ func (h *Handler) hasPendingTaskForIssueAndAgent(ctx context.Context, issueID, a
// dedupe and the natural queued/dispatched coalescing of the task queue.
// Note: no issue status gate here — @mention is an explicit action and should
// work even on done/cancelled issues (the agent can reopen the issue if needed).
-func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, mentions []util.Mention, authorType, authorID string, opts commentTriggerComputeOptions) []commentAgentTrigger {
+// commentMentionTarget is one EXPLICIT @agent / @squad mention and how it
+// resolved (MUL-4525 §2). This is tracked separately from the execution
+// triggers: several mentions can resolve to the same executing agent (e.g.
+// @Agent A and @Squad S whose leader is A), and each still needs its own
+// outcome even though the run is coalesced. Exactly one of the resolution
+// fields is set:
+// - ExecAgentID non-empty → the mention runs via that executing agent; its
+// outcome mirrors the agent's enqueue status (queued/coalesced/deferred).
+// - Status set (with ReasonCode) → a terminal, non-executing outcome
+// (blocked, or an A2A self-suppressed squad leader that is deferred).
+type commentMentionTarget struct {
+ TargetType string // "agent" | "squad"
+ TargetID string
+ ExecAgentID string
+ Status DispatchStatus
+ ReasonCode DispatchReasonCode
+}
+
+func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issue db.Issue, mentions []util.Mention, authorType, authorID string, opts commentTriggerComputeOptions) ([]commentAgentTrigger, []commentMentionTarget) {
wsID := uuidToString(issue.WorkspaceID)
triggers := make([]commentAgentTrigger, 0, len(mentions))
- seen := make(map[string]struct{}, len(mentions))
+ // seen dedups EXECUTION by resolved agent id: two mentions resolving to the
+ // same agent enqueue only one task. Mapping to the trigger's index lets a
+ // squad-leader mention UPGRADE an already-added plain @agent trigger for the
+ // same agent — the leader task is a strict superset (it sets is_leader_task
+ // and squad_id so the daemon injects the squad briefing), so the merged run
+ // must carry that role regardless of mention order.
+ seen := make(map[string]int, len(mentions))
add := func(trigger commentAgentTrigger) {
id := uuidToString(trigger.Agent.ID)
- if _, ok := seen[id]; ok {
+ if idx, ok := seen[id]; ok {
+ if triggers[idx].Source != commentTriggerSourceMentionSquadLeader &&
+ trigger.Source == commentTriggerSourceMentionSquadLeader {
+ triggers[idx] = trigger
+ }
return
}
- seen[id] = struct{}{}
+ seen[id] = len(triggers)
triggers = append(triggers, trigger)
}
+ // targets record one outcome per EXPLICIT mention — deduped by the target
+ // the user named (type:id), NOT by executing agent — so no explicitly-named
+ // target is silently dropped even when its run coalesces with another's.
+ var targets []commentMentionTarget
+ targetSeen := make(map[string]struct{}, len(mentions))
+ addTarget := func(t commentMentionTarget) {
+ key := t.TargetType + ":" + t.TargetID
+ if _, ok := targetSeen[key]; ok {
+ return
+ }
+ targetSeen[key] = struct{}{}
+ targets = append(targets, t)
+ }
+ // blockTarget records a mention that will not fire. The invoke gate is
+ // evaluated BEFORE any archived/runtime state is read, so a caller who
+ // cannot invoke a private target learns only the generic
+ // invocation_not_allowed and can never enumerate the target's existence or
+ // state from the reason code.
+ blockTarget := func(targetType, targetID string, reason DispatchReasonCode) {
+ addTarget(commentMentionTarget{TargetType: targetType, TargetID: targetID, Status: DispatchBlocked, ReasonCode: reason})
+ }
for _, m := range mentions {
if m.Type == "squad" {
// @squad mention → trigger the squad's leader agent.
@@ -1959,34 +2251,54 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
WorkspaceID: issue.WorkspaceID,
})
if err != nil {
+ blockTarget("squad", m.ID, ReasonTargetUnavailable)
continue
}
leaderID := squad.LeaderID
- // Prevent self-trigger unless the agent's last activity on this
- // issue was a worker task for this same squad. Generic non-leader
- // tasks (direct @agent mentions, thread-parent replies) are not a
- // worker-role handoff and must not re-enqueue the leader.
+ // A2A self-suppression: the author IS this squad's leader and its
+ // most recent task on this issue was a leader/generic role (NOT a
+ // fresh same-squad worker→leader handoff), so we do not re-fire the
+ // leader from its own @mention. The outcome must reflect reality, not
+ // assume success (MUL-4525): `deferred` only when a real non-terminal
+ // task is still active (its reconcile covers this comment); a query
+ // failure is a non-success internal_error, never a fabricated
+ // deferred; otherwise nothing runs → self_trigger_suppressed.
if authorType == "agent" && authorID == uuidToString(leaderID) &&
h.shouldSuppressSquadLeaderSelfTrigger(ctx, issue.ID, leaderID, squad.ID) {
+ active, activeErr := h.hasActiveTaskForIssueAndAgent(ctx, issue.ID, leaderID)
+ status, reason := decideSuppressedLeaderOutcome(active, activeErr)
+ addTarget(commentMentionTarget{TargetType: "squad", TargetID: m.ID, Status: status, ReasonCode: reason})
continue
}
- // Verify leader agent is ready (has runtime, not archived).
agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
ID: leaderID,
WorkspaceID: issue.WorkspaceID,
})
- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ if err != nil {
+ blockTarget("squad", m.ID, ReasonTargetUnavailable)
continue
}
- // Private-agent gate: prevent triggering a private leader via squad mention.
+ // Private-leader gate first (enumeration-safe: a caller who cannot
+ // invoke the leader never learns its archived/runtime state).
if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {
+ blockTarget("squad", m.ID, ReasonInvocationNotAllowed)
+ continue
+ }
+ if agent.ArchivedAt.Valid {
+ blockTarget("squad", m.ID, ReasonTargetUnavailable)
+ continue
+ }
+ if !agent.RuntimeID.Valid {
+ blockTarget("squad", m.ID, ReasonRuntimeOffline)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, leaderID, opts)
if err != nil {
+ blockTarget("squad", m.ID, ReasonInternalError)
continue
}
add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionSquadLeader, Squad: &squad, AlreadyPending: hasPending})
+ addTarget(commentMentionTarget{TargetType: "squad", TargetID: m.ID, ExecAgentID: uuidToString(leaderID)})
continue
}
if m.Type != "agent" {
@@ -2003,21 +2315,34 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu
ID: agentUUID,
WorkspaceID: issue.WorkspaceID,
})
- if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {
+ if err != nil {
+ // Do not reveal whether the id exists (it may be a private agent in
+ // another workspace): the generic invocation_not_allowed is returned.
+ blockTarget("agent", m.ID, ReasonInvocationNotAllowed)
continue
}
- // Private-agent gate (member→private requires allowed_principals;
- // agent→agent always passes).
+ // Private-agent gate first, before any archived/runtime state is read.
if !h.canInvokeAgent(ctx, agent, authorType, authorID, opts.OriginatorUserID, wsID) {
+ blockTarget("agent", m.ID, ReasonInvocationNotAllowed)
+ continue
+ }
+ if agent.ArchivedAt.Valid {
+ blockTarget("agent", m.ID, ReasonTargetUnavailable)
+ continue
+ }
+ if !agent.RuntimeID.Valid {
+ blockTarget("agent", m.ID, ReasonRuntimeOffline)
continue
}
hasPending, err := h.hasPendingTaskForIssueAndAgent(ctx, issue.ID, agentUUID, opts)
if err != nil {
+ blockTarget("agent", m.ID, ReasonInternalError)
continue
}
add(commentAgentTrigger{Agent: agent, Source: commentTriggerSourceMentionAgent, AlreadyPending: hasPending})
+ addTarget(commentMentionTarget{TargetType: "agent", TargetID: m.ID, ExecAgentID: uuidToString(agentUUID)})
}
- return triggers
+ return triggers, targets
}
func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
@@ -2127,9 +2452,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to update comment")
return
}
- retriggerEditedComment := func() {
+ retriggerEditedComment := func() []CommentTriggerOutcome {
if oldContent == comment.Content {
- return
+ return nil
}
issue := *triggerIssue
var parentComment *db.Comment
@@ -2141,7 +2466,7 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
h.retriggerCancelledTaskSurvivors(r.Context(), issue, cancelled, existing.ID)
- h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)
+ return h.triggerTasksForComment(r.Context(), issue, comment, parentComment, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), suppressAgentIDs)
}
// Replace the comment attachment set when a modern client sends
@@ -2171,7 +2496,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
slog.Info("comment updated", append(logger.RequestAttrs(r), "comment_id", commentId)...)
h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, map[string]any{"comment": resp})
- retriggerEditedComment()
+ // The broadcast above intentionally omits trigger_outcomes — it is the
+ // editor's private feedback, not shared timeline state (MUL-4525 §2).
+ resp.TriggerOutcomes = retriggerEditedComment()
writeJSON(w, http.StatusOK, resp)
}
@@ -2326,7 +2653,7 @@ func (h *Handler) retriggerCancelledTaskSurvivors(ctx context.Context, issue db.
if actorType != "member" {
originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, comment.ID))
}
- triggers := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
+ triggers, _ := h.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
ExcludeTriggerCommentID: comment.ID,
OriginatorUserID: originatorUserID,
})
diff --git a/server/internal/handler/comment_decision_test.go b/server/internal/handler/comment_decision_test.go
new file mode 100644
index 0000000000..4bdb7e3496
--- /dev/null
+++ b/server/internal/handler/comment_decision_test.go
@@ -0,0 +1,105 @@
+package handler
+
+import (
+ "errors"
+ "testing"
+)
+
+// TestDecidePostMergeMiss is Elon round-4 must-fix: the active-task check governs
+// what happens after a comment merge misses. A query FAILURE must fail closed —
+// never enqueue a fresh task (a duplicate concurrent-run risk) and never report a
+// success. Only a confirmed active task defers; a confirmed-none enqueues fresh.
+// Unit-tested here because a real DB fault cannot be forced through valid inputs,
+// and this decision — not the query call — is what actually governs the branch.
+func TestDecidePostMergeMiss(t *testing.T) {
+ t.Run("query error: fail closed, non-success internal_error", func(t *testing.T) {
+ status, reason, enqueueFresh := decidePostMergeMiss(false, errors.New("db down"))
+ if enqueueFresh {
+ t.Error("enqueueFresh = true on query error; must fail closed to avoid a duplicate run")
+ }
+ if status != DispatchBlocked || reason != ReasonInternalError {
+ t.Errorf("got %s/%s, want blocked/internal_error", status, reason)
+ }
+ })
+ t.Run("query error dominates a stale active=true", func(t *testing.T) {
+ status, _, enqueueFresh := decidePostMergeMiss(true, errors.New("db down"))
+ if enqueueFresh || status != DispatchBlocked {
+ t.Errorf("got status %s enqueueFresh %v, want blocked + no fresh enqueue", status, enqueueFresh)
+ }
+ })
+ t.Run("active task: defer, no fresh enqueue", func(t *testing.T) {
+ status, reason, enqueueFresh := decidePostMergeMiss(true, nil)
+ if enqueueFresh || status != DispatchDeferred || reason != ReasonDeferred {
+ t.Errorf("got %s/%s enqueueFresh %v, want deferred + no fresh enqueue", status, reason, enqueueFresh)
+ }
+ })
+ t.Run("no active task: enqueue a fresh follow-up", func(t *testing.T) {
+ _, _, enqueueFresh := decidePostMergeMiss(false, nil)
+ if !enqueueFresh {
+ t.Error("enqueueFresh = false with no active task; a fresh follow-up must run")
+ }
+ })
+}
+
+// TestCommentMergeTerminalOutcome is Elon round-5 must-fix: a pending-task merge
+// must report an HONEST public outcome. Only a real merge is coalesced; a
+// fail-closed refusal is blocked/attribution_blocked and any other failure is
+// blocked/internal_error — never a fabricated coalesced success. Only
+// "no queued task to fold into" is non-terminal (the caller runs the active-task
+// decision). Pure-tested because a real DB/attribution fault cannot be forced
+// through valid handler inputs, and this mapping is what governs the outcome.
+func TestCommentMergeTerminalOutcome(t *testing.T) {
+ cases := []struct {
+ name string
+ result commentMergeResult
+ wantTerminal bool
+ wantStatus DispatchStatus
+ wantReason DispatchReasonCode
+ }{
+ {"real merge coalesces", commentMergeSucceeded, true, DispatchCoalesced, ReasonCoalesced},
+ {"attribution fail-closed is blocked, not success", commentMergeAttributionBlocked, true, DispatchBlocked, ReasonAttributionBlocked},
+ {"unknown error is blocked, not success", commentMergeError, true, DispatchBlocked, ReasonInternalError},
+ {"no pending task defers to active-task decision", commentMergeNoPendingTask, false, "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ status, reason, terminal := commentMergeTerminalOutcome(tc.result)
+ if terminal != tc.wantTerminal {
+ t.Errorf("terminal = %v, want %v", terminal, tc.wantTerminal)
+ }
+ if status != tc.wantStatus || reason != tc.wantReason {
+ t.Errorf("got %q/%q, want %q/%q", status, reason, tc.wantStatus, tc.wantReason)
+ }
+ if tc.wantTerminal && status != DispatchCoalesced && status != DispatchBlocked {
+ t.Errorf("terminal outcome %q is neither the coalesced success nor a blocked failure", status)
+ }
+ })
+ }
+}
+
+// TestDecideSuppressedLeaderOutcome: the self-trigger-suppressed squad leader's
+// active-task check must never fake success — a query error is a non-success
+// internal_error, a confirmed active run defers, and a confirmed-none is
+// self_trigger_suppressed (MUL-4525, Elon round 4).
+func TestDecideSuppressedLeaderOutcome(t *testing.T) {
+ cases := []struct {
+ name string
+ active bool
+ err error
+ wantStatus DispatchStatus
+ wantReason DispatchReasonCode
+ }{
+ {"query error", false, errors.New("db down"), DispatchBlocked, ReasonInternalError},
+ {"query error dominates stale active", true, errors.New("db down"), DispatchBlocked, ReasonInternalError},
+ {"active run", true, nil, DispatchDeferred, ReasonAlreadyActive},
+ {"no active run", false, nil, DispatchBlocked, ReasonSelfTriggerSuppressed},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ status, reason := decideSuppressedLeaderOutcome(tc.active, tc.err)
+ if status != tc.wantStatus || reason != tc.wantReason {
+ t.Errorf("got %s/%s, want %s/%s", status, reason, tc.wantStatus, tc.wantReason)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/comment_merge_failclosed_test.go b/server/internal/handler/comment_merge_failclosed_test.go
new file mode 100644
index 0000000000..e0ac4d4c47
--- /dev/null
+++ b/server/internal/handler/comment_merge_failclosed_test.go
@@ -0,0 +1,137 @@
+package handler
+
+import (
+ "context"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestMergeCommentIntoPendingTask_FailClosedKeepsOriginalSnapshot is Elon's must-fix
+// regression exercising the REAL merge path (mergeCommentIntoPendingTask), not just the
+// service helper. On a fail-closed workspace, folding a comment that resolves to no
+// precise human must REFUSE the merge and leave the queued task's entire attribution
+// snapshot (trigger comment, originator, accountable, source) intact — never re-stamped
+// to a degraded owner_fallback. A fail-open control proves the same comment DOES merge
+// (owner_fallback) when the workspace permits the degrade (MUL-4302).
+func TestMergeCommentIntoPendingTask_FailClosedKeepsOriginalSnapshot(t *testing.T) {
+ ctx := context.Background()
+ agentID := createWebhookTestAgent(t, "MergeFailClosed Agent")
+
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `SELECT runtime_id FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("load runtime: %v", err)
+ }
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority)
+ VALUES ($1, 'merge fail-closed', 'member', $2, 'agent', $3, 'medium') RETURNING id`,
+ testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ // cidA: the precise member comment the queued task is attributed to.
+ var cidA string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'please do X') RETURNING id`,
+ issueID, testWorkspaceID, testUserID).Scan(&cidA); err != nil {
+ t.Fatalf("seed comment A: %v", err)
+ }
+ // cidB: an agent comment with no source-task lineage → resolves to no precise human.
+ var cidB string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'autonomous follow-up') RETURNING id`,
+ issueID, testWorkspaceID, agentID).Scan(&cidB); err != nil {
+ t.Fatalf("seed comment B: %v", err)
+ }
+
+ // A QUEUED task with a fully precise snapshot triggered by cidA.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue
+ (agent_id, runtime_id, issue_id, trigger_comment_id, status, priority,
+ originator_user_id, accountable_user_id, originator_source,
+ trigger_evidence_kind, trigger_evidence_ref_id)
+ VALUES ($1, $2, $3, $4, 'queued', 0, $5, $5, 'comment_source', 'comment', $4)`,
+ agentID, runtimeID, issueID, cidA, testUserID); err != nil {
+ t.Fatalf("seed queued task: %v", err)
+ }
+
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("get agent: %v", err)
+ }
+ issue := db.Issue{ID: parseUUID(issueID), WorkspaceID: parseUUID(testWorkspaceID)}
+ trigger := commentAgentTrigger{Agent: agent, Source: commentTriggerSourceIssueAssignee}
+
+ readSnapshot := func() (triggerComment, originator, accountable, source string) {
+ if err := testPool.QueryRow(ctx, `
+ SELECT COALESCE(trigger_comment_id::text,''), COALESCE(originator_user_id::text,''),
+ COALESCE(accountable_user_id::text,''), COALESCE(originator_source,'')
+ FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`,
+ issueID, agentID).Scan(&triggerComment, &originator, &accountable, &source); err != nil {
+ t.Fatalf("read snapshot: %v", err)
+ }
+ return
+ }
+
+ // ── Fail-closed: merge must be refused, snapshot preserved ──
+ if _, err := testPool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = true WHERE id = $1`, testWorkspaceID); err != nil {
+ t.Fatalf("set fail-closed: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `UPDATE workspace SET attribution_fail_closed = false WHERE id = $1`, testWorkspaceID)
+ })
+
+ countTasks := func() int {
+ var n int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, agentID).Scan(&n); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ return n
+ }
+ before := countTasks()
+
+ if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB)); result != commentMergeAttributionBlocked {
+ t.Fatalf("fail-closed merge result = %d, want commentMergeAttributionBlocked (refused, non-success)", result)
+ }
+ if after := countTasks(); after != before {
+ t.Errorf("task count changed %d -> %d on refused merge; a fail-closed refusal must not spawn a task", before, after)
+ }
+ // The refused merge must surface as a non-success blocked/attribution_blocked
+ // outcome, never a fabricated coalesced success.
+ if status, reason, terminal := commentMergeTerminalOutcome(commentMergeAttributionBlocked); !terminal || status != DispatchBlocked || reason != ReasonAttributionBlocked {
+ t.Errorf("attribution-blocked outcome = %s/%s (terminal=%v), want blocked/attribution_blocked", status, reason, terminal)
+ }
+ tc, orig, acc, src := readSnapshot()
+ if tc != cidA {
+ t.Errorf("trigger_comment_id = %s, want unchanged %s (fail-closed must keep the original trigger)", tc, cidA)
+ }
+ if orig != testUserID || acc != testUserID {
+ t.Errorf("originator/accountable = %s/%s, want unchanged %s (fail-closed must not re-stamp)", orig, acc, testUserID)
+ }
+ if src != "comment_source" {
+ t.Errorf("originator_source = %s, want unchanged comment_source (fail-closed must not degrade)", src)
+ }
+
+ // ── Fail-open control: the same comment now merges to owner_fallback ──
+ if _, err := testPool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = false WHERE id = $1`, testWorkspaceID); err != nil {
+ t.Fatalf("clear fail-closed: %v", err)
+ }
+ if result := testHandler.mergeCommentIntoPendingTask(ctx, issue, trigger, parseUUID(cidB)); result != commentMergeSucceeded {
+ t.Fatalf("fail-open merge result = %d, want commentMergeSucceeded", result)
+ }
+ tc2, orig2, _, src2 := readSnapshot()
+ if tc2 != cidB {
+ t.Errorf("fail-open: trigger_comment_id = %s, want repointed to %s (merge should proceed)", tc2, cidB)
+ }
+ if src2 != "owner_fallback" {
+ t.Errorf("fail-open: originator_source = %s, want owner_fallback (merge proceeded)", src2)
+ }
+ if orig2 != "" {
+ t.Errorf("fail-open owner_fallback: originator = %s, want NULL (authorization carries no human)", orig2)
+ }
+}
diff --git a/server/internal/handler/comment_trigger_outcomes_test.go b/server/internal/handler/comment_trigger_outcomes_test.go
new file mode 100644
index 0000000000..274f885a37
--- /dev/null
+++ b/server/internal/handler/comment_trigger_outcomes_test.go
@@ -0,0 +1,316 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func findCommentOutcome(t *testing.T, outcomes []CommentTriggerOutcome, targetID string) CommentTriggerOutcome {
+ t.Helper()
+ for _, o := range outcomes {
+ if o.TargetID == targetID {
+ return o
+ }
+ }
+ t.Fatalf("no trigger outcome for target %s in %+v", targetID, outcomes)
+ return CommentTriggerOutcome{}
+}
+
+// TestCreateComment_MixedMentionSurfacesPartialTriggerOutcomes is the MUL-4525 §2
+// acceptance test for Bohan's exact scenario: a comment @mentions an agent the
+// author can invoke AND a squad whose private leader they cannot. The comment is
+// still saved (one blocked mention must not reject it), and the response carries
+// per-target outcomes — queued for the allowed agent, blocked +
+// invocation_not_allowed for the squad — so the client can show partial success
+// instead of a silent no-op. The preview surfaces the same split before sending.
+func TestCreateComment_MixedMentionSurfacesPartialTriggerOutcomes(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ allowedAgentID := createHandlerTestAgent(t, "Outcome Allowed Agent", nil)
+ // A private leader owned by someone other than testUserID: the workspace
+ // owner can VIEW it but cannot INVOKE it (no admin bypass).
+ privateLeaderID, _, _ := privateAgentTestFixture(t)
+ squadID := createCommentTriggerPreviewSquad(t, "Outcome Private Squad", privateLeaderID)
+ issueID := createCommentTriggerPreviewIssue(t, "mixed mention partial outcomes", "", "")
+
+ content := fmt.Sprintf(
+ "[@Allowed](mention://agent/%s) [@Squad](mention://squad/%s) please take a look",
+ allowedAgentID, squadID,
+ )
+
+ // Preview surfaces both the allowed agent and the blocked squad.
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ requirePreviewAgents(t, preview, allowedAgentID)
+ if len(preview.Blocked) != 1 {
+ t.Fatalf("preview blocked = %+v, want 1 entry", preview.Blocked)
+ }
+ if b := preview.Blocked[0]; b.TargetType != "squad" || b.TargetID != squadID ||
+ b.Status != DispatchBlocked || b.ReasonCode != ReasonInvocationNotAllowed {
+ t.Fatalf("preview blocked[0] = %+v, want squad %s blocked/invocation_not_allowed", b, squadID)
+ }
+
+ // Create the comment: it must save (201) and report partial outcomes.
+ w := httptest.NewRecorder()
+ r := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{"content": content}), "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201 (comment must save despite blocked mention), got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode comment: %v", err)
+ }
+ if resp.ID == "" {
+ t.Fatal("comment was not saved")
+ }
+ if len(resp.TriggerOutcomes) != 2 {
+ t.Fatalf("trigger_outcomes = %+v, want 2 (one queued, one blocked)", resp.TriggerOutcomes)
+ }
+
+ allowed := findCommentOutcome(t, resp.TriggerOutcomes, allowedAgentID)
+ if allowed.TargetType != "agent" || allowed.Status != DispatchQueued {
+ t.Errorf("allowed outcome = %+v, want agent/queued", allowed)
+ }
+ blocked := findCommentOutcome(t, resp.TriggerOutcomes, squadID)
+ if blocked.TargetType != "squad" || blocked.Status != DispatchBlocked || blocked.ReasonCode != ReasonInvocationNotAllowed {
+ t.Errorf("blocked outcome = %+v, want squad/blocked/invocation_not_allowed", blocked)
+ }
+
+ // The allowed agent ran; the private leader was never enqueued.
+ if got := countQueuedCommentTriggerTasks(t, issueID, allowedAgentID); got != 1 {
+ t.Errorf("allowed agent queued tasks = %d, want 1", got)
+ }
+ var leaderTasks int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, privateLeaderID).Scan(&leaderTasks); err != nil {
+ t.Fatalf("count leader tasks: %v", err)
+ }
+ if leaderTasks != 0 {
+ t.Errorf("blocked private leader tasks = %d, want 0", leaderTasks)
+ }
+}
+
+// TestCreateComment_BlockedMentionReasonDoesNotEnumeratePrivateAgent pins the
+// enumeration-safety rule (MUL-4525 §2): a mention the author cannot invoke and a
+// mention of a truly nonexistent agent both return the same generic
+// invocation_not_allowed, so a blocked reason can never confirm a private
+// agent's existence.
+func TestCreateComment_BlockedMentionReasonDoesNotEnumeratePrivateAgent(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, _, _ := privateAgentTestFixture(t)
+ issueID := createCommentTriggerPreviewIssue(t, "blocked mention enumeration safety", "", "")
+ nonexistentID := "00000000-0000-0000-0000-0000000000ff"
+
+ content := fmt.Sprintf(
+ "[@Private](mention://agent/%s) [@Ghost](mention://agent/%s) ping",
+ privateAgentID, nonexistentID,
+ )
+ preview := previewCommentTriggersForTest(t, issueID, map[string]any{"content": content})
+ if len(preview.Agents) != 0 {
+ t.Fatalf("preview agents = %+v, want none", preview.Agents)
+ }
+ if len(preview.Blocked) != 2 {
+ t.Fatalf("preview blocked = %+v, want 2", preview.Blocked)
+ }
+ for _, b := range preview.Blocked {
+ if b.ReasonCode != ReasonInvocationNotAllowed {
+ t.Errorf("blocked %s reason = %q, want invocation_not_allowed (must not distinguish private-exists from not-found)", b.TargetID, b.ReasonCode)
+ }
+ }
+}
+
+// TestCreateComment_AgentAndSameLeaderSquad is Elon's round-3 must-fix 1
+// acceptance test: when a comment names BOTH @Agent A and @Squad S whose leader
+// is A, the run coalesces to ONE task that carries the LEADER role
+// (is_leader_task + squad_id=S, so the daemon injects S's briefing) regardless
+// of mention order, and each explicitly-named target still gets its own outcome
+// (MUL-4525). The old first-mention-wins dedup could drop the leader role when
+// @Agent A came first — this asserts the role independent of order.
+func TestCreateComment_AgentAndSameLeaderSquad(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ cases := []struct {
+ name string
+ content func(agentID, squadID string) string
+ }{
+ {"agent mention first", func(a, s string) string {
+ return fmt.Sprintf("[@A](mention://agent/%s) [@S](mention://squad/%s) please", a, s)
+ }},
+ {"squad mention first", func(a, s string) string {
+ return fmt.Sprintf("[@S](mention://squad/%s) [@A](mention://agent/%s) please", s, a)
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Shared Leader Agent "+tc.name, nil)
+ squadID := createCommentTriggerPreviewSquad(t, "Shared Leader Squad "+tc.name, agentID)
+ issueID := createCommentTriggerPreviewIssue(t, "same-leader "+tc.name, "", "")
+
+ w := httptest.NewRecorder()
+ r := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{"content": tc.content(agentID, squadID)}), "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode comment: %v", err)
+ }
+
+ // One coalesced execution carrying the leader role for squad S.
+ var taskCount int
+ var isLeader bool
+ var taskSquadID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*), COALESCE(bool_or(is_leader_task), false), COALESCE(max(squad_id::text), '')
+ FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2 AND status = 'queued'
+ `, issueID, agentID).Scan(&taskCount, &isLeader, &taskSquadID); err != nil {
+ t.Fatalf("read task role: %v", err)
+ }
+ if taskCount != 1 {
+ t.Fatalf("queued tasks = %d, want 1 (coalesced execution)", taskCount)
+ }
+ if !isLeader {
+ t.Errorf("execution is_leader_task = false, want true (leader role must win regardless of order)")
+ }
+ if taskSquadID != squadID {
+ t.Errorf("execution squad_id = %q, want %q", taskSquadID, squadID)
+ }
+
+ // Two outcomes — one per explicitly-named target — both queued.
+ if len(resp.TriggerOutcomes) != 2 {
+ t.Fatalf("trigger_outcomes = %+v, want 2 (agent + squad)", resp.TriggerOutcomes)
+ }
+ if o := findCommentOutcome(t, resp.TriggerOutcomes, agentID); o.TargetType != "agent" || o.Status != DispatchQueued {
+ t.Errorf("agent outcome = %+v, want agent/queued", o)
+ }
+ if o := findCommentOutcome(t, resp.TriggerOutcomes, squadID); o.TargetType != "squad" || o.Status != DispatchQueued {
+ t.Errorf("squad outcome = %+v, want squad/queued", o)
+ }
+ })
+ }
+}
+
+// TestCreateComment_TwoSquadsSharingLeaderCoalescesNonWinner is Elon's round-3
+// must-fix 1 (multi-squad case): two DIFFERENT squads share the same leader and
+// both are @mentioned. The single leader agent runs ONCE carrying one squad's
+// context; the other squad's mention folds into that run and is reported
+// coalesced — never a second task, and never both reported queued (MUL-4525).
+func TestCreateComment_TwoSquadsSharingLeaderCoalescesNonWinner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ leaderID := createHandlerTestAgent(t, "Two-Squad Shared Leader", nil)
+ squad1 := createCommentTriggerPreviewSquad(t, "Two-Squad S1", leaderID)
+ squad2 := createCommentTriggerPreviewSquad(t, "Two-Squad S2", leaderID)
+ issueID := createCommentTriggerPreviewIssue(t, "two squads sharing leader", "", "")
+ content := fmt.Sprintf("[@S1](mention://squad/%s) [@S2](mention://squad/%s) please", squad1, squad2)
+
+ w := httptest.NewRecorder()
+ r := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{"content": content}), "id", issueID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode comment: %v", err)
+ }
+
+ // Exactly one queued task (a single leader agent can only run once).
+ if got := countQueuedCommentTriggerTasks(t, issueID, leaderID); got != 1 {
+ t.Fatalf("queued tasks = %d, want 1", got)
+ }
+ // Two squad outcomes; exactly one queued (the executed squad) and one
+ // coalesced (the folded squad) — never both queued.
+ if len(resp.TriggerOutcomes) != 2 {
+ t.Fatalf("trigger_outcomes = %+v, want 2", resp.TriggerOutcomes)
+ }
+ statuses := map[DispatchStatus]int{}
+ for _, o := range resp.TriggerOutcomes {
+ if o.TargetType != "squad" {
+ t.Errorf("outcome %+v: want squad target", o)
+ }
+ statuses[o.Status]++
+ }
+ if statuses[DispatchQueued] != 1 || statuses[DispatchCoalesced] != 1 {
+ t.Errorf("outcome statuses = %v, want exactly 1 queued + 1 coalesced (not both queued)", statuses)
+ }
+}
+
+// TestCreateComment_SquadLeaderSelfMentionCompletedTaskDoesNotFakeSuccess is
+// Elon's round-3 must-fix 2: a squad leader's own @mention of its squad is
+// suppressed by the self-trigger guard, but when its latest task is already
+// TERMINAL (no active run), the outcome must NOT be a success-shaped `deferred`
+// — it is a non-success `blocked/self_trigger_suppressed`, and no new task runs.
+func TestCreateComment_SquadLeaderSelfMentionCompletedTaskDoesNotFakeSuccess(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ leaderID := createHandlerTestAgent(t, "Self-Mention Leader", nil)
+ squadID := createCommentTriggerPreviewSquad(t, "Self-Mention Squad", leaderID)
+ issueID := createCommentTriggerPreviewIssue(t, "self-mention completed task", "", "")
+
+ // The leader's latest task on this issue is a COMPLETED leader task: the
+ // self-trigger guard suppresses (latest role is leader) AND there is no
+ // active run to cover the comment.
+ var completedTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, is_leader_task, squad_id, started_at, completed_at)
+ VALUES ($1, $2, 'completed', 0, $3, true, $4, now(), now())
+ RETURNING id
+ `, leaderID, handlerTestRuntimeID(t), issueID, squadID).Scan(&completedTaskID); err != nil {
+ t.Fatalf("seed completed leader task: %v", err)
+ }
+
+ content := fmt.Sprintf("[@S](mention://squad/%s) revisit please", squadID)
+ w := httptest.NewRecorder()
+ r := withURLParam(newRequest(http.MethodPost, "/api/issues/"+issueID+"/comments", map[string]any{"content": content}), "id", issueID)
+ // Author the comment AS the leader agent (A2A self-mention).
+ r.Header.Set("X-Agent-ID", leaderID)
+ r.Header.Set("X-Task-ID", completedTaskID)
+ testHandler.CreateComment(w, r)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateComment: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CommentResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode comment: %v", err)
+ }
+
+ // The self-mention neither re-fired the leader nor is covered by an active
+ // run: the outcome is non-success, never a fake `deferred`.
+ if len(resp.TriggerOutcomes) != 1 {
+ t.Fatalf("trigger_outcomes = %+v, want 1", resp.TriggerOutcomes)
+ }
+ o := resp.TriggerOutcomes[0]
+ if o.TargetType != "squad" || o.TargetID != squadID {
+ t.Fatalf("outcome target = %+v, want squad %s", o, squadID)
+ }
+ if o.Status != DispatchBlocked || o.ReasonCode != ReasonSelfTriggerSuppressed {
+ t.Errorf("outcome = %+v, want blocked/self_trigger_suppressed (must not fake success)", o)
+ }
+ // No new task was enqueued (only the pre-seeded completed one exists).
+ var total int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1 AND agent_id = $2`, issueID, leaderID).Scan(&total); err != nil {
+ t.Fatalf("count leader tasks: %v", err)
+ }
+ if total != 1 {
+ t.Errorf("leader tasks = %d, want 1 (self-mention suppressed, no new task)", total)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 2fe8e47aaf..ed993aebc9 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2988,7 +2988,7 @@ func (h *Handler) reconcileCommentsOnCompletion(ctx context.Context, task *db.Ag
if actorType != "member" {
originatorUserID = uuidToString(h.TaskService.ResolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, c.ID))
}
- triggers := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
+ triggers, _ := h.computeCommentAgentTriggers(ctx, issue, c.Content, parentComment, actorType, actorID, commentTriggerComputeOptions{
ExcludeTriggerCommentID: c.ID,
OriginatorUserID: originatorUserID,
})
@@ -3582,6 +3582,8 @@ func (h *Handler) GetActiveTaskForIssue(w http.ResponseWriter, r *http.Request)
for i, t := range tasks {
resp[i] = taskToResponse(t, workspaceID)
}
+ // Same issue-facing attribution surface as ListTasksByIssue — hydrate names.
+ h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
writeJSON(w, http.StatusOK, map[string]any{"tasks": resp})
}
@@ -3612,7 +3614,11 @@ func (h *Handler) CancelTask(w http.ResponseWriter, r *http.Request) {
}
slog.Info("task cancelled by user", "task_id", taskID, "issue_id", uuidToString(task.IssueID))
- writeJSON(w, http.StatusOK, taskToResponse(*task, uuidToString(issue.WorkspaceID)))
+ resp := taskToResponse(*task, uuidToString(issue.WorkspaceID))
+ // Keep this issue-scoped surface consistent with the list endpoints so a
+ // cancelled row keeps its resolved "on behalf of" name in the UI.
+ h.hydrateTaskAttributions(r.Context(), []*TaskAttribution{resp.Attribution})
+ writeJSON(w, http.StatusOK, resp)
}
// ListTasksByIssue returns all tasks (any status) for an issue — used for execution history.
@@ -3634,6 +3640,10 @@ func (h *Handler) ListTasksByIssue(w http.ResponseWriter, r *http.Request) {
for i, t := range tasks {
resp[i] = taskToResponse(t, workspaceID)
}
+ // Execution-log rows render the "on behalf of <member>" badge, so this
+ // issue-facing surface must resolve initiator/originator names (departed-safe,
+ // one batch) — otherwise the badge falls back to "someone" on issue detail.
+ h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))
writeJSON(w, http.StatusOK, resp)
}
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index c52b58f76f..eb8fc116ee 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -694,7 +694,7 @@ func TestRerunIssue_PreservesSourceCommentPlanAndResetsReceipt(t *testing.T) {
testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
})
- rerun, err := testHandler.TaskService.RerunIssue(ctx, util.MustParseUUID(issueID), util.MustParseUUID(sourceID), pgtype.UUID{})
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, util.MustParseUUID(issueID), util.MustParseUUID(sourceID), pgtype.UUID{}, pgtype.UUID{}, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
@@ -733,7 +733,7 @@ func TestRerunIssue_PromotesNewestSurvivorAfterSourceTriggerDeleted(t *testing.T
t.Fatalf("delete rerun source trigger: %v", err)
}
- rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(fixture.issueID), parseUUID(fixture.taskID), pgtype.UUID{})
+ rerun, err := testHandler.TaskService.RerunIssue(ctx, parseUUID(fixture.issueID), parseUUID(fixture.taskID), pgtype.UUID{}, pgtype.UUID{}, nil)
if err != nil {
t.Fatalf("RerunIssue: %v", err)
}
diff --git a/server/internal/handler/issue_agent_create_e2e_test.go b/server/internal/handler/issue_agent_create_e2e_test.go
index 042e67a55e..6eb58cb99f 100644
--- a/server/internal/handler/issue_agent_create_e2e_test.go
+++ b/server/internal/handler/issue_agent_create_e2e_test.go
@@ -77,8 +77,8 @@ func TestAgentCreateOriginator_E2E_CreateAssignSquad_PrivateWorkerTriggered(t *t
creatorAID := createHandlerTestAgent(t, "mul4305-e2e-creator-agent", nil)
var creatorTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id)
- VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id, accountable_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $2)
RETURNING id
`, creatorAID, ownerH).Scan(&creatorTaskID); err != nil {
t.Fatalf("create A's acting task: %v", err)
@@ -197,8 +197,8 @@ func TestAgentCreateOriginator_E2E_UpdateAssignSquad_HandlerGateAdmitsPrivateLea
creatorAID := createHandlerTestAgent(t, "mul4305-e2e-update-creator", nil)
var creatorTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id)
- VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id, accountable_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $2)
RETURNING id
`, creatorAID, ownerH).Scan(&creatorTaskID); err != nil {
t.Fatalf("create A's acting task: %v", err)
diff --git a/server/internal/handler/issue_agent_create_origin_test.go b/server/internal/handler/issue_agent_create_origin_test.go
index 1394416739..2db4926201 100644
--- a/server/internal/handler/issue_agent_create_origin_test.go
+++ b/server/internal/handler/issue_agent_create_origin_test.go
@@ -34,8 +34,8 @@ func TestCreateIssue_AgentCreate_StampsActingTaskOrigin(t *testing.T) {
// validates this (agent, task) pair before the handler trusts X-Task-ID.
var taskID string
if err := testPool.QueryRow(ctx,
- `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id)
- VALUES ($1, $2, 'running', 0, $3) RETURNING id`,
+ `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, 'running', 0, $3, $3) RETURNING id`,
agentID, runtimeID, testUserID,
).Scan(&taskID); err != nil {
t.Fatalf("seed acting task: %v", err)
diff --git a/server/internal/handler/issue_trigger.go b/server/internal/handler/issue_trigger.go
index 20f4334c6f..5d7c7cfb74 100644
--- a/server/internal/handler/issue_trigger.go
+++ b/server/internal/handler/issue_trigger.go
@@ -53,12 +53,30 @@ func (h *Handler) issueTriggerPreviewProbe(r *http.Request, actorType, actorID,
func (h *Handler) dispatchIssueRun(ctx context.Context, issue db.Issue, trigger service.IssueRunTrigger, actorType, actorID, handoffNote string) {
switch trigger.AssigneeType {
case "agent":
- _, _ = h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote)
+ // The member who performed this assign/promote is the accountable human
+ // for the run (MUL-4302 §4). An agent actor is not a human, so only a
+ // member actor is threaded; otherwise attribution falls back to the chain.
+ _, _ = h.TaskService.EnqueueTaskForIssueWithHandoff(ctx, issue, handoffNote, memberActorUserID(actorType, actorID))
case "squad":
h.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, actorType, actorID, handoffNote)
}
}
+// memberActorUserID returns the acting member's user id as a pgtype.UUID when the
+// actor is a member, and an invalid UUID otherwise (an agent actor id is not a
+// human and must never become an accountable human). Used to thread the
+// assign/promote actor into the attribution resolver (MUL-4302 §4).
+func memberActorUserID(actorType, actorID string) pgtype.UUID {
+ if actorType != "member" {
+ return pgtype.UUID{}
+ }
+ uid, err := util.ParseUUID(actorID)
+ if err != nil {
+ return pgtype.UUID{}
+ }
+ return uid
+}
+
// IssueTriggerPreviewRequest asks "if I apply this assignee and/or status to
// these issues (or create one), which runs will start". All fields are
// optional; a nil prospective field means "leave unchanged".
diff --git a/server/internal/handler/mention_self_trigger_test.go b/server/internal/handler/mention_self_trigger_test.go
index d31fd63a11..93c475f91c 100644
--- a/server/internal/handler/mention_self_trigger_test.go
+++ b/server/internal/handler/mention_self_trigger_test.go
@@ -13,7 +13,7 @@ import (
// test helper so these integration tests keep asserting enqueue side effects.
func enqueueMentionedAgentTasksForTest(t *testing.T, ctx context.Context, issue db.Issue, comment db.Comment, parentComment *db.Comment, authorType, authorID string) {
t.Helper()
- triggers := testHandler.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID, commentTriggerComputeOptions{})
+ triggers, _ := testHandler.computeCommentAgentTriggers(ctx, issue, comment.Content, parentComment, authorType, authorID, commentTriggerComputeOptions{})
testHandler.enqueueCommentAgentTriggers(ctx, issue, comment.ID, triggers)
}
diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.go
index 649b3aba9c..af8caf987d 100644
--- a/server/internal/handler/squad.go
+++ b/server/internal/handler/squad.go
@@ -1072,7 +1072,10 @@ func (h *Handler) enqueueSquadLeaderTask(ctx context.Context, issue db.Issue, tr
// triggerCommentID is always empty on the assign/promote path; the handoff
// note rides its own task column, never trigger_comment_id.
_ = triggerCommentID
- if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote); err != nil {
+ // The member who performed the assign/promote is the accountable human for the
+ // leader run (MUL-4302 §4) — the same principal the gate above judged. An agent
+ // author is not a human, so only a member actor is threaded.
+ if _, err := h.TaskService.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, squad.LeaderID, squad.ID, handoffNote, memberActorUserID(authorType, authorID)); err != nil {
slog.Warn("enqueue squad leader task failed",
"issue_id", uuidToString(issue.ID),
"squad_id", uuidToString(squad.ID),
diff --git a/server/internal/handler/squad_comment_trigger_test.go b/server/internal/handler/squad_comment_trigger_test.go
index ae18a4037d..f2c1585927 100644
--- a/server/internal/handler/squad_comment_trigger_test.go
+++ b/server/internal/handler/squad_comment_trigger_test.go
@@ -45,11 +45,13 @@ func TestCommentMentionsAnyone(t *testing.T) {
// shouldEnqueueSquadLeaderOnCommentForTest reports whether the shared cascade
// would wake the issue's assigned squad leader.
func shouldEnqueueSquadLeaderOnCommentForTest(ctx context.Context, issue db.Issue, content, authorType, authorID string) bool {
- return triggersContainIssueAssigneeSquadLeader(testHandler.computeCommentAgentTriggers(ctx, issue, content, nil, authorType, authorID, commentTriggerComputeOptions{}))
+ triggers, _ := testHandler.computeCommentAgentTriggers(ctx, issue, content, nil, authorType, authorID, commentTriggerComputeOptions{})
+ return triggersContainIssueAssigneeSquadLeader(triggers)
}
func shouldEnqueueSquadLeaderOnReplyForTest(ctx context.Context, issue db.Issue, content string, parent *db.Comment, authorType, authorID string) bool {
- return triggersContainIssueAssigneeSquadLeader(testHandler.computeCommentAgentTriggers(ctx, issue, content, parent, authorType, authorID, commentTriggerComputeOptions{}))
+ triggers, _ := testHandler.computeCommentAgentTriggers(ctx, issue, content, parent, authorType, authorID, commentTriggerComputeOptions{})
+ return triggersContainIssueAssigneeSquadLeader(triggers)
}
func triggersContainIssueAssigneeSquadLeader(triggers []commentAgentTrigger) bool {
diff --git a/server/internal/handler/squad_private_leader_test.go b/server/internal/handler/squad_private_leader_test.go
index efbd79d1f5..144e9e85c1 100644
--- a/server/internal/handler/squad_private_leader_test.go
+++ b/server/internal/handler/squad_private_leader_test.go
@@ -378,8 +378,8 @@ func TestChildDone_SquadPrivateLeader_AgentActorWakesLeader(t *testing.T) {
// depends on the completer being able to invoke the leader.
var workerTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_user_id)
- VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $3)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_user_id, accountable_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $3, $3)
RETURNING id
`, workerAgentID, child.ID, memberID).Scan(&workerTaskID); err != nil {
t.Fatalf("create worker task: %v", err)
@@ -458,8 +458,8 @@ func TestComment_SquadPrivateLeader_AgentActorAllowed(t *testing.T) {
// the private leader.
var taskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_user_id)
- VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $3)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, issue_id, originator_user_id, accountable_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), 'running', 0, $2, $3, $3)
RETURNING id
`, otherAgentID, issueID, ownerID).Scan(&taskID); err != nil {
t.Fatalf("create agent task: %v", err)
diff --git a/server/internal/handler/squad_worker_comment_wakes_leader_test.go b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
index 5b2d7347c4..07531f098a 100644
--- a/server/internal/handler/squad_worker_comment_wakes_leader_test.go
+++ b/server/internal/handler/squad_worker_comment_wakes_leader_test.go
@@ -50,8 +50,8 @@ func TestCreateComment_WorkerAgentCommentWakesSquadLeader_MUL4015(t *testing.T)
}
var workerTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id)
- VALUES ($1, $2, $3, 'running', FALSE, $4)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, $3, 'running', FALSE, $4, $4)
RETURNING id
`, fx.OtherID, workerRuntimeID, issueID, testUserID).Scan(&workerTaskID); err != nil {
t.Fatalf("seed worker task: %v", err)
@@ -65,8 +65,8 @@ func TestCreateComment_WorkerAgentCommentWakesSquadLeader_MUL4015(t *testing.T)
t.Fatalf("load leader runtime: %v", err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id)
- VALUES ($1, $2, $3, 'completed', TRUE, $4)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, $3, 'completed', TRUE, $4, $4)
`, fx.LeaderID, leaderRuntimeID, issueID, testUserID); err != nil {
t.Fatalf("seed leader task: %v", err)
}
@@ -125,8 +125,8 @@ func TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending
}
var workerTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id)
- VALUES ($1, $2, $3, 'running', FALSE, $4)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, $3, 'running', FALSE, $4, $4)
RETURNING id
`, fx.OtherID, workerRuntimeID, issueID, testUserID).Scan(&workerTaskID); err != nil {
t.Fatalf("seed worker task: %v", err)
@@ -140,8 +140,8 @@ func TestCreateComment_WorkerAgentCommentDoesNotWakeLeader_WhenLeaderTaskPending
t.Fatalf("load leader runtime: %v", err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id)
- VALUES ($1, $2, $3, 'queued', TRUE, $4)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, $3, 'queued', TRUE, $4, $4)
`, fx.LeaderID, leaderRuntimeID, issueID, testUserID); err != nil {
t.Fatalf("seed queued leader task: %v", err)
}
@@ -270,8 +270,8 @@ func TestCreateComment_WorkerAgentCommentWakesPrivateSquadLeader_MUL4015(t *test
}
var leaderTaskID string
if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, squad_id)
- VALUES ($1, $2, $3, 'running', TRUE, $4, $5)
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, is_leader_task, originator_user_id, accountable_user_id, squad_id)
+ VALUES ($1, $2, $3, 'running', TRUE, $4, $4, $5)
RETURNING id
`, leaderID, leaderRuntimeID, issueID, testUserID, squadID).Scan(&leaderTaskID); err != nil {
t.Fatalf("seed leader task: %v", err)
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
index f3c3444727..e84abcb420 100644
--- a/server/internal/handler/task_lifecycle.go
+++ b/server/internal/handler/task_lifecycle.go
@@ -2,12 +2,14 @@ package handler
import (
"encoding/json"
+ "errors"
"io"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -143,11 +145,37 @@ func (h *Handler) RerunIssue(w http.ResponseWriter, r *http.Request) {
sourceTaskID = parsed
}
- task, err := h.TaskService.RerunIssue(r.Context(), issue.ID, sourceTaskID, pgtype.UUID{})
+ // A manual rerun is a direct human action: attribute the new run to the
+ // rerunning member (MUL-4302 §5). Resolve the actor the same way assign/promote
+ // does; an agent A2A actor is not a human and threads an invalid actor.
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := uuidToString(issue.WorkspaceID)
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ actorUserID := memberActorUserID(actorType, actorID)
+
+ // Re-validate the operator's invoke permission on the resolved target agent
+ // before cancelling / creating anything (MUL-4525). Issue visibility does not
+ // grant the right to trigger a private agent — a task_id rerun must gate the
+ // historical agent, not the (possibly reassigned) current assignee.
+ originatorUserID := h.invokeOriginatorFromRequest(r, actorType, actorID)
+ canInvoke := func(agent db.Agent) bool {
+ return h.canInvokeAgent(r.Context(), agent, actorType, actorID, originatorUserID, workspaceID)
+ }
+
+ task, err := h.TaskService.RerunIssue(r.Context(), issue.ID, sourceTaskID, pgtype.UUID{}, actorUserID, canInvoke)
+ if errors.Is(err, service.ErrRerunInvokeNotAllowed) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
if err != nil {
slog.Warn("issue rerun failed", "issue_id", id, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
- writeJSON(w, http.StatusAccepted, taskToResponse(*task, uuidToString(issue.WorkspaceID)))
+ resp := taskToResponse(*task, uuidToString(issue.WorkspaceID))
+ h.hydrateTaskAttributions(r.Context(), []*TaskAttribution{resp.Attribution})
+ writeJSON(w, http.StatusAccepted, resp)
}
diff --git a/server/internal/service/admission_mul4525_test.go b/server/internal/service/admission_mul4525_test.go
new file mode 100644
index 0000000000..ddc1abbe6b
--- /dev/null
+++ b/server/internal/service/admission_mul4525_test.go
@@ -0,0 +1,148 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/dispatch"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestRerunIssueBlockedBeforeMutationWhenInvokeDenied is the security acceptance
+// test for MUL-4525 §5: a rerun whose operator cannot invoke the resolved target
+// agent must be refused with ErrRerunInvokeNotAllowed, and it must fail BEFORE
+// any mutation — the prior task is not cancelled and no new task is created.
+func TestRerunIssueBlockedBeforeMutationWhenInvokeDenied(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
+
+ issueStruct := db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: util.MustParseUUID(creatorID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ }
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ orig, err := svc.EnqueueTaskForIssue(ctx, issueStruct)
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssue (original): %v", err)
+ }
+
+ countTasks := func() int {
+ var n int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&n); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ return n
+ }
+ origStatus := func() string {
+ var s string
+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, orig.ID).Scan(&s); err != nil {
+ t.Fatalf("read orig status: %v", err)
+ }
+ return s
+ }
+ beforeCount := countTasks()
+ beforeStatus := origStatus()
+
+ // The gate is invoked with the RESOLVED target agent and denies it.
+ gateSawAgent := false
+ deny := func(a db.Agent) bool {
+ if util.UUIDToString(a.ID) == agentID {
+ gateSawAgent = true
+ }
+ return false
+ }
+
+ _, err = svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), deny)
+ if !errors.Is(err, ErrRerunInvokeNotAllowed) {
+ t.Fatalf("RerunIssue with denying gate: err = %v, want ErrRerunInvokeNotAllowed", err)
+ }
+ if !gateSawAgent {
+ t.Errorf("gate was not evaluated against the resolved target agent %s", agentID)
+ }
+ // Fail-before-mutation: no new task, original untouched.
+ if got := countTasks(); got != beforeCount {
+ t.Errorf("task count changed after blocked rerun: got %d, want %d", got, beforeCount)
+ }
+ if got := origStatus(); got != beforeStatus {
+ t.Errorf("original task status changed after blocked rerun: got %q, want %q", got, beforeStatus)
+ }
+
+ // A permitting gate reruns normally (cancels the original, enqueues fresh).
+ allow := func(db.Agent) bool { return true }
+ rerun, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(creatorID), allow)
+ if err != nil {
+ t.Fatalf("RerunIssue with permitting gate: %v", err)
+ }
+ if util.UUIDToString(rerun.ID) == util.UUIDToString(orig.ID) {
+ t.Errorf("expected a new task id, got the original %s", util.UUIDToString(orig.ID))
+ }
+}
+
+// TestAutopilotDispatchAdmitsClickerNotCreator is the acceptance test for
+// MUL-4525 §3: a MANUAL "run now" admits on the CURRENT clicker's invoke
+// permission (not the autopilot creator's), while automation (no human actor)
+// still falls back to the creator gate. The two must not fork.
+func TestAutopilotDispatchAdmitsClickerNotCreator(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ // Fixture agent is private and owned by ownerID.
+ workspaceID, ownerID, agentID, _ := seedAttributionFixture(t, pool)
+
+ // A different member owns the autopilot; they neither own the private agent
+ // nor sit on its allow-list, so the creator gate denies them.
+ var apCreatorID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('AP Creator', $1) RETURNING id`,
+ fmt.Sprintf("apc-%[email protected]", time.Now().UnixNano())).Scan(&apCreatorID); err != nil {
+ t.Fatalf("seed ap creator: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, apCreatorID) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')`,
+ workspaceID, apCreatorID); err != nil {
+ t.Fatalf("seed ap creator member: %v", err)
+ }
+
+ ap := db.Autopilot{
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeID: util.MustParseUUID(agentID),
+ AssigneeType: "agent",
+ ExecutionMode: "run_only",
+ Status: "active",
+ CreatedByType: "member",
+ CreatedByID: util.MustParseUUID(apCreatorID),
+ }
+ svc := &AutopilotService{Queries: q}
+
+ // Manual dispatch by the agent owner (the clicker) is admitted.
+ if reason, _, skip := svc.shouldSkipDispatch(ctx, ap, util.MustParseUUID(ownerID)); skip {
+ t.Fatalf("manual dispatch by the agent owner should be admitted, got skip: %q", reason)
+ }
+
+ // Automation (no human actor) falls back to the creator gate, which denies
+ // the admin-but-non-owner creator on a private agent — and the typed reason
+ // code is decided at that branch, not guessed from text.
+ reason, code, skip := svc.shouldSkipDispatch(ctx, ap, pgtype.UUID{})
+ if !skip {
+ t.Fatalf("automation dispatch should be blocked by the creator gate")
+ }
+ if !strings.Contains(strings.ToLower(reason), "creator") {
+ t.Errorf("automation skip reason = %q, want creator-gate phrasing", reason)
+ }
+ if code != dispatch.ReasonInvocationNotAllowed {
+ t.Errorf("skip reason_code = %q, want invocation_not_allowed", code)
+ }
+}
diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.go
new file mode 100644
index 0000000000..998bd85768
--- /dev/null
+++ b/server/internal/service/attribution_stamp_test.go
@@ -0,0 +1,1283 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/attribution"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// seedAttributionFixture creates the minimal user/workspace/member/runtime/agent
+// graph plus a member-created issue assigned to the agent, and returns the ids
+// needed to enqueue a run. Everything is cleaned up via t.Cleanup.
+func seedAttributionFixture(t *testing.T, pool *pgxpool.Pool) (workspaceID, userID, agentID, issueID string) {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Attr User', $1) RETURNING id`,
+ fmt.Sprintf("attr-%[email protected]", suffix)).Scan(&userID); err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })
+
+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug) VALUES ('attr ws', $1) RETURNING id`,
+ fmt.Sprintf("attr-%d", suffix)).Scan(&workspaceID); err != nil {
+ t.Fatalf("seed workspace: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID) })
+
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,
+ workspaceID, userID); err != nil {
+ t.Fatalf("seed member: %v", err)
+ }
+
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, status, device_info, metadata, owner_id)
+ VALUES ($1, 'attr-runtime', 'cloud', 'codex', 'online', '', '{}'::jsonb, $2)
+ RETURNING id`, workspaceID, userID).Scan(&runtimeID); err != nil {
+ t.Fatalf("seed runtime: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_config, runtime_id, visibility,
+ max_concurrent_tasks, owner_id, instructions, custom_env, custom_args)
+ VALUES ($1, 'attr-agent', 'cloud', '{}'::jsonb, $2, 'workspace', 1, $3, '', '{}'::jsonb, '[]'::jsonb)
+ RETURNING id`, workspaceID, runtimeID, userID).Scan(&agentID); err != nil {
+ t.Fatalf("seed agent: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority)
+ VALUES ($1, 'attr issue', 'member', $2, 'agent', $3, 'medium')
+ RETURNING id`, workspaceID, userID, agentID).Scan(&issueID); err != nil {
+ t.Fatalf("seed issue: %v", err)
+ }
+ return workspaceID, userID, agentID, issueID
+}
+
+// TestEnqueueTaskForIssueStampsDirectHumanAttribution is the acceptance test for
+// the Phase 1 foundation (MUL-4302 §11): a member-assigned run must land with a
+// non-empty, correct attribution — source=direct_human, the accountable human
+// equal to the issue creator, and evidence pointing back at the issue.
+func TestEnqueueTaskForIssueStampsDirectHumanAttribution(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: util.MustParseUUID(userID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssue: %v", err)
+ }
+
+ // Read the stored row so we assert what actually persisted, not just the
+ // returned struct.
+ var source pgtype.Text
+ var originator, accountable, evidenceRef pgtype.UUID
+ var evidenceKind pgtype.Text
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, trigger_evidence_kind, trigger_evidence_ref_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &evidenceKind, &evidenceRef); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(userID).Bytes {
+ t.Errorf("originator_user_id = %s, want %s", util.UUIDToString(originator), userID)
+ }
+ // MUL-4302 §11 invariant at the DB layer: a non-NULL originator implies the
+ // accountable human equals it.
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable_user_id = %s, want == originator %s", util.UUIDToString(accountable), util.UUIDToString(originator))
+ }
+ if evidenceKind.String != string(attribution.EvidenceIssueAssignment) {
+ t.Errorf("trigger_evidence_kind = %q, want issue_assignment", evidenceKind.String)
+ }
+ if !evidenceRef.Valid || evidenceRef.Bytes != util.MustParseUUID(issueID).Bytes {
+ t.Errorf("trigger_evidence_ref_id = %s, want issue %s", util.UUIDToString(evidenceRef), issueID)
+ }
+}
+
+// TestEnqueueTaskForIssueWithHandoffAttributesToActor is the acceptance test for
+// the assign/promote actor fix (MUL-4302 §4): when a member assigns an issue that
+// a DIFFERENT member created, the run's accountable human — and, honoring the
+// invariant, its originator — is the assigning member (the actor), not the issue
+// creator. The evidence still points at the issue.
+func TestEnqueueTaskForIssueWithHandoffAttributesToActor(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // A second member in the same workspace performs the assign.
+ var actorID string
+ suffix := time.Now().UnixNano()
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Actor', $1) RETURNING id`,
+ fmt.Sprintf("actor-%[email protected]", suffix)).Scan(&actorID); err != nil {
+ t.Fatalf("seed actor user: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ workspaceID, actorID); err != nil {
+ t.Fatalf("seed actor member: %v", err)
+ }
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueTaskForIssueWithHandoff(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: util.MustParseUUID(creatorID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ }, "", util.MustParseUUID(actorID))
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssueWithHandoff: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(actorID).Bytes {
+ t.Errorf("accountable_user_id = %s, want actor %s (not creator %s)", util.UUIDToString(accountable), actorID, creatorID)
+ }
+ // Invariant: originator mirrors accountable, so it is the actor too — the
+ // assigning member lends the authority, not the issue creator.
+ if !originator.Valid || originator.Bytes != accountable.Bytes {
+ t.Errorf("originator_user_id = %s, want == accountable (actor) %s", util.UUIDToString(originator), util.UUIDToString(accountable))
+ }
+}
+
+// TestMergeCommentIntoPendingTask_KeepsAccountableEqualsOriginator guards the
+// MUL-4302 one-way invariant across the comment-coalescing merge (main #5192 ×
+// attribution): when a coalescing run re-stamps originator_user_id to the newly
+// arrived comment's human, accountable_user_id must mirror it. Otherwise folding
+// member B's comment into member A's queued task leaves originator=B / accountable=A.
+func TestMergeCommentIntoPendingTask_KeepsAccountableEqualsOriginator(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userA, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // A second member B whose comment will be coalesced in.
+ var userB string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Attr User B', $1) RETURNING id`,
+ fmt.Sprintf("attr-b-%[email protected]", time.Now().UnixNano())).Scan(&userB); err != nil {
+ t.Fatalf("seed user B: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userB) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`, workspaceID, userB); err != nil {
+ t.Fatalf("add member B: %v", err)
+ }
+
+ // A queued task attributed to A with a STALE source label + no evidence, so the
+ // merge has something to prove it re-stamped the whole snapshot, not just people.
+ var taskID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $3, 'delegation')
+ RETURNING id`, agentID, issueID, userA).Scan(&taskID); err != nil {
+ t.Fatalf("seed queued task: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ // B's newly-arrived comment on the same issue.
+ var commentID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'member', $3, 'B comment') RETURNING id`, issueID, workspaceID, userB).Scan(&commentID); err != nil {
+ t.Fatalf("seed comment: %v", err)
+ }
+
+ // Re-stamp the FULL snapshot for B's member comment (direct_human + comment
+ // evidence), as the caller does.
+ if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{
+ IssueID: util.MustParseUUID(issueID),
+ AgentID: util.MustParseUUID(agentID),
+ NewTriggerCommentID: util.MustParseUUID(commentID),
+ NewOriginatorUserID: util.MustParseUUID(userB),
+ NewAccountableUserID: util.MustParseUUID(userB),
+ NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},
+ NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},
+ NewTriggerEvidenceRefID: util.MustParseUUID(commentID),
+ }); err != nil {
+ t.Fatalf("MergeCommentIntoPendingTask: %v", err)
+ }
+
+ var originator, accountable pgtype.UUID
+ var source, evidenceKind pgtype.Text
+ if err := pool.QueryRow(ctx,
+ `SELECT originator_user_id, accountable_user_id, originator_source, trigger_evidence_kind FROM agent_task_queue WHERE id = $1`, taskID,
+ ).Scan(&originator, &accountable, &source, &evidenceKind); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(userB).Bytes {
+ t.Errorf("originator = %s, want re-stamped to B %s", util.UUIDToString(originator), userB)
+ }
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable = %s, want == originator (B); one-way invariant violated on merge", util.UUIDToString(accountable))
+ }
+ // Full-snapshot re-stamp: the stale 'delegation' source + NULL evidence must move
+ // to the new comment's 'direct_human' + comment evidence, not linger.
+ if source.String != "direct_human" {
+ t.Errorf("originator_source = %q, want re-stamped to direct_human (stale snapshot left behind)", source.String)
+ }
+ if evidenceKind.String != "comment" {
+ t.Errorf("trigger_evidence_kind = %q, want re-stamped to comment", evidenceKind.String)
+ }
+}
+
+// TestAttributionForMergedComment_HonorsFailClosedPolicy is Elon's must-fix
+// regression: folding a comment that resolves to NO precise human into a queued task
+// re-opens the fail-closed decision. On a fail-closed workspace the merge must be
+// REFUSED (ErrAttributionFailClosed) so the queued task keeps its original precise
+// snapshot instead of being re-stamped to a degraded owner_fallback; on a fail-open
+// workspace the same comment degrades to owner_fallback (accountable = agent owner)
+// with no error, exactly as a fresh enqueue would (MUL-4302).
+func TestAttributionForMergedComment_HonorsFailClosedPolicy(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, ownerID, agentID, issueID := seedAttributionFixture(t, pool)
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ agent, err := q.GetAgent(ctx, util.MustParseUUID(agentID))
+ if err != nil {
+ t.Fatalf("get agent: %v", err)
+ }
+
+ // An agent-authored comment with no source-task lineage → no precise human.
+ var commentID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)
+ VALUES ($1, $2, 'agent', $3, 'autonomous ping') RETURNING id`,
+ issueID, workspaceID, agentID).Scan(&commentID); err != nil {
+ t.Fatalf("seed comment: %v", err)
+ }
+
+ // Fail-CLOSED: the merge must be refused, not degraded.
+ if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = true WHERE id = $1`, workspaceID); err != nil {
+ t.Fatalf("set fail-closed: %v", err)
+ }
+ if _, err := svc.AttributionForMergedComment(ctx, util.MustParseUUID(workspaceID), util.MustParseUUID(commentID), false, agent); !errors.Is(err, ErrAttributionFailClosed) {
+ t.Fatalf("fail-closed merge must return ErrAttributionFailClosed, got %v", err)
+ }
+
+ // Fail-OPEN (default): the same comment degrades to owner_fallback, no error.
+ if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = false WHERE id = $1`, workspaceID); err != nil {
+ t.Fatalf("clear fail-closed: %v", err)
+ }
+ attr, err := svc.AttributionForMergedComment(ctx, util.MustParseUUID(workspaceID), util.MustParseUUID(commentID), false, agent)
+ if err != nil {
+ t.Fatalf("fail-open merge must not error, got %v", err)
+ }
+ if attr.Source != attribution.SourceOwnerFallback {
+ t.Errorf("fail-open unattributable merge source = %q, want owner_fallback", attr.Source)
+ }
+ if !attr.AccountableUserID.Valid || attr.AccountableUserID.Bytes != util.MustParseUUID(ownerID).Bytes {
+ t.Errorf("owner_fallback accountable = %s, want agent owner %s", util.UUIDToString(attr.AccountableUserID), ownerID)
+ }
+ if attr.UserID.Valid {
+ t.Errorf("owner_fallback must not set originator (authorization stays NULL), got %s", util.UUIDToString(attr.UserID))
+ }
+}
+
+// TestAttributionInvariantCheck_RejectsBypass verifies the DB-level cross-column
+// CHECK (MUL-4302): a write in the ENFORCED regime (originator_source non-NULL — every
+// real enqueue / coalesce path stamps it) that sets originator_user_id but leaves
+// accountable_user_id NULL — or different — is rejected at the database, so a future
+// code path that bypasses finalizeAttribution fails loudly instead of silently
+// mis-attributing an audited run (the #5192 comment-merge bug class). The legacy-row
+// exemption (originator_source IS NULL) is covered by
+// TestAttributionInvariantCheck_ExemptsLegacyRows.
+func TestAttributionInvariantCheck_RejectsBypass(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ _, userA, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // originator set, accountable NULL, source set (enforced) → must violate the check.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, originator_source)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, 'comment_source')`,
+ agentID, issueID, userA); err == nil {
+ t.Fatal("expected the CHECK to reject originator set with NULL accountable, but insert succeeded")
+ }
+
+ // originator != accountable → also rejected.
+ var userB string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Check B', $1) RETURNING id`,
+ fmt.Sprintf("check-b-%[email protected]", time.Now().UnixNano())).Scan(&userB); err != nil {
+ t.Fatalf("seed user B: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userB) })
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $4, 'comment_source')`,
+ agentID, issueID, userA, userB); err == nil {
+ t.Fatal("expected the CHECK to reject originator != accountable, but insert succeeded")
+ }
+
+ // The legitimate shape (equal) is accepted.
+ var okTaskID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id, originator_source)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3, $3, 'direct_human') RETURNING id`,
+ agentID, issueID, userA).Scan(&okTaskID); err != nil {
+ t.Fatalf("equal originator/accountable must be accepted, got %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, okTaskID) })
+}
+
+// TestAttributionInvariantCheck_ExemptsLegacyRows is the upgrade-safety test Elon
+// required (MUL-4302, Option A): a pre-migration row — originator set, accountable
+// NULL, and originator_source NULL (its column did not exist yet) — must survive the
+// NOT VALID CHECK and, crucially, must still accept a later status UPDATE by the new
+// backend (claim / complete / cancel), even though that UPDATE does not touch the
+// attribution columns. This reproduces the cross-deployment stale-task scenario the
+// two-phase rollout protects; without the `originator_source IS NULL` exemption the
+// UPDATE would fail the CHECK on the whole updated row.
+func TestAttributionInvariantCheck_ExemptsLegacyRows(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ _, userA, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // A legacy-shaped row: originator set, accountable + source NULL. The exemption
+ // admits it (as it admits the real pre-migration rows the migration cannot rewrite).
+ var legacyID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, originator_user_id)
+ VALUES ($1, (SELECT runtime_id FROM agent WHERE id = $1), $2, 'queued', 0, $3) RETURNING id`,
+ agentID, issueID, userA).Scan(&legacyID); err != nil {
+ t.Fatalf("legacy-shaped row must be admitted by the exemption, got %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, legacyID) })
+
+ // The status transitions the new backend performs on such a stale task must all
+ // succeed — this is exactly what a bare invariant CHECK would have broken.
+ for _, status := range []string{"running", "completed", "cancelled"} {
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = $2 WHERE id = $1`, legacyID, status); err != nil {
+ t.Fatalf("status UPDATE to %q on a legacy row must succeed, got %v", status, err)
+ }
+ }
+}
+
+// TestTriggerOwnerAttribution_ScheduleTriggerCreator is the acceptance test for
+// trigger_owner (MUL-4302; Bohan): an autopilot schedule/webhook run is accountable
+// to the member who CREATED the firing trigger, with originator NULL (no human
+// authorized the autonomous fire).
+func TestTriggerOwnerAttribution_ScheduleTriggerCreator(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'trigger-owner-ap', $2, 'run_only', 'member', $3) RETURNING id`,
+ workspaceID, agentID, creatorID).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed autopilot: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ // Schedule trigger whose responsible publisher is the creating member.
+ var triggerID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
+ VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,
+ autopilotID, creatorID).Scan(&triggerID); err != nil {
+ t.Fatalf("seed trigger: %v", err)
+ }
+
+ got := triggerOwnerAttribution(ctx, q,
+ util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
+ attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
+ if got.Source != attribution.SourceTriggerOwner {
+ t.Fatalf("source = %q, want trigger_owner", got.Source)
+ }
+ if got.UserID.Valid {
+ t.Errorf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))
+ }
+ if !got.AccountableUserID.Valid || got.AccountableUserID.Bytes != util.MustParseUUID(creatorID).Bytes {
+ t.Errorf("accountable = %s, want trigger creator %s", util.UUIDToString(got.AccountableUserID), creatorID)
+ }
+}
+
+// TestTriggerOwnerAttribution_LegacyTriggerFallsBackToRuleOwner verifies the
+// backward-compat path Bohan signed off on: a trigger with no recorded creator
+// (created before this migration) degrades to the rule publisher (rule_owner),
+// never fabricating a human.
+func TestTriggerOwnerAttribution_LegacyTriggerFallsBackToRuleOwner(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'legacy-trigger-ap', $2, 'run_only', 'member', $3) RETURNING id`,
+ workspaceID, agentID, publisherID).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed autopilot: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ // Trigger with NO creator recorded (pre-migration style).
+ var triggerID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression)
+ VALUES ($1, 'schedule', true, '0 * * * *') RETURNING id`,
+ autopilotID).Scan(&triggerID); err != nil {
+ t.Fatalf("seed trigger: %v", err)
+ }
+ // Active rule version so the fallback resolves to rule_owner (the publisher).
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
+ VALUES ($1, $2, 'member', $3)`, autopilotID, workspaceID, publisherID); err != nil {
+ t.Fatalf("seed rule version: %v", err)
+ }
+
+ got := triggerOwnerAttribution(ctx, q,
+ util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
+ attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
+ if got.Source != attribution.SourceRuleOwner {
+ t.Fatalf("source = %q, want rule_owner (legacy trigger falls back)", got.Source)
+ }
+ if !got.AccountableUserID.Valid || got.AccountableUserID.Bytes != util.MustParseUUID(publisherID).Bytes {
+ t.Errorf("accountable = %s, want rule publisher %s", util.UUIDToString(got.AccountableUserID), publisherID)
+ }
+}
+
+// seedExtraMember inserts a standalone user + workspace member and returns the
+// user id, so a test can model an EDITOR distinct from the trigger creator.
+func seedExtraMember(t *testing.T, pool *pgxpool.Pool, workspaceID, label string) string {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var userID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ label, fmt.Sprintf("%s-%[email protected]", label, suffix)).Scan(&userID); err != nil {
+ t.Fatalf("seed %s user: %v", label, err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ workspaceID, userID); err != nil {
+ t.Fatalf("seed %s member: %v", label, err)
+ }
+ return userID
+}
+
+// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor is Elon's must-fix
+// acceptance test: it drives the REAL triggerOwnerAttribution resolver (not the
+// ruleOwnerAttribution helper) across the SAME queries the handlers use, and proves
+// both halves of the pinned model — (1) responsibility TRANSFERS from the creator to
+// whoever substantively edits the trigger, and (2) a trigger-scoped edit re-stamps
+// ONLY that trigger, never a sibling. It also proves an autopilot-level edit bumps
+// every trigger together (MUL-4302).
+func TestTriggerOwnerAttribution_TransfersToSubstantiveEditor(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorA, agentID, _ := seedAttributionFixture(t, pool)
+ editorB := seedExtraMember(t, pool, workspaceID, "editor-b")
+ editorC := seedExtraMember(t, pool, workspaceID, "editor-c")
+
+ var autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_id, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'transfer-ap', $2, 'run_only', 'member', $3) RETURNING id`,
+ workspaceID, agentID, creatorA).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed autopilot: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ // Two triggers, both initially published by creator A (the create-site default).
+ seedTrigger := func(cron string) string {
+ var id string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
+ VALUES ($1, 'schedule', true, $2, 'member', $3) RETURNING id`,
+ autopilotID, cron, creatorA).Scan(&id); err != nil {
+ t.Fatalf("seed trigger: %v", err)
+ }
+ return id
+ }
+ trigger1 := seedTrigger("0 * * * *")
+ trigger2 := seedTrigger("0 0 * * *")
+
+ accountableOf := func(triggerID string) string {
+ got := triggerOwnerAttribution(ctx, q,
+ util.MustParseUUID(triggerID), util.MustParseUUID(workspaceID), util.MustParseUUID(autopilotID),
+ attribution.EvidenceAutopilotRun, util.MustParseUUID(autopilotID))
+ if got.Source != attribution.SourceTriggerOwner {
+ t.Fatalf("trigger %s: source = %q, want trigger_owner", triggerID, got.Source)
+ }
+ if got.UserID.Valid {
+ t.Fatalf("trigger_owner is audit-only; originator must stay NULL, got %s", util.UUIDToString(got.UserID))
+ }
+ return util.UUIDToString(got.AccountableUserID)
+ }
+
+ // Baseline: both triggers attribute to creator A.
+ if a := accountableOf(trigger1); a != creatorA {
+ t.Fatalf("trigger1 baseline accountable = %s, want creator %s", a, creatorA)
+ }
+ if a := accountableOf(trigger2); a != creatorA {
+ t.Fatalf("trigger2 baseline accountable = %s, want creator %s", a, creatorA)
+ }
+
+ // B substantively edits trigger1 — the SAME query UpdateAutopilotTrigger runs.
+ if err := q.SetAutopilotTriggerPublisher(ctx, db.SetAutopilotTriggerPublisherParams{
+ ID: util.MustParseUUID(trigger1),
+ PublishedByType: pgtype.Text{String: "member", Valid: true},
+ PublishedByID: util.MustParseUUID(editorB),
+ }); err != nil {
+ t.Fatalf("SetAutopilotTriggerPublisher: %v", err)
+ }
+
+ // Transfer: trigger1 now attributes to editor B, NOT the original creator.
+ if a := accountableOf(trigger1); a != editorB {
+ t.Fatalf("after edit, trigger1 accountable = %s, want editor %s (responsibility must transfer)", a, editorB)
+ }
+ // Isolation: editing trigger1 must NOT move trigger2 — it stays with creator A.
+ if a := accountableOf(trigger2); a != creatorA {
+ t.Fatalf("trigger2 accountable = %s, want creator %s (editing a sibling must not transfer)", a, creatorA)
+ }
+
+ // C makes an autopilot-level substantive edit — the SAME bump-all query
+ // UpdateAutopilot runs — which governs every trigger of the autopilot.
+ if err := q.SetAutopilotTriggerPublishersByAutopilot(ctx, db.SetAutopilotTriggerPublishersByAutopilotParams{
+ AutopilotID: util.MustParseUUID(autopilotID),
+ PublishedByType: pgtype.Text{String: "member", Valid: true},
+ PublishedByID: util.MustParseUUID(editorC),
+ }); err != nil {
+ t.Fatalf("SetAutopilotTriggerPublishersByAutopilot: %v", err)
+ }
+ if a := accountableOf(trigger1); a != editorC {
+ t.Fatalf("after autopilot-level edit, trigger1 accountable = %s, want %s", a, editorC)
+ }
+ if a := accountableOf(trigger2); a != editorC {
+ t.Fatalf("after autopilot-level edit, trigger2 accountable = %s, want %s", a, editorC)
+ }
+}
+
+// TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner is the acceptance test for
+// rule_owner (MUL-4302 §3.4): an autopilot-origin issue's run has NO authorizing
+// human (originator_user_id stays NULL) but IS accountable to the publisher of the
+// autopilot's active rule version, with rule_version_id recording the snapshot.
+// This is the accountable-diverges-from-originator case.
+func TestEnqueueTaskForIssueAutopilotOriginStampsRuleOwner(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+
+ // A synthetic autopilot id (no FK) with an active rule version published by the
+ // member. gen_random_uuid() gives the autopilot id back so the issue can point
+ // its origin at it.
+ var ruleVersionID, autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
+ VALUES (gen_random_uuid(), $1, 'member', $2) RETURNING id, autopilot_id`,
+ workspaceID, publisherID).Scan(&ruleVersionID, &autopilotID); err != nil {
+ t.Fatalf("seed rule version: %v", err)
+ }
+
+ var issueID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
+ VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9001, 'autopilot', $3) RETURNING id`,
+ workspaceID, agentID, autopilotID).Scan(&issueID); err != nil {
+ t.Fatalf("seed autopilot-origin issue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "agent",
+ CreatorID: util.MustParseUUID(agentID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ OriginType: pgtype.Text{String: "autopilot", Valid: true},
+ OriginID: util.MustParseUUID(autopilotID),
+ })
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssue: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable, ruleVersion pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+
+ if source.String != string(attribution.SourceRuleOwner) {
+ t.Errorf("originator_source = %q, want rule_owner", source.String)
+ }
+ if originator.Valid {
+ t.Errorf("autopilot run must NOT set originator (authorization stays NULL), got %s", util.UUIDToString(originator))
+ }
+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {
+ t.Errorf("accountable_user_id = %s, want rule publisher %s", util.UUIDToString(accountable), publisherID)
+ }
+ if !ruleVersion.Valid || ruleVersion.Bytes != util.MustParseUUID(ruleVersionID).Bytes {
+ t.Errorf("rule_version_id = %s, want %s", util.UUIDToString(ruleVersion), ruleVersionID)
+ }
+}
+
+// TestEnqueueTaskForIssueAutopilotOriginWithoutVersionDegrades verifies that an
+// autopilot-origin issue whose autopilot has NO published rule version degrades to
+// unattributed (never fabricating a human) rather than crashing or bypassing.
+// TestEnqueueTaskForIssueAutopilotOriginWithoutVersionOwnerFallback: an
+// autopilot-origin issue whose autopilot has no published rule version resolves to
+// unattributed, then the default (non-fail-closed) workspace policy degrades it to
+// owner_fallback — accountable = agent owner, originator still NULL — so no run is
+// left without an accountable human (MUL-4302 §3.5).
+func TestEnqueueTaskForIssueAutopilotOriginWithoutVersionOwnerFallback(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, ownerID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var issueID, autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
+ VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9002, 'autopilot', gen_random_uuid()) RETURNING id, origin_id`,
+ workspaceID, agentID).Scan(&issueID, &autopilotID); err != nil {
+ t.Fatalf("seed autopilot-origin issue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "agent",
+ CreatorID: util.MustParseUUID(agentID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ OriginType: pgtype.Text{String: "autopilot", Valid: true},
+ OriginID: util.MustParseUUID(autopilotID),
+ })
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssue: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id FROM agent_task_queue WHERE id = $1`,
+ task.ID).Scan(&source, &originator, &accountable); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceOwnerFallback) {
+ t.Errorf("originator_source = %q, want owner_fallback", source.String)
+ }
+ if originator.Valid {
+ t.Errorf("owner_fallback is audit-only; originator must stay NULL, got %s", util.UUIDToString(originator))
+ }
+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(ownerID).Bytes {
+ t.Errorf("accountable_user_id = %s, want agent owner %s", util.UUIDToString(accountable), ownerID)
+ }
+}
+
+// TestEnqueueTaskFailClosedRefusesUnattributed: with the workspace opted into
+// fail-closed, an unattributable run (autopilot-origin issue, no rule version) is
+// REFUSED at enqueue (ErrAttributionFailClosed) rather than degraded to
+// owner_fallback (MUL-4302 §3.5).
+func TestEnqueueTaskFailClosedRefusesUnattributed(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, _, agentID, _ := seedAttributionFixture(t, pool)
+ if _, err := pool.Exec(ctx, `UPDATE workspace SET attribution_fail_closed = TRUE WHERE id = $1`, workspaceID); err != nil {
+ t.Fatalf("set fail-closed: %v", err)
+ }
+
+ var issueID, autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
+ VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9003, 'autopilot', gen_random_uuid()) RETURNING id, origin_id`,
+ workspaceID, agentID).Scan(&issueID, &autopilotID); err != nil {
+ t.Fatalf("seed autopilot-origin issue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ _, err := svc.EnqueueTaskForIssue(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "agent",
+ CreatorID: util.MustParseUUID(agentID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ OriginType: pgtype.Text{String: "autopilot", Valid: true},
+ OriginID: util.MustParseUUID(autopilotID),
+ })
+ if !errors.Is(err, ErrAttributionFailClosed) {
+ t.Fatalf("EnqueueTaskForIssue error = %v, want ErrAttributionFailClosed", err)
+ }
+ // No task row should have been created for the issue.
+ var count int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&count); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ if count != 0 {
+ t.Errorf("fail-closed must not enqueue any task, found %d", count)
+ }
+}
+
+// seedRunOnlyAutopilot creates an active run_only autopilot (agent-assigned) plus a
+// running autopilot_run for it, and returns their ids. Used to exercise
+// dispatchRunOnly's direct CreateAutopilotTask path.
+func seedRunOnlyAutopilot(t *testing.T, pool *pgxpool.Pool, workspaceID, agentID, creatorID string) (autopilotID, runID string) {
+ t.Helper()
+ ctx := context.Background()
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_type, assignee_id, status, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'run-only ap', 'agent', $2, 'active', 'run_only', 'member', $3) RETURNING id`,
+ workspaceID, agentID, creatorID).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed autopilot: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_run (autopilot_id, source, status) VALUES ($1, 'manual', 'running') RETURNING id`,
+ autopilotID).Scan(&runID); err != nil {
+ t.Fatalf("seed autopilot run: %v", err)
+ }
+ return autopilotID, runID
+}
+
+// TestDispatchRunOnlyScheduleStampsRuleOwnerRow is the run_only row assertion Elon
+// asked for: the direct CreateAutopilotTask path (no member actor → schedule-like)
+// must persist rule_owner on the queue row — originator NULL, accountable = the
+// active rule version publisher, rule_version_id set.
+func TestDispatchRunOnlyScheduleStampsRuleOwnerRow(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+ autopilotID, runID := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, publisherID)
+
+ var ruleVersionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
+ VALUES ($1, $2, 'member', $3) RETURNING id`, autopilotID, workspaceID, publisherID).Scan(&ruleVersionID); err != nil {
+ t.Fatalf("seed rule version: %v", err)
+ }
+
+ svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
+ ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
+ if err != nil {
+ t.Fatalf("get autopilot: %v", err)
+ }
+ run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
+ if err != nil {
+ t.Fatalf("get run: %v", err)
+ }
+ // No member actor → schedule/webhook-style rule_owner attribution.
+ if err := svc.dispatchRunOnly(ctx, ap, &run, pgtype.UUID{}); err != nil {
+ t.Fatalf("dispatchRunOnly: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable, ruleVersion pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
+ FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceRuleOwner) {
+ t.Errorf("originator_source = %q, want rule_owner", source.String)
+ }
+ if originator.Valid {
+ t.Errorf("run_only autopilot must NOT set originator, got %s", util.UUIDToString(originator))
+ }
+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(publisherID).Bytes {
+ t.Errorf("accountable_user_id = %s, want publisher %s", util.UUIDToString(accountable), publisherID)
+ }
+ if !ruleVersion.Valid || ruleVersion.Bytes != util.MustParseUUID(ruleVersionID).Bytes {
+ t.Errorf("rule_version_id = %s, want %s", util.UUIDToString(ruleVersion), ruleVersionID)
+ }
+}
+
+// TestDispatchRunOnlyManualStampsDirectHuman verifies the blocking-finding fix on the
+// run_only path: a MANUAL trigger attributes direct_human to the triggering member —
+// originator == accountable == actor, no rule_version — even when the autopilot has a
+// published rule owned by someone else (MUL-4302 §4).
+func TestDispatchRunOnlyManualStampsDirectHuman(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+ autopilotID, runID := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, publisherID)
+
+ // A rule version published by the creator exists; the manual actor is a
+ // DIFFERENT member, who must win.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
+ VALUES ($1, $2, 'member', $3)`, autopilotID, workspaceID, publisherID); err != nil {
+ t.Fatalf("seed rule version: %v", err)
+ }
+ var actorID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Trigger', $1) RETURNING id`,
+ fmt.Sprintf("trigger-%[email protected]", time.Now().UnixNano())).Scan(&actorID); err != nil {
+ t.Fatalf("seed actor: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ workspaceID, actorID); err != nil {
+ t.Fatalf("seed actor member: %v", err)
+ }
+
+ svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
+ ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
+ if err != nil {
+ t.Fatalf("get autopilot: %v", err)
+ }
+ run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
+ if err != nil {
+ t.Fatalf("get run: %v", err)
+ }
+ if err := svc.dispatchRunOnly(ctx, ap, &run, util.MustParseUUID(actorID)); err != nil {
+ t.Fatalf("dispatchRunOnly: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable, ruleVersion pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
+ FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(actorID).Bytes {
+ t.Errorf("originator_user_id = %s, want triggering member %s", util.UUIDToString(originator), actorID)
+ }
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable_user_id = %s, want == originator (actor)", util.UUIDToString(accountable))
+ }
+ if ruleVersion.Valid {
+ t.Errorf("manual direct_human must not set rule_version_id, got %s", util.UUIDToString(ruleVersion))
+ }
+}
+
+// TestDispatchRunOnlyScheduleTransfersToEditor is Elon's must-fix REAL dispatch test:
+// it drives dispatchRunOnly end to end (schedule-style, no member actor) and asserts
+// the PERSISTED agent_task_queue row's accountable_user_id follows the trigger's
+// current responsible publisher after a substantive edit — the creator seeds it, then
+// a later editor's re-stamp (the same SetAutopilotTriggerPublisher the UpdateTrigger
+// handler runs) makes future runs attribute to the editor, with originator still NULL
+// (MUL-4302). The resolver-level before/after and per-trigger isolation are covered by
+// TestTriggerOwnerAttribution_TransfersToSubstantiveEditor.
+func TestDispatchRunOnlyScheduleTransfersToEditor(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorA, agentID, _ := seedAttributionFixture(t, pool)
+ editorB := seedExtraMember(t, pool, workspaceID, "dispatch-editor-b")
+
+ var autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot (workspace_id, title, assignee_type, assignee_id, status, execution_mode, created_by_type, created_by_id)
+ VALUES ($1, 'dispatch-transfer-ap', 'agent', $2, 'active', 'run_only', 'member', $3) RETURNING id`,
+ workspaceID, agentID, creatorA).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed autopilot: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM autopilot WHERE id = $1`, autopilotID) })
+
+ // Schedule trigger initially published by creator A, then edited by B.
+ var triggerID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, published_by_type, published_by_id)
+ VALUES ($1, 'schedule', true, '0 * * * *', 'member', $2) RETURNING id`,
+ autopilotID, creatorA).Scan(&triggerID); err != nil {
+ t.Fatalf("seed trigger: %v", err)
+ }
+ if err := q.SetAutopilotTriggerPublisher(ctx, db.SetAutopilotTriggerPublisherParams{
+ ID: util.MustParseUUID(triggerID),
+ PublishedByType: pgtype.Text{String: "member", Valid: true},
+ PublishedByID: util.MustParseUUID(editorB),
+ }); err != nil {
+ t.Fatalf("SetAutopilotTriggerPublisher: %v", err)
+ }
+
+ // A running schedule run bound to that trigger — the shape the scheduler dispatches.
+ var runID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_run (autopilot_id, trigger_id, source, status)
+ VALUES ($1, $2, 'schedule', 'running') RETURNING id`,
+ autopilotID, triggerID).Scan(&runID); err != nil {
+ t.Fatalf("seed run: %v", err)
+ }
+
+ svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}}
+ ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
+ if err != nil {
+ t.Fatalf("get autopilot: %v", err)
+ }
+ run, err := q.GetAutopilotRun(ctx, util.MustParseUUID(runID))
+ if err != nil {
+ t.Fatalf("get run: %v", err)
+ }
+ // No member actor → schedule/webhook-style trigger_owner attribution.
+ if err := svc.dispatchRunOnly(ctx, ap, &run, pgtype.UUID{}); err != nil {
+ t.Fatalf("dispatchRunOnly: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id
+ FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID).Scan(&source, &originator, &accountable); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceTriggerOwner) {
+ t.Errorf("originator_source = %q, want trigger_owner", source.String)
+ }
+ if originator.Valid {
+ t.Errorf("schedule dispatch must NOT set originator, got %s", util.UUIDToString(originator))
+ }
+ if !accountable.Valid || accountable.Bytes != util.MustParseUUID(editorB).Bytes {
+ t.Errorf("accountable_user_id = %s, want editor %s (dispatch must follow the transferred publisher, not creator %s)",
+ util.UUIDToString(accountable), editorB, creatorA)
+ }
+}
+
+// TestEnqueueTaskForIssueAutopilotManualStampsDirectHuman verifies the manual fix on
+// the create_issue path: enqueuing an autopilot-origin issue WITH a triggering actor
+// (as dispatchCreateIssue does for a manual trigger) attributes direct_human to that
+// actor, not rule_owner — the actor override wins over the autopilot-origin branch.
+func TestEnqueueTaskForIssueAutopilotManualStampsDirectHuman(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var autopilotID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_rule_version (autopilot_id, workspace_id, published_by_type, published_by_id)
+ VALUES (gen_random_uuid(), $1, 'member', $2) RETURNING autopilot_id`,
+ workspaceID, publisherID).Scan(&autopilotID); err != nil {
+ t.Fatalf("seed rule version: %v", err)
+ }
+ var issueID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, assignee_type, assignee_id, priority, number, origin_type, origin_id)
+ VALUES ($1, 'autopilot issue', 'agent', $2, 'agent', $2, 'medium', 9101, 'autopilot', $3) RETURNING id`,
+ workspaceID, agentID, autopilotID).Scan(&issueID); err != nil {
+ t.Fatalf("seed autopilot-origin issue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ // A distinct triggering member (not the rule publisher) manually triggers.
+ var actorID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Trigger', $1) RETURNING id`,
+ fmt.Sprintf("trig2-%[email protected]", time.Now().UnixNano())).Scan(&actorID); err != nil {
+ t.Fatalf("seed actor: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, actorID) })
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ // dispatchCreateIssue routes a manual trigger through the actor-carrying enqueue.
+ task, err := svc.EnqueueTaskForIssueWithHandoff(ctx, db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "agent",
+ CreatorID: util.MustParseUUID(agentID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ OriginType: pgtype.Text{String: "autopilot", Valid: true},
+ OriginID: util.MustParseUUID(autopilotID),
+ }, "", util.MustParseUUID(actorID))
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssueWithHandoff: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable, ruleVersion pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, rule_version_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &ruleVersion); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(actorID).Bytes {
+ t.Errorf("originator_user_id = %s, want actor %s", util.UUIDToString(originator), actorID)
+ }
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable_user_id = %s, want == originator (actor)", util.UUIDToString(accountable))
+ }
+ if ruleVersion.Valid {
+ t.Errorf("manual direct_human must not set rule_version_id, got %s", util.UUIDToString(ruleVersion))
+ }
+}
+
+// TestRecordAutopilotRuleVersionRepublishReattributes verifies the final Phase 1
+// item (MUL-4302 §3.4): republishing a rule (as a trigger edit / archive / system
+// pause does) appends a new version, the LATEST version is the active one, and
+// dispatch attribution follows it. So editing member A's autopilot as member B
+// re-attributes subsequent runs to B; a system pause records a 'system' publisher.
+func TestRecordAutopilotRuleVersionRepublishReattributes(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, memberA, agentID, _ := seedAttributionFixture(t, pool)
+ autopilotID, _ := seedRunOnlyAutopilot(t, pool, workspaceID, agentID, memberA)
+
+ var memberB string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Editor', $1) RETURNING id`,
+ fmt.Sprintf("editor-%[email protected]", time.Now().UnixNano())).Scan(&memberB); err != nil {
+ t.Fatalf("seed member B: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, memberB) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ workspaceID, memberB); err != nil {
+ t.Fatalf("seed member B membership: %v", err)
+ }
+
+ ap, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotID))
+ if err != nil {
+ t.Fatalf("get autopilot: %v", err)
+ }
+ verParams := db.GetActiveAutopilotRuleVersionParams{WorkspaceID: ap.WorkspaceID, AutopilotID: ap.ID}
+
+ // v1: creator (member A) publishes; active + dispatch attribute to A.
+ if err := RecordAutopilotRuleVersion(ctx, q, ap, "member", util.MustParseUUID(memberA)); err != nil {
+ t.Fatalf("record v1: %v", err)
+ }
+ active, err := q.GetActiveAutopilotRuleVersion(ctx, verParams)
+ if err != nil || active.PublishedByType != "member" || active.PublishedByID.Bytes != util.MustParseUUID(memberA).Bytes {
+ t.Fatalf("v1 active = %+v (err %v), want member A", active, err)
+ }
+
+ // v2: member B republishes (e.g. edited a trigger) → latest wins.
+ if err := RecordAutopilotRuleVersion(ctx, q, ap, "member", util.MustParseUUID(memberB)); err != nil {
+ t.Fatalf("record v2: %v", err)
+ }
+ attr := ruleOwnerAttribution(ctx, q, ap.WorkspaceID, ap.ID, attribution.EvidenceAutopilotRun, ap.ID)
+ if attr.Source != attribution.SourceRuleOwner || attr.AccountableUserID.Bytes != util.MustParseUUID(memberB).Bytes {
+ t.Errorf("after republish, dispatch attribution = %+v, want rule_owner accountable = member B", attr)
+ }
+
+ // v3: system auto-pause records a 'system' publisher (no member id).
+ if err := RecordAutopilotRuleVersion(ctx, q, ap, "system", pgtype.UUID{}); err != nil {
+ t.Fatalf("record v3 (system): %v", err)
+ }
+ active, err = q.GetActiveAutopilotRuleVersion(ctx, verParams)
+ if err != nil || active.PublishedByType != "system" || active.PublishedByID.Valid {
+ t.Errorf("v3 active = %+v (err %v), want system publisher with NULL id", active, err)
+ }
+ // A system-published version has no member → dispatch degrades to unattributed
+ // (never fabricates a human).
+ sysAttr := ruleOwnerAttribution(ctx, q, ap.WorkspaceID, ap.ID, attribution.EvidenceAutopilotRun, ap.ID)
+ if sysAttr.Source != attribution.SourceUnattributed || sysAttr.AccountableUserID.Valid {
+ t.Errorf("system-published version must yield unattributed, got %+v", sysAttr)
+ }
+}
+
+// TestApplyAttributionFallbackRefusesOnMissingOwner: an unattributed run in an
+// OPEN (non-fail-closed) workspace whose agent has no valid owner cannot resolve an
+// accountable human via owner_fallback, so the enqueue is refused rather than
+// creating a NULL-accountable task (MUL-4302 §3.5, Elon must-fix 1).
+func TestApplyAttributionFallbackRefusesOnMissingOwner(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, _, _, _ := seedAttributionFixture(t, pool) // default policy = open
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ unattr := attribution.Unattributed(attribution.EvidenceIssueAssignment, util.MustParseUUID(workspaceID))
+ _, err := svc.applyAttributionFallback(ctx, unattr, db.Agent{WorkspaceID: util.MustParseUUID(workspaceID)}) // OwnerID zero
+ if !errors.Is(err, ErrAttributionFailClosed) {
+ t.Fatalf("missing owner: err = %v, want ErrAttributionFailClosed", err)
+ }
+}
+
+// TestApplyAttributionFallbackRefusesOnPolicyReadFailure: if the workspace policy
+// cannot be read for an unattributed run, fail CLOSED (refuse) rather than silently
+// running an unattributable task — even when a valid owner is present (Elon must-fix 1).
+func TestApplyAttributionFallbackRefusesOnPolicyReadFailure(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ _, ownerID, _, _ := seedAttributionFixture(t, pool)
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ unattr := attribution.Unattributed(attribution.EvidenceIssueAssignment, pgtype.UUID{})
+ missingWs := pgtype.UUID{Bytes: [16]byte{0xDE, 0xAD, 0xBE, 0xEF}, Valid: true} // no such workspace
+ _, err := svc.applyAttributionFallback(ctx, unattr, db.Agent{WorkspaceID: missingWs, OwnerID: util.MustParseUUID(ownerID)})
+ if !errors.Is(err, ErrAttributionFailClosed) {
+ t.Fatalf("policy read failure: err = %v, want ErrAttributionFailClosed", err)
+ }
+}
+
+// TestApplyAttributionFallbackPreciseUntouched: a precise attribution never reads
+// the policy and passes through unchanged (proven with a nil-Queries service).
+func TestApplyAttributionFallbackPreciseUntouched(t *testing.T) {
+ svc := &TaskService{} // no Queries: a policy read would panic/error if attempted
+ precise := attribution.DirectHumanRun(pgtype.UUID{Bytes: [16]byte{0x11}, Valid: true}, attribution.EvidenceComment, pgtype.UUID{})
+ got, err := svc.applyAttributionFallback(context.Background(), precise, db.Agent{})
+ if err != nil {
+ t.Fatalf("precise attribution must not error: %v", err)
+ }
+ if got.Source != attribution.SourceDirectHuman || got != precise {
+ t.Errorf("precise attribution must pass through unchanged, got %+v", got)
+ }
+}
+
+// TestRerunIssueAttributesToRerunningMember is the §5 acceptance test: a manual
+// rerun is a NEW direct_human trigger attributed to the member who re-ran — not the
+// original run's human — and records rerun_of_task_id lineage back to the source.
+func TestRerunIssueAttributesToRerunningMember(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
+
+ // A distinct member performs the rerun.
+ var rerunnerID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('Rerunner', $1) RETURNING id`,
+ fmt.Sprintf("rerunner-%[email protected]", time.Now().UnixNano())).Scan(&rerunnerID); err != nil {
+ t.Fatalf("seed rerunner: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, rerunnerID) })
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ workspaceID, rerunnerID); err != nil {
+ t.Fatalf("seed rerunner member: %v", err)
+ }
+
+ issueStruct := db.Issue{
+ ID: util.MustParseUUID(issueID),
+ AssigneeID: util.MustParseUUID(agentID),
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: util.MustParseUUID(creatorID),
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ }
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ // The original run, attributed to the issue creator.
+ orig, err := svc.EnqueueTaskForIssue(ctx, issueStruct)
+ if err != nil {
+ t.Fatalf("EnqueueTaskForIssue (original): %v", err)
+ }
+
+ // The rerun, performed by a different member.
+ task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), orig.ID, pgtype.UUID{}, util.MustParseUUID(rerunnerID), nil)
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+
+ var source pgtype.Text
+ var originator, accountable, rerunOf pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, rerun_of_task_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &rerunOf); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(rerunnerID).Bytes {
+ t.Errorf("originator_user_id = %s, want rerunner %s (not creator %s)", util.UUIDToString(originator), rerunnerID, creatorID)
+ }
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable_user_id = %s, want == originator (rerunner)", util.UUIDToString(accountable))
+ }
+ if !rerunOf.Valid || rerunOf.Bytes != orig.ID.Bytes {
+ t.Errorf("rerun_of_task_id = %s, want original task %s", util.UUIDToString(rerunOf), util.UUIDToString(orig.ID))
+ }
+}
+
+// TestEnqueueChatTaskStampsChatEvidence verifies the chat enqueue path is no
+// longer a NULL-source bypass and uses the UNIFORM evidence pair: the sender is a
+// direct_human originator+accountable, and evidence is (kind=chat,
+// ref=chat_session_id) so the attribution UI links to the conversation the same
+// way it does for autopilot_run / issue_assignment (MUL-4302 §2, Elon 2nd-round).
+func TestEnqueueChatTaskStampsChatEvidence(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var chatSessionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false)
+ if err != nil {
+ t.Fatalf("EnqueueChatTask: %v", err)
+ }
+
+ var source, evidenceKind pgtype.Text
+ var originator, accountable, evidenceRef pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT originator_source, originator_user_id, accountable_user_id, trigger_evidence_kind, trigger_evidence_ref_id
+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&source, &originator, &accountable, &evidenceKind, &evidenceRef); err != nil {
+ t.Fatalf("read stored attribution: %v", err)
+ }
+
+ if source.String != string(attribution.SourceDirectHuman) {
+ t.Errorf("originator_source = %q, want direct_human", source.String)
+ }
+ if !originator.Valid || originator.Bytes != util.MustParseUUID(userID).Bytes {
+ t.Errorf("originator_user_id = %s, want sender %s", util.UUIDToString(originator), userID)
+ }
+ if !accountable.Valid || accountable.Bytes != originator.Bytes {
+ t.Errorf("accountable_user_id = %s, want == originator", util.UUIDToString(accountable))
+ }
+ if evidenceKind.String != string(attribution.EvidenceChat) {
+ t.Errorf("trigger_evidence_kind = %q, want chat", evidenceKind.String)
+ }
+ if !evidenceRef.Valid || evidenceRef.Bytes != util.MustParseUUID(chatSessionID).Bytes {
+ t.Errorf("trigger_evidence_ref_id = %s, want chat session %s", util.UUIDToString(evidenceRef), chatSessionID)
+ }
+}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 3d6049bb4d..d40c2f6710 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -14,6 +14,8 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/attribution"
+ "github.com/multica-ai/multica/server/internal/dispatch"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/issueposition"
@@ -47,6 +49,50 @@ func NewAutopilotService(q *db.Queries, tx TxStarter, bus *events.Bus, taskSvc *
return &AutopilotService{Queries: q, TxStarter: tx, Bus: bus, TaskSvc: taskSvc}
}
+// autopilotRuleConfigSummary captures the substantive (accountability-bearing)
+// config of an autopilot at publish time, stored on each rule-version snapshot for
+// audit display (MUL-4302 §7). Cosmetic fields (title / description / issue title
+// template) are intentionally excluded — changing them does not transfer
+// accountability. Trigger config (cron / webhook / event_filters) lives in a
+// separate table and is not inlined here; a trigger edit still republishes the
+// rule (recording the editing member + timestamp), the summary just carries the
+// autopilot row's core config.
+type autopilotRuleConfigSummary struct {
+ AssigneeType string `json:"assignee_type"`
+ AssigneeID string `json:"assignee_id"`
+ Status string `json:"status"`
+ ExecutionMode string `json:"execution_mode"`
+}
+
+// RecordAutopilotRuleVersion appends one rule-version snapshot for a substantive
+// publish (MUL-4302 §3.4), recording the publisher and the effective config. Shared
+// by the handler publish paths (create / update / trigger edits / archive, run in
+// their tx) and the failure monitor's system-pause (a different package). q is the
+// caller's *db.Queries (tx-scoped where the caller wants atomicity). publishedByType
+// is "member" (with the acting member id) or "system" (with an invalid id, e.g. the
+// auto-pause monitor).
+func RecordAutopilotRuleVersion(ctx context.Context, q *db.Queries, ap db.Autopilot, publishedByType string, publishedByID pgtype.UUID) error {
+ summary, err := json.Marshal(autopilotRuleConfigSummary{
+ AssigneeType: ap.AssigneeType,
+ AssigneeID: util.UUIDToString(ap.AssigneeID),
+ Status: ap.Status,
+ ExecutionMode: ap.ExecutionMode,
+ })
+ if err != nil {
+ return fmt.Errorf("marshal rule version config summary: %w", err)
+ }
+ if _, err := q.CreateAutopilotRuleVersion(ctx, db.CreateAutopilotRuleVersionParams{
+ AutopilotID: ap.ID,
+ WorkspaceID: ap.WorkspaceID,
+ PublishedByType: publishedByType,
+ PublishedByID: publishedByID,
+ ConfigSummary: summary,
+ }); err != nil {
+ return fmt.Errorf("create autopilot rule version: %w", err)
+ }
+ return nil
+}
+
// DispatchAutopilot is the core execution entry point.
// It creates a run and either creates an issue or enqueues a direct agent task
// depending on execution_mode.
@@ -72,7 +118,32 @@ func (s *AutopilotService) DispatchAutopilot(
source string,
payload []byte,
) (*db.AutopilotRun, error) {
- return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{})
+ // No member actor on this entry point (schedule / webhook / api, or a manual
+ // trigger without a resolved member): attribution resolves rule_owner. These
+ // callers don't surface a per-run reason code to a human, so it is dropped.
+ // webhookDeliveryID is invalid here — durable webhook deliveries admit through
+ // AdmitAutopilotWebhookDelivery instead of this entry point.
+ run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{}, pgtype.UUID{})
+ return run, err
+}
+
+// DispatchAutopilotManual is the "run now" entry point for a member manually
+// triggering an autopilot. Unlike scheduled / webhook / api dispatch (no human in
+// the loop → rule_owner), a manual trigger is a direct human action: the run is
+// attributed direct_human to actorUserID, which becomes BOTH its originator
+// (authorization) and accountable human (MUL-4302 §4), across both execution modes.
+// An invalid actorUserID behaves exactly like DispatchAutopilot(source="manual").
+func (s *AutopilotService) DispatchAutopilotManual(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ payload []byte,
+ actorUserID pgtype.UUID,
+) (*db.AutopilotRun, dispatch.ReasonCode, error) {
+ // The manual path is the one surface that shows a per-run outcome to a human,
+ // so it returns the typed reason code decided at the admission source. No
+ // webhook delivery on the manual path.
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, "manual", payload, pgtype.Timestamptz{}, pgtype.UUID{}, actorUserID)
}
// AdmitAutopilotWebhookDelivery creates or reuses the idempotent run for a
@@ -99,7 +170,9 @@ func (s *AutopilotService) AdmitAutopilotWebhookDelivery(
return nil, fmt.Errorf("admit webhook delivery: lookup existing run: %w", err)
}
- if reason, skip := s.shouldSkipDispatch(ctx, autopilot); skip {
+ // Webhook admission has no member actor → automation principal (rule_owner);
+ // the per-run reason code is not surfaced to a human here, so it is dropped.
+ if reason, _, skip := s.shouldSkipDispatch(ctx, autopilot, pgtype.UUID{}); skip {
run, err := s.recordSkippedRun(
ctx,
autopilot,
@@ -210,7 +283,10 @@ func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(
return run, fmt.Errorf("dispatch for webhook delivery: lookup linked task: %w", taskErr)
}
}
- return s.dispatchAutopilotRun(ctx, autopilot, triggerID, "webhook", run)
+ // Webhook worker dispatch has no member actor and no human reason-code
+ // surface, so actorUserID is invalid and the reason code is dropped.
+ dispatched, _, err := s.dispatchAutopilotRun(ctx, autopilot, triggerID, "webhook", run, pgtype.UUID{})
+ return dispatched, err
}
// ensureWebhookCreateIssueTask repairs the create_issue crash window after the
@@ -330,7 +406,11 @@ func (s *AutopilotService) DispatchAutopilotForPlan(
return nil, fmt.Errorf("dispatch for plan: lookup existing run: %w", err)
}
- return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{})
+ // Scheduled dispatch has no member actor → rule_owner attribution, and no
+ // human surface for a per-run reason code, so it is dropped. No webhook
+ // delivery on the scheduled-plan path.
+ run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{}, pgtype.UUID{})
+ return run, err
}
// isAutopilotRunComplete decides whether an existing autopilot_run row
@@ -381,9 +461,11 @@ func (s *AutopilotService) dispatchAutopilot(
payload []byte,
plannedAt pgtype.Timestamptz,
webhookDeliveryID pgtype.UUID,
-) (*db.AutopilotRun, error) {
- if reason, skip := s.shouldSkipDispatch(ctx, autopilot); skip {
- return s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)
+ actorUserID pgtype.UUID,
+) (*db.AutopilotRun, dispatch.ReasonCode, error) {
+ if reason, code, skip := s.shouldSkipDispatch(ctx, autopilot, actorUserID); skip {
+ run, err := s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)
+ return run, code, err
}
// Determine initial status based on execution mode.
@@ -403,10 +485,10 @@ func (s *AutopilotService) dispatchAutopilot(
WebhookDeliveryID: webhookDeliveryID,
})
if err != nil {
- return nil, fmt.Errorf("create run: %w", err)
+ return nil, dispatch.ReasonInternalError, fmt.Errorf("create run: %w", err)
}
s.captureAutopilotRunStarted(autopilot, run, source)
- return s.dispatchAutopilotRun(ctx, autopilot, triggerID, source, &run)
+ return s.dispatchAutopilotRun(ctx, autopilot, triggerID, source, &run, actorUserID)
}
// dispatchAutopilotRun performs the downstream side effect for an already
@@ -419,31 +501,32 @@ func (s *AutopilotService) dispatchAutopilotRun(
triggerID pgtype.UUID,
source string,
run *db.AutopilotRun,
-) (*db.AutopilotRun, error) {
+ actorUserID pgtype.UUID,
+) (*db.AutopilotRun, dispatch.ReasonCode, error) {
switch autopilot.ExecutionMode {
case "create_issue":
triggerTimezone := s.resolveAutopilotTriggerTimezone(ctx, triggerID)
- if err := s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone); err != nil {
- if skipped := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
- return skipped, nil
+ if err := s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone, actorUserID); err != nil {
+ if skipped, code := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
+ return skipped, code, nil
}
s.failRun(ctx, run.ID, err.Error())
s.captureAutopilotRunFailed(autopilot, *run, source, err.Error())
- return run, fmt.Errorf("dispatch create_issue: %w", err)
+ return run, dispatchFailReasonCode(err), fmt.Errorf("dispatch create_issue: %w", err)
}
case "run_only":
- if err := s.dispatchRunOnly(ctx, autopilot, run); err != nil {
- if skipped := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
- return skipped, nil
+ if err := s.dispatchRunOnly(ctx, autopilot, run, actorUserID); err != nil {
+ if skipped, code := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
+ return skipped, code, nil
}
s.failRun(ctx, run.ID, err.Error())
s.captureAutopilotRunFailed(autopilot, *run, source, err.Error())
- return run, fmt.Errorf("dispatch run_only: %w", err)
+ return run, dispatchFailReasonCode(err), fmt.Errorf("dispatch run_only: %w", err)
}
default:
s.failRun(ctx, run.ID, "unknown execution_mode: "+autopilot.ExecutionMode)
s.captureAutopilotRunFailed(autopilot, *run, source, "unknown execution_mode: "+autopilot.ExecutionMode)
- return run, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)
+ return run, dispatch.ReasonInternalError, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)
}
// Update last_run_at on the autopilot.
@@ -462,7 +545,18 @@ func (s *AutopilotService) dispatchAutopilotRun(
},
})
- return run, nil
+ return run, "", nil
+}
+
+// dispatchFailReasonCode types a dispatch error that fell through to failRun.
+// It inspects the error with typed checks (never substring matching): a
+// fail-closed attribution refusal is attribution_blocked; everything else is an
+// unclassified internal error.
+func dispatchFailReasonCode(err error) dispatch.ReasonCode {
+ if errors.Is(err, ErrAttributionFailClosed) {
+ return dispatch.ReasonAttributionBlocked
+ }
+ return dispatch.ReasonInternalError
}
// dispatchCreateIssue creates an issue and enqueues a task for the agent.
@@ -476,7 +570,7 @@ func (s *AutopilotService) dispatchAutopilotRun(
// Creator on the issue is always the agent that will actually do the work
// (the resolved leader for a squad autopilot, otherwise the assignee agent
// itself), so activity / mentions render with the right author identity.
-func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, triggerTimezone string) error {
+func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, triggerTimezone string, actorUserID pgtype.UUID) error {
leader, _, err := s.resolveAutopilotLeader(ctx, ap)
if err != nil {
return fmt.Errorf("resolve leader: %w", err)
@@ -498,7 +592,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
); err != nil {
return fmt.Errorf("recent duplicate guard: %w", err)
} else if found {
- return &errDispatchSkipped{reason: "recent duplicate autopilot issue: " + util.UUIDToString(duplicate.ID)}
+ return &errDispatchSkipped{reason: "recent duplicate autopilot issue: " + util.UUIDToString(duplicate.ID), code: dispatch.ReasonAlreadyActive}
}
issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)
@@ -606,21 +700,33 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
// route to the resolved leader as the executing agent (Path A from
// MUL-2429); agent-assigned autopilots go through the standard issue
// path. Both code paths land in agent_task_queue with agent_id = leader.
+ // A MANUAL trigger (valid actorUserID) is a direct human action: enqueue via the
+ // actor-carrying entry points so attribution resolves direct_human to the
+ // triggering member (originator == accountable == actor, MUL-4302 §4). Schedule /
+ // webhook dispatch has no actor and takes the plain entry points, where the
+ // autopilot-origin issue resolves to rule_owner. The *WithHandoff variants are
+ // the existing actor-carrying enqueue methods; the handoff note is empty here.
if ap.AssigneeType == "squad" {
- // Fail-closed invocation gate: verify the autopilot creator may still
- // invoke the leader under the permission model. Catches configs that
- // predate the save-time gate, and admin-created configs that no longer
- // pass (MUL-3963).
- if !s.canCreatorInvokeAgent(ctx, ap, leader) {
- return fmt.Errorf("autopilot creator cannot access private squad leader")
+ // Fail-closed invocation gate: verify the admission principal (manual
+ // clicker, else creator — see autopilotAdmitInvoke) may still invoke the
+ // leader. Catches configs that predate the save-time gate, and configs
+ // that no longer pass (MUL-3963 / MUL-4525).
+ if !s.autopilotAdmitInvoke(ctx, ap, leader, actorUserID) {
+ return fmt.Errorf("not allowed to invoke private squad leader")
}
- if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}); err != nil {
+ if actorUserID.Valid {
+ if _, err := s.TaskSvc.EnqueueTaskForSquadLeaderWithHandoff(ctx, issue, leader.ID, ap.AssigneeID, "", actorUserID); err != nil {
+ return fmt.Errorf("enqueue squad leader task: %w", err)
+ }
+ } else if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, ap.AssigneeID, pgtype.UUID{}); err != nil {
return fmt.Errorf("enqueue squad leader task: %w", err)
}
- } else {
- if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
+ } else if actorUserID.Valid {
+ if _, err := s.TaskSvc.EnqueueTaskForIssueWithHandoff(ctx, issue, "", actorUserID); err != nil {
return fmt.Errorf("enqueue task for issue: %w", err)
}
+ } else if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
+ return fmt.Errorf("enqueue task for issue: %w", err)
}
slog.Info("autopilot dispatched (create_issue)",
@@ -724,6 +830,10 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate(
// monitor would auto-pause autopilots whose only crime was a flaky runtime).
type errDispatchSkipped struct {
reason string
+ // code is the stable, typed admission reason decided at THIS branch and
+ // carried through to the response (MUL-4525) — never reverse-engineered from
+ // the human-readable reason string above.
+ code dispatch.ReasonCode
}
func (e *errDispatchSkipped) Error() string { return e.reason }
@@ -736,14 +846,14 @@ func (e *errDispatchSkipped) Error() string { return e.reason }
// applies also run here as belt-and-braces: if the leader changed between
// admission and dispatch, or the runtime went offline in the gap, we still
// fail closed instead of enqueueing a doomed task.
-func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun) error {
+func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, actorUserID pgtype.UUID) error {
agent, _, err := s.resolveAutopilotLeader(ctx, ap)
if err != nil {
// Same admission-vs-failure classification as shouldSkipDispatch:
// if the row disappeared or the squad was archived between
// admission and dispatch, that is a skip, not a failure.
if errors.Is(err, pgx.ErrNoRows) || errors.Is(err, errSquadArchived) {
- return &errDispatchSkipped{reason: formatAdmissionReason(ap, "assignee no longer resolvable")}
+ return &errDispatchSkipped{reason: formatAdmissionReason(ap, "assignee no longer resolvable"), code: dispatch.ReasonTargetUnavailable}
}
return fmt.Errorf("resolve leader: %w", err)
}
@@ -752,14 +862,39 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
return fmt.Errorf("check agent readiness: %w", err)
}
if !ready {
- return &errDispatchSkipped{reason: formatAdmissionReason(ap, reason)}
+ return &errDispatchSkipped{reason: formatAdmissionReason(ap, reason), code: agentReadinessReasonCode(agent)}
+ }
+
+ // Fail-closed invocation gate for squad autopilots (admission principal =
+ // manual clicker, else creator — see autopilotAdmitInvoke).
+ if ap.AssigneeType == "squad" && !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID) {
+ return &errDispatchSkipped{reason: formatAdmissionReason(ap, "not allowed to invoke private squad leader"), code: dispatch.ReasonInvocationNotAllowed}
+ }
+
+ // Attribution splits on the trigger. A MANUAL trigger is a direct human action:
+ // the triggering member is direct_human and becomes BOTH originator (so the run
+ // carries their authorization context) and accountable (MUL-4302 §4). A
+ // schedule / webhook trigger has no human — originator_user_id stays NULL and
+ // the audit-accountable human is the member currently RESPONSIBLE for the firing
+ // trigger's effective config (its creator, then whoever last substantively edited
+ // it) — trigger_owner, resolved from run.TriggerID (MUL-4302; Elon must-fix) —
+ // degrading to the rule version publisher (rule_owner) when no such member is
+ // recoverable, then to unattributed. Either way evidence points at the autopilot
+ // run and the row is never a NULL-source bypass.
+ var autopilotAttr attribution.Result
+ if actorUserID.Valid {
+ autopilotAttr = attribution.DirectHumanRun(actorUserID, attribution.EvidenceAutopilotRun, run.ID)
+ } else {
+ autopilotAttr = triggerOwnerAttribution(ctx, s.Queries, run.TriggerID, ap.WorkspaceID, ap.ID, attribution.EvidenceAutopilotRun, run.ID)
}
-
- // Fail-closed invocation gate for squad autopilots.
- if ap.AssigneeType == "squad" && !s.canCreatorInvokeAgent(ctx, ap, agent) {
- return &errDispatchSkipped{reason: formatAdmissionReason(ap, "creator cannot access private squad leader")}
+ // If no precise human resolved (a version-less autopilot), degrade to
+ // owner_fallback (accountable = agent owner), or skip the dispatch when the
+ // workspace is fail-closed (MUL-4302 §3.5).
+ autopilotAttr, err = s.TaskSvc.applyAttributionFallback(ctx, autopilotAttr, agent)
+ if err != nil {
+ return &errDispatchSkipped{reason: formatAdmissionReason(ap, "workspace fail-closed: no accountable human for autopilot run"), code: dispatch.ReasonAttributionBlocked}
}
-
+ apSource, _, apEvidenceKind, apEvidenceRef := attributionCreateParams(autopilotAttr)
task, err := s.Queries.CreateAutopilotTask(ctx, db.CreateAutopilotTaskParams{
AgentID: agent.ID,
RuntimeID: agent.RuntimeID,
@@ -772,6 +907,12 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
String: truncateForSummary(ap.Title, triggerSummaryMaxLen),
Valid: ap.Title != "",
},
+ OriginatorUserID: autopilotAttr.UserID,
+ AccountableUserID: autopilotAttr.AccountableUserID,
+ RuleVersionID: autopilotAttr.RuleVersionID,
+ OriginatorSource: apSource,
+ TriggerEvidenceKind: apEvidenceKind,
+ TriggerEvidenceRefID: apEvidenceRef,
})
if err != nil {
return fmt.Errorf("create autopilot task: %w", err)
@@ -975,10 +1116,10 @@ func taskFailureReasonForAutopilotRun(task db.AgentTaskQueue) string {
// DispatchAutopilot up the stack and the failure-vs-skip distinction is
// owned by the dispatcher entry point. Keeps dispatchRunOnly free of
// state-mutation helpers.
-func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, err error) *db.AutopilotRun {
+func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, err error) (*db.AutopilotRun, dispatch.ReasonCode) {
var skipErr *errDispatchSkipped
if !errors.As(err, &skipErr) {
- return nil
+ return nil, ""
}
updated, uerr := s.Queries.UpdateAutopilotRunSkipped(ctx, db.UpdateAutopilotRunSkippedParams{
ID: run.ID,
@@ -990,7 +1131,7 @@ func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopil
// Leave the run in its current (running/issue_created) state if
// the update failed; the failure monitor will eventually fail it
// out, but at least we didn't pretend it succeeded.
- return nil
+ return nil, ""
}
*run = updated
slog.Info("autopilot dispatch skipped post-admission",
@@ -1004,7 +1145,7 @@ func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopil
// caught a late readiness regression.
s.Queries.UpdateAutopilotLastRunAt(ctx, ap.ID)
s.publishRunDone(util.UUIDToString(ap.WorkspaceID), updated, "skipped")
- return run
+ return run, skipErr.code
}
func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reason string) {
@@ -1031,9 +1172,9 @@ func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reaso
// scheduled run. Migration 096 removed the agent FK on autopilot, so an
// agent assignee being missing is now a real condition the gate must
// handle (previously cascade-deleted).
-func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopilot) (string, bool) {
+func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopilot, actorUserID pgtype.UUID) (string, dispatch.ReasonCode, bool) {
if !ap.AssigneeID.Valid {
- return "autopilot has no assignee", true
+ return "autopilot has no assignee", dispatch.ReasonTargetUnavailable, true
}
agent, squadResolved, err := s.resolveAutopilotLeader(ctx, ap)
if err != nil {
@@ -1056,18 +1197,18 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
// should have rewritten this autopilot's assignee to the leader
// already; surfacing the case explicitly keeps the failure
// reason useful when something slipped past the transfer.
- return "assignee squad is archived", true
+ return "assignee squad is archived", dispatch.ReasonTargetUnavailable, true
case missing && squadResolved:
- return "assignee squad cannot be resolved", true
+ return "assignee squad cannot be resolved", dispatch.ReasonTargetUnavailable, true
case missing && !squadResolved:
// Agent row gone. With migration 096 the FK is gone too, so
// this is the new "agent was hard-deleted under us" case. Skip
// rather than fail-open: we know retrying will not help.
- return "assignee agent no longer exists", true
+ return "assignee agent no longer exists", dispatch.ReasonTargetUnavailable, true
}
// Transient DB error — fail-open so the next scheduler tick gets a
// chance to succeed.
- return "", false
+ return "", "", false
}
ready, reason, err := AgentReadiness(ctx, s.Queries, agent)
if err != nil {
@@ -1076,7 +1217,7 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
"runtime_id", util.UUIDToString(agent.RuntimeID),
"error", err,
)
- return "", false
+ return "", "", false
}
if !ready {
if ap.ExecutionMode == "create_issue" && strings.HasPrefix(reason, "agent runtime is ") {
@@ -1086,19 +1227,36 @@ func (s *AutopilotService) shouldSkipDispatch(ctx context.Context, ap db.Autopil
"reason", reason,
)
} else {
- return formatAdmissionReason(ap, reason), true
+ return formatAdmissionReason(ap, reason), agentReadinessReasonCode(agent), true
}
}
- // Invocation gate at the autopilot layer (MUL-3963). Effective user = the
- // autopilot's creator: if the creator may not invoke the target agent
- // under the permission model, the dispatch is recorded as `skipped`.
- // Admins do NOT bypass a private agent they do not own; agent-created
- // autopilots are judged as workspace principals. For squad autopilots the
- // gate runs against the resolved leader.
- if !s.canCreatorInvokeAgent(ctx, ap, agent) {
- return "autopilot creator lacks access to private assignee agent", true
+ // Invocation gate at the autopilot layer (MUL-3963 / MUL-4525). The
+ // admission principal depends on how the dispatch was triggered: a MANUAL
+ // "run now" (actorUserID valid) is a direct human action gated by the
+ // current CLICKER's access — not the autopilot creator's — so admission and
+ // attribution credit the same member and never fork. Automation (schedule /
+ // webhook / api, actorUserID invalid) has no human in the loop and falls
+ // back to the creator. Admins do NOT bypass a private agent they do not own;
+ // agent-created autopilots are judged as workspace principals. For squad
+ // autopilots the gate runs against the resolved leader.
+ if !s.autopilotAdmitInvoke(ctx, ap, agent, actorUserID) {
+ if actorUserID.Valid {
+ return "you are not allowed to trigger this autopilot's assignee agent", dispatch.ReasonInvocationNotAllowed, true
+ }
+ return "autopilot creator lacks access to private assignee agent", dispatch.ReasonInvocationNotAllowed, true
}
- return "", false
+ return "", "", false
+}
+
+// agentReadinessReasonCode types the reason an AgentReadiness check failed from
+// the agent's own state rather than the human-readable reason string (MUL-4525).
+// An archived agent cannot run at all; anything else (no runtime bound, or a
+// bound runtime that is not online) is a runtime-availability problem.
+func agentReadinessReasonCode(agent db.Agent) dispatch.ReasonCode {
+ if agent.ArchivedAt.Valid {
+ return dispatch.ReasonTargetUnavailable
+ }
+ return dispatch.ReasonRuntimeOffline
}
// formatAdmissionReason rewrites the generic AgentReadiness reason into the
@@ -1590,6 +1748,61 @@ func (s *AutopilotService) getIssuePrefix(workspaceID pgtype.UUID) string {
// admits the matching creator; team targets are inert.
//
// Fail-closed on any lookup error.
+// autopilotAdmitInvoke decides whether the dispatch's admission principal may
+// invoke the target agent (MUL-4525). A MANUAL "run now" (actorUserID valid) is
+// a direct human action gated by the CURRENT clicker's access, so admission and
+// attribution credit the same member. Automation (schedule / webhook / api,
+// actorUserID invalid) has no human in the loop and falls back to the autopilot
+// creator. Both branches fail closed and never grant an admin bypass.
+func (s *AutopilotService) autopilotAdmitInvoke(ctx context.Context, ap db.Autopilot, agent db.Agent, actorUserID pgtype.UUID) bool {
+ if actorUserID.Valid {
+ return s.canMemberInvokeAgent(ctx, agent, actorUserID, ap.WorkspaceID)
+ }
+ return s.canCreatorInvokeAgent(ctx, ap, agent)
+}
+
+// canMemberInvokeAgent checks whether a specific member may invoke the agent
+// under the invocation-permission model (MUL-3963). It mirrors
+// handler.canInvokeAgent with a member effective user — used for a manual
+// autopilot "run now" where the clicker, not the creator, is the admission
+// principal. Fail-closed on any lookup error; no admin bypass.
+func (s *AutopilotService) canMemberInvokeAgent(ctx context.Context, agent db.Agent, memberUserID pgtype.UUID, workspaceID pgtype.UUID) bool {
+ userID := util.UUIDToString(memberUserID)
+ if userID == "" {
+ return false
+ }
+ if util.UUIDToString(agent.OwnerID) == userID {
+ return true
+ }
+ if agent.PermissionMode != "public_to" {
+ return false
+ }
+ targets, err := s.Queries.ListAgentInvocationTargets(ctx, agent.ID)
+ if err != nil {
+ return false
+ }
+ isWorkspaceMember := false
+ if _, err := s.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: memberUserID,
+ WorkspaceID: workspaceID,
+ }); err == nil {
+ isWorkspaceMember = true
+ }
+ for _, t := range targets {
+ switch t.TargetType {
+ case "workspace":
+ if isWorkspaceMember {
+ return true
+ }
+ case "member":
+ if util.UUIDToString(t.TargetID) == userID {
+ return true
+ }
+ }
+ }
+ return false
+}
+
func (s *AutopilotService) canCreatorInvokeAgent(ctx context.Context, ap db.Autopilot, agent db.Agent) bool {
creatorID := util.UUIDToString(ap.CreatedByID)
if ap.CreatedByType == "member" && util.UUIDToString(agent.OwnerID) == creatorID {
diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.go
new file mode 100644
index 0000000000..05b0c3afdf
--- /dev/null
+++ b/server/internal/service/reason_code_test.go
@@ -0,0 +1,53 @@
+package service
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/dispatch"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestDispatchFailReasonCode is the regression for Elon must-fix 2, case 1: a
+// dispatch that fails fail-closed on attribution must be classified
+// attribution_blocked, not internal_error — decided by a TYPED errors.Is check,
+// not by substring-matching an English message.
+func TestDispatchFailReasonCode(t *testing.T) {
+ if got := dispatchFailReasonCode(ErrAttributionFailClosed); got != dispatch.ReasonAttributionBlocked {
+ t.Errorf("bare fail-closed: got %q, want attribution_blocked", got)
+ }
+ // The real dispatch path wraps the sentinel (create_issue enqueue → %w);
+ // errors.Is must still see through the wrap.
+ wrapped := fmt.Errorf("dispatch create_issue: enqueue task for issue: %w", ErrAttributionFailClosed)
+ if got := dispatchFailReasonCode(wrapped); got != dispatch.ReasonAttributionBlocked {
+ t.Errorf("wrapped fail-closed: got %q, want attribution_blocked", got)
+ }
+ if got := dispatchFailReasonCode(errors.New("some other failure")); got != dispatch.ReasonInternalError {
+ t.Errorf("generic error: got %q, want internal_error", got)
+ }
+}
+
+// TestAgentReadinessReasonCode is the regression for Elon must-fix 2, case 2: a
+// runtime-availability failure (no runtime bound, or a bound-but-offline
+// runtime) must map to runtime_offline, and an archived agent to
+// target_unavailable — decided from the agent's own state, not the reason text.
+func TestAgentReadinessReasonCode(t *testing.T) {
+ validRuntime := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
+ archivedAt := pgtype.Timestamptz{Valid: true}
+
+ // No runtime bound (the "agent has no runtime bound" case that previously
+ // fell through the substring classifier to generic).
+ if got := agentReadinessReasonCode(db.Agent{}); got != dispatch.ReasonRuntimeOffline {
+ t.Errorf("no runtime bound: got %q, want runtime_offline", got)
+ }
+ // Bound runtime that is offline at dispatch time.
+ if got := agentReadinessReasonCode(db.Agent{RuntimeID: validRuntime}); got != dispatch.ReasonRuntimeOffline {
+ t.Errorf("bound offline runtime: got %q, want runtime_offline", got)
+ }
+ // Archived agent cannot run at all.
+ if got := agentReadinessReasonCode(db.Agent{ArchivedAt: archivedAt, RuntimeID: validRuntime}); got != dispatch.ReasonTargetUnavailable {
+ t.Errorf("archived agent: got %q, want target_unavailable", got)
+ }
+}
diff --git a/server/internal/service/resolve_originator_test.go b/server/internal/service/resolve_originator_test.go
index 28e9d87415..490a8982e1 100644
--- a/server/internal/service/resolve_originator_test.go
+++ b/server/internal/service/resolve_originator_test.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/runtimeapps"
@@ -196,9 +197,9 @@ func seedOriginatorFanout(t *testing.T, pool *pgxpool.Pool) (memberCommentID, ag
// row the resolver must follow back through comment.source_task_id.
if err := pool.QueryRow(ctx, `
INSERT INTO agent_task_queue (
- agent_id, runtime_id, issue_id, status, priority, originator_user_id
+ agent_id, runtime_id, issue_id, status, priority, originator_user_id, accountable_user_id
)
- VALUES ($1, $2, $3, 'completed', 0, $4)
+ VALUES ($1, $2, $3, 'completed', 0, $4, $4)
RETURNING id
`, agentAID, runtimeID, issueID, userIDStr).Scan(&taskAIDStr); err != nil {
t.Fatalf("seed task A: %v", err)
@@ -269,6 +270,62 @@ func TestResolveOriginatorFromTriggerComment_AgentAuthoredInheritsFromParent(t *
}
}
+// TestAttributionForIssueTask_SystemCommentFallsThroughToIssueProvenance covers
+// the Stage-completion cascade (MUL-4302; raised by Bohan). Closing the last
+// sub-issue in a Stage wakes the parent's assignee agent through a SYSTEM-authored
+// child-done comment that threads no actor. That system comment carries no human,
+// so attribution must NOT stop at it (which would degrade to owner_fallback, the
+// agent's own owner) — it must fall through to the PARENT issue's own provenance
+// and attribute to the human who caused the parent issue to exist. Here the parent
+// was created by an agent on behalf of userID (agent_create origin), so the woken
+// run is delegation-accountable to userID.
+func TestAttributionForIssueTask_SystemCommentFallsThroughToIssueProvenance(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ _, _, parentTaskID, userID, _ := seedOriginatorFanout(t, pool)
+ ctx := context.Background()
+
+ // Plant a system-authored comment on the seed's issue (mirrors the child-done
+ // comment). Its issue/workspace are derived from the origin task's issue.
+ var issueIDStr, workspaceIDStr string
+ if err := pool.QueryRow(ctx, `
+ SELECT i.id::text, i.workspace_id::text
+ FROM agent_task_queue t JOIN issue i ON i.id = t.issue_id
+ WHERE t.id = $1
+ `, util.UUIDToString(parentTaskID)).Scan(&issueIDStr, &workspaceIDStr); err != nil {
+ t.Fatalf("load issue/workspace: %v", err)
+ }
+ var systemCommentIDStr string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'system', '00000000-0000-0000-0000-000000000000', 'child done', 'system')
+ RETURNING id
+ `, issueIDStr, workspaceIDStr).Scan(&systemCommentIDStr); err != nil {
+ t.Fatalf("seed system comment: %v", err)
+ }
+ systemCommentID := util.MustParseUUID(systemCommentIDStr)
+
+ svc := &TaskService{Queries: db.New(pool)}
+ // Parent issue created by an agent on behalf of userID (agent_create origin).
+ // WorkspaceID is set so the workspace-scoped trigger-comment lookup (MUL-4252)
+ // finds the system comment and classifies it (author_type=system) before the
+ // fall-through to issue provenance.
+ issue := db.Issue{
+ CreatorType: "agent",
+ OriginType: pgtype.Text{String: "agent_create", Valid: true},
+ OriginID: parentTaskID,
+ WorkspaceID: util.MustParseUUID(workspaceIDStr),
+ }
+
+ got := svc.attributionForIssueTask(ctx, issue, systemCommentID, attribution.SourceDelegation, pgtype.UUID{})
+ if got.Source != attribution.SourceDelegation {
+ t.Fatalf("source = %q, want delegation (system comment must fall through to issue provenance, not owner_fallback)", got.Source)
+ }
+ if !got.UserID.Valid || got.UserID.Bytes != userID.Bytes {
+ t.Errorf("accountable = %s, want %s (the human who caused the parent issue to exist)",
+ util.UUIDToString(got.UserID), util.UUIDToString(userID))
+ }
+}
+
// TestResolveOriginatorForIssueTask_MemberCreatedNoComment covers direct issue
// assignment/creation: there is no trigger comment to inspect, but the issue's
// human creator is still the run originator for Composio overlay gating.
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 1d65424673..de320b2bba 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -14,6 +14,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflags"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
@@ -161,6 +162,32 @@ func (s *TaskService) ResolveOriginatorFromTriggerComment(ctx context.Context, w
return s.resolveOriginatorFromTriggerComment(ctx, workspaceID, commentID)
}
+// AttributionForMergedComment resolves the FULL attribution snapshot for a comment
+// being coalesced into an already-queued task (MUL-4302). A merge re-attributes the
+// run to the newly-arrived comment's human, so the whole snapshot — source, evidence,
+// delegation lineage, and both person columns — must move together as one
+// attribution.Result; re-stamping only the person columns would leave a run showing
+// B accountable while still pointing at A's stale source / evidence / level. isMention
+// picks the agent-authored label (delegation for a mention / thread-parent, otherwise
+// comment_source), matching the fresh-enqueue routing.
+//
+// The merge re-opens the same fail-closed decision the original enqueue faced: a merge
+// swaps the effective trigger, responsible human, and evidence to the NEW comment, so
+// "the enqueue already checked" does not carry over. It runs the comment through
+// applyAttributionFallback — the identical fail-closed gate the fresh-enqueue path uses
+// — and returns ErrAttributionFailClosed when the new comment cannot be attributed
+// precisely and the workspace forbids the owner_fallback degrade. The caller must then
+// REFUSE the merge and keep the original (precisely-attributed) task snapshot rather
+// than re-stamp a queued run to a degraded owner_fallback (Elon must-fix).
+func (s *TaskService) AttributionForMergedComment(ctx context.Context, workspaceID, commentID pgtype.UUID, isMention bool, agent db.Agent) (attribution.Result, error) {
+ agentAuthoredSource := attribution.SourceCommentSource
+ if isMention {
+ agentAuthoredSource = attribution.SourceDelegation
+ }
+ attr := s.attributionFromTriggerComment(ctx, workspaceID, commentID, agentAuthoredSource)
+ return s.applyAttributionFallback(ctx, attr, agent)
+}
+
// BuildCommentTriggerSummary is the exported wrapper used by the comment-merge
// path (MUL-4195) to refresh a coalesced task's trigger_summary to the newest
// trigger comment's snapshot. workspaceID scopes the lookup (MUL-4252).
@@ -283,38 +310,60 @@ func (s *TaskService) buildRuntimeMCPOverlay(ctx context.Context, originatorUser
// to the task's workspace so a foreign comment UUID cannot resolve an
// originator from another tenant (MUL-4252).
func (s *TaskService) resolveOriginatorFromTriggerComment(ctx context.Context, workspaceID, commentID pgtype.UUID) pgtype.UUID {
- if s == nil || s.Queries == nil {
- return pgtype.UUID{}
- }
- if !commentID.Valid {
- return pgtype.UUID{}
+ // The originator VALUE is independent of the agent-authored source label, so
+ // any label works here; comment_source is passed only as a placeholder.
+ return s.attributionFromTriggerComment(ctx, workspaceID, commentID, attribution.SourceCommentSource).UserID
+}
+
+// attributionFromTriggerComment resolves the full attribution (accountable
+// human + provenance label + delegation lineage + evidence) for a
+// comment-triggered run. It performs the DB reads and hands the gathered facts
+// to the pure attribution.ClassifyComment rules so the classification stays
+// side-effect-free and unit-tested. The returned UserID is byte-identical to
+// the pre-MUL-4302 originator resolution, so authorization behavior (Composio
+// overlay, canInvokeAgent A2A gate) is unchanged. workspaceID scopes the comment
+// lookup to the task's workspace (MUL-4252).
+//
+// agentAuthoredSource selects the label for an agent-authored trigger comment:
+// attribution.SourceCommentSource for the issue-assignee-reacting path,
+// attribution.SourceDelegation for an explicit mention / thread-parent /
+// squad-leader path.
+func (s *TaskService) attributionFromTriggerComment(ctx context.Context, workspaceID, commentID pgtype.UUID, agentAuthoredSource attribution.Source) attribution.Result {
+ if s == nil || s.Queries == nil || !commentID.Valid {
+ return attribution.Result{Source: attribution.SourceUnattributed}
}
comment, err := s.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{
ID: commentID,
WorkspaceID: workspaceID,
})
if err != nil {
- return pgtype.UUID{}
- }
- switch comment.AuthorType {
- case "member":
- return comment.AuthorID
- case "agent":
- // Inherit from the agent's own triggering task. comment.source_task_id
- // is set by every agent comment-write path (see migration 120), so a
- // NULL here means either the comment predates that migration or it
- // was authored out-of-band — both fall through to "no overlay".
- if !comment.SourceTaskID.Valid {
- return pgtype.UUID{}
- }
- parent, err := s.Queries.GetAgentTask(ctx, comment.SourceTaskID)
- if err != nil {
- return pgtype.UUID{}
+ return attribution.Result{Source: attribution.SourceUnattributed}
+ }
+ return s.attributionFromComment(ctx, comment, agentAuthoredSource)
+}
+
+// attributionFromComment classifies a run from an already-loaded trigger comment,
+// so a caller that already has the row (e.g. to inspect author_type) does not
+// re-read it. Kept byte-identical to the inline logic attributionFromTriggerComment
+// used before, so authorization behavior is unchanged.
+func (s *TaskService) attributionFromComment(ctx context.Context, comment db.Comment, agentAuthoredSource attribution.Source) attribution.Result {
+ facts := attribution.CommentFacts{
+ CommentID: comment.ID,
+ AuthorType: comment.AuthorType,
+ AuthorID: comment.AuthorID,
+ }
+ // For an agent-authored comment, walk comment.source_task_id → parent task →
+ // parent.originator_user_id (set by every agent comment-write path since
+ // migration 120). A NULL/missing source task leaves ParentOriginator
+ // invalid, which ClassifyComment maps to unattributed.
+ if comment.AuthorType == "agent" && comment.SourceTaskID.Valid {
+ facts.SourceTaskID = comment.SourceTaskID
+ if parent, err := s.Queries.GetAgentTask(ctx, comment.SourceTaskID); err == nil {
+ facts.ParentOriginator = parent.OriginatorUserID
+ facts.ParentAccountable = parent.AccountableUserID
}
- return parent.OriginatorUserID
- default:
- return pgtype.UUID{}
}
+ return attribution.ClassifyComment(facts, agentAuthoredSource)
}
// resolveOriginatorForIssueTask returns the top-of-chain human for issue-backed
@@ -326,27 +375,208 @@ func (s *TaskService) resolveOriginatorFromTriggerComment(ctx context.Context, w
// points at the agent_task_queue row that created the issue. Other
// agent/system origins, including autopilot, deliberately remain unattributed.
func (s *TaskService) resolveOriginatorForIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID) pgtype.UUID {
+ return s.attributionForIssueTask(ctx, issue, triggerCommentID, attribution.SourceCommentSource, pgtype.UUID{}).UserID
+}
+
+// attributionForIssueTask resolves the full attribution for an issue-backed
+// enqueue. Comment-triggered runs keep the comment-chain semantics; direct
+// assignment/creation falls back to the issue's member creator; agent-created
+// quick-create issues inherit the origin task's human as a delegation. The
+// accountable-human value is byte-identical to resolveOriginatorForIssueTask,
+// which now delegates here — so there is a single source of truth and
+// authorization is unaffected. agentAuthoredSource labels the agent-authored
+// trigger comment case (see attributionFromTriggerComment).
+func (s *TaskService) attributionForIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, agentAuthoredSource attribution.Source, actorUserID pgtype.UUID) attribution.Result {
+ // A direct member action is the accountable human AND originator, ahead of any
+ // trigger comment, origin, or rule (MUL-4302 §4/§5). This covers assign/promote,
+ // a manual autopilot trigger, and a manual rerun — the last of which may INHERIT
+ // a triggerCommentID for the daemon's prompt context, but must still attribute to
+ // the member who clicked rerun, not the original comment's human. So the actor is
+ // checked before the trigger-comment / origin branches.
+ if actorUserID.Valid {
+ return attribution.ClassifyDirect(attribution.DirectFacts{IssueID: issue.ID, ActorUserID: actorUserID})
+ }
if triggerCommentID.Valid {
- return s.resolveOriginatorFromTriggerComment(ctx, issue.WorkspaceID, triggerCommentID)
+ if s == nil || s.Queries == nil {
+ return attribution.Result{Source: attribution.SourceUnattributed}
+ }
+ // workspace-scoped so a foreign comment UUID cannot resolve a human from
+ // another tenant (MUL-4252).
+ comment, err := s.Queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{
+ ID: triggerCommentID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ return attribution.Result{Source: attribution.SourceUnattributed}
+ }
+ // A member/agent trigger comment resolves the human (direct_human / delegation
+ // / comment_source). A SYSTEM-authored comment — today the Stage-completion
+ // child-done comment (issue_child_done.go), which wakes the parent assignee
+ // and threads no actor — carries no human and is not part of any delegation
+ // chain. Classifying it would degrade straight to owner_fallback (the agent's
+ // own owner), which is wrong for a Stage cascade: the woken run should be
+ // accountable to whoever caused the PARENT issue to exist. So for a system
+ // comment we skip the comment branch and fall through to the parent issue's
+ // own provenance below — the same creator / agent_create-origin /
+ // autopilot-origin chain a direct enqueue resolves — reaching owner_fallback
+ // only if that provenance itself has no human (MUL-4302; raised by Bohan on
+ // the stage-cascade fallback).
+ if comment.AuthorType != "system" {
+ return s.attributionFromComment(ctx, comment, agentAuthoredSource)
+ }
}
- if issue.CreatorType == "member" && issue.CreatorID.Valid {
- return issue.CreatorID
+ // Autopilot-origin issues (origin_id is the autopilot id) from a schedule /
+ // webhook trigger: no human authorized the run, so originator stays NULL, but it
+ // is accountable to the human currently RESPONSIBLE for the firing trigger's
+ // effective config (creator, then last substantive editor) — trigger_owner
+ // (MUL-4302; Elon must-fix), degrading to the rule publisher when no such member
+ // is recoverable. Resolved the same way run_only dispatch resolves
+ // it, so both autopilot execution modes attribute identically. (A manual trigger
+ // carries an actor and is already handled above.) The issue only stores the
+ // autopilot id, so bridge issue → active run → trigger_id to find the trigger.
+ if s != nil && s.Queries != nil && issue.OriginType.Valid &&
+ issue.OriginType.String == "autopilot" && issue.OriginID.Valid {
+ var triggerID pgtype.UUID
+ if run, err := s.Queries.GetAutopilotRunByIssue(ctx, issue.ID); err == nil {
+ triggerID = run.TriggerID
+ }
+ return triggerOwnerAttribution(ctx, s.Queries, triggerID, issue.WorkspaceID, issue.OriginID, attribution.EvidenceIssueAssignment, issue.ID)
+ }
+ facts := attribution.DirectFacts{
+ IssueID: issue.ID,
+ CreatorType: issue.CreatorType,
+ CreatorID: issue.CreatorID,
+ }
+ // Member-created issues resolve without a DB read. Only origin-linked
+ // agent-created issues (quick_create, agent_create) need to load the origin
+ // task to inherit its human, and only when the DB is wired (nil Queries keeps
+ // unit-test setups safe and yields unattributed). Both origin types stamp
+ // origin_id with the agent_task_queue row that created the issue, so the
+ // top-of-chain human is that task's originator_user_id (MUL-4305).
+ if !(issue.CreatorType == "member" && issue.CreatorID.Valid) &&
+ s != nil && s.Queries != nil && issue.OriginType.Valid && issue.OriginID.Valid &&
+ (issue.OriginType.String == "quick_create" || issue.OriginType.String == "agent_create") {
+ facts.OriginType = issue.OriginType.String
+ facts.OriginTaskID = issue.OriginID
+ if task, err := s.Queries.GetAgentTask(ctx, issue.OriginID); err == nil {
+ facts.OriginOriginator = task.OriginatorUserID
+ facts.OriginAccountable = task.AccountableUserID
+ }
}
- if s == nil || s.Queries == nil || !issue.OriginType.Valid || !issue.OriginID.Valid {
- return pgtype.UUID{}
+ return attribution.ClassifyDirect(facts)
+}
+
+// ruleOwnerAttribution resolves the rule_owner attribution for an autopilot run
+// from its active (latest) rule version snapshot (MUL-4302 §3.4). Shared by both
+// autopilot execution modes — run_only dispatch and the create_issue enqueue path —
+// so they attribute identically. originator stays NULL (an autopilot carries no
+// human's authority); only the audit-accountable side is set, to the version's
+// member publisher. A missing version (autopilot published before this feature, or
+// none yet) or a non-member/absent publisher degrades to unattributed rather than
+// fabricating a human. Never returns an error: attribution must not fail an
+// enqueue, and a degraded label is the honest fallback.
+func ruleOwnerAttribution(ctx context.Context, q *db.Queries, workspaceID, autopilotID pgtype.UUID, evidenceKind attribution.EvidenceKind, evidenceRefID pgtype.UUID) attribution.Result {
+ if q == nil || !autopilotID.Valid {
+ return attribution.RuleOwner(pgtype.UUID{}, pgtype.UUID{}, evidenceKind, evidenceRefID)
+ }
+ ver, err := q.GetActiveAutopilotRuleVersion(ctx, db.GetActiveAutopilotRuleVersionParams{
+ WorkspaceID: workspaceID,
+ AutopilotID: autopilotID,
+ })
+ if err != nil {
+ return attribution.RuleOwner(pgtype.UUID{}, pgtype.UUID{}, evidenceKind, evidenceRefID)
}
- switch issue.OriginType.String {
- case "quick_create", "agent_create":
- // Both stamp origin_id with the agent_task_queue row that created the
- // issue, so the top-of-chain human is that task's originator_user_id.
- task, err := s.Queries.GetAgentTask(ctx, issue.OriginID)
- if err != nil {
- return pgtype.UUID{}
+ var publisher pgtype.UUID
+ if ver.PublishedByType == "member" {
+ publisher = ver.PublishedByID
+ }
+ return attribution.RuleOwner(publisher, ver.ID, evidenceKind, evidenceRefID)
+}
+
+// triggerOwnerAttribution resolves an autopilot schedule/webhook run to the human
+// currently RESPONSIBLE for the firing trigger's effective config (MUL-4302; Bohan +
+// Elon must-fix). triggerID is the autopilot_run's trigger_id. The trigger row's
+// published_by starts at the creator and transfers to whoever later substantively
+// edits it, so the run attributes to whoever last shaped what fires it — not the
+// original creator. A trigger with no recorded publisher (predating this migration)
+// or an agent publisher degrades to ruleOwnerAttribution (rule publisher, then
+// owner_fallback) — the same coarser behavior autopilots had before, so nothing
+// regresses. Never errors: attribution must not fail an enqueue.
+func triggerOwnerAttribution(ctx context.Context, q *db.Queries, triggerID, workspaceID, autopilotID pgtype.UUID, evidenceKind attribution.EvidenceKind, evidenceRefID pgtype.UUID) attribution.Result {
+ if q != nil && triggerID.Valid {
+ // published_by is the member CURRENTLY responsible for this trigger's
+ // effective config: the creator until someone substantively edits it (that
+ // trigger's cron/filter/webhook, or an autopilot-level change that bumps all
+ // its triggers), then the editor. So a run attributes to whoever last shaped
+ // what fires it, not the original creator — and editing another trigger never
+ // moves this one (MUL-4302; Elon must-fix).
+ if trig, err := q.GetAutopilotTrigger(ctx, triggerID); err == nil &&
+ trig.PublishedByType.Valid && trig.PublishedByType.String == "member" && trig.PublishedByID.Valid {
+ return attribution.TriggerOwner(trig.PublishedByID, evidenceKind, evidenceRefID)
}
- return task.OriginatorUserID
- default:
- return pgtype.UUID{}
}
+ return ruleOwnerAttribution(ctx, q, workspaceID, autopilotID, evidenceKind, evidenceRefID)
+}
+
+// ErrAttributionFailClosed signals that a run resolved to no precise accountable
+// human and the enqueue is REFUSED rather than started. It covers three cases, all
+// of which mean "we cannot guarantee an accountable human for this run" (MUL-4302
+// §1/§3.5): the workspace opted into fail-closed; the workspace policy could not be
+// read (so we cannot confirm fallback is allowed — fail closed, don't run); or
+// owner_fallback has no agent owner to fall back to. Enqueue paths surface it so the
+// run never starts.
+var ErrAttributionFailClosed = errors.New("attribution: no precise accountable human and enqueue refused (fail-closed policy, policy read failed, or no agent owner)")
+
+// applyAttributionFallback applies the workspace's degraded-attribution policy to a
+// resolved attribution whose source came back unattributed (no precise human). A
+// PRECISE attribution passes through untouched (no policy read at all). For an
+// unattributed run the accountable-never-null guarantee is enforced fail-closed —
+// we never silently enqueue a task that could run with a NULL accountable_user_id:
+//
+// - policy read fails (or no workspace) → REFUSE. We cannot confirm the workspace
+// permits fallback, so we do not run an unattributable task on a transient DB
+// hiccup. (Only the rare unattributed path pays this; precise runs never read.)
+// - fail-closed workspace → REFUSE.
+// - otherwise → owner_fallback (accountable = agent owner, audit-only, originator
+// untouched). If there is no valid agent owner, owner_fallback stays
+// unattributed → REFUSE rather than enqueue a NULL-accountable task.
+//
+// Keeping this at the enqueue boundary (not inside the pure classifiers) means
+// owner_fallback needs the agent owner, which every enqueue path has in hand.
+func (s *TaskService) applyAttributionFallback(ctx context.Context, attr attribution.Result, agent db.Agent) (attribution.Result, error) {
+ if attr.Source != attribution.SourceUnattributed {
+ return attr, nil
+ }
+ if s == nil || s.Queries == nil || !agent.WorkspaceID.Valid {
+ return attr, fmt.Errorf("%w: workspace policy unavailable", ErrAttributionFailClosed)
+ }
+ failClosed, err := s.Queries.GetWorkspaceAttributionFailClosed(ctx, agent.WorkspaceID)
+ if err != nil {
+ // Cannot confirm the workspace allows fallback → fail closed rather than
+ // silently run an unattributable task.
+ return attr, fmt.Errorf("%w: policy read failed: %v", ErrAttributionFailClosed, err)
+ }
+ if failClosed {
+ return attr, ErrAttributionFailClosed
+ }
+ fallback := attribution.OwnerFallback(attr, agent.OwnerID)
+ if fallback.Source == attribution.SourceUnattributed {
+ // owner_fallback could not resolve an accountable human (no valid agent
+ // owner): refuse rather than enqueue a NULL-accountable task.
+ return attr, fmt.Errorf("%w: no agent owner to attribute", ErrAttributionFailClosed)
+ }
+ return fallback, nil
+}
+
+// attributionCreateParams maps a resolved attribution onto the CreateAgentTask
+// provenance columns. originator_source is always stamped (never NULL for a new
+// row); delegation lineage and evidence are stamped only when present.
+func attributionCreateParams(attr attribution.Result) (source pgtype.Text, delegatedFrom pgtype.UUID, evidenceKind pgtype.Text, evidenceRef pgtype.UUID) {
+ source = pgtype.Text{String: attr.Source.String(), Valid: true}
+ delegatedFrom = attr.DelegatedFromTaskID
+ evidenceKind = pgtype.Text{String: string(attr.EvidenceKind), Valid: attr.EvidenceKind != ""}
+ evidenceRef = attr.EvidenceRefID
+ return
}
// OriginatorForIssueTask exposes resolveOriginatorForIssueTask to callers
@@ -653,15 +883,17 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t
if len(triggerCommentID) > 0 {
commentID = triggerCommentID[0]
}
- return s.enqueueIssueTask(ctx, issue, commentID, false, "")
+ return s.enqueueIssueTask(ctx, issue, commentID, false, "", pgtype.UUID{}, pgtype.UUID{})
}
// EnqueueTaskForIssueWithHandoff is the assign/promote variant that carries a
// handoff note into the run's opening context (MUL-3375). The note rides a
// dedicated task column; the daemon renders it via the assignment-handoff
-// branch. Empty note behaves exactly like EnqueueTaskForIssue.
-func (s *TaskService) EnqueueTaskForIssueWithHandoff(ctx context.Context, issue db.Issue, handoffNote string) (db.AgentTaskQueue, error) {
- return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote)
+// branch. Empty note behaves exactly like EnqueueTaskForIssue. actorUserID is the
+// member who performed the assign/promote and becomes the accountable human for
+// the run (MUL-4302 §4); invalid when the caller has no member actor.
+func (s *TaskService) EnqueueTaskForIssueWithHandoff(ctx context.Context, issue db.Issue, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote, actorUserID, pgtype.UUID{})
}
// enqueueIssueTask is the shared implementation behind EnqueueTaskForIssue
@@ -709,11 +941,11 @@ func (s *TaskService) ResolveIssueReviewSHAParam(ctx context.Context, issueID pg
return headShaText(s.ResolveIssueReviewSHA(ctx, issueID))
}
-func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote)
+func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID)
}
-func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
if !issue.AssigneeID.Valid {
slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")
return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")
@@ -733,8 +965,22 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")
}
- originatorUserID := s.resolveOriginatorForIssueTask(ctx, issue, triggerCommentID)
+ // The issue assignee reacting to an agent-authored comment is a
+ // comment_source attribution (a special case of delegation); a member
+ // comment or direct member assignment is direct_human. attr.UserID is the
+ // same value the pre-MUL-4302 resolver produced, so overlay/authorization
+ // are unchanged; the extra fields are audit provenance.
+ attr := s.attributionForIssueTask(ctx, issue, triggerCommentID, attribution.SourceCommentSource, actorUserID)
+ // No precise human resolved → owner_fallback (accountable = agent owner), or
+ // refuse the enqueue if the workspace is fail-closed (MUL-4302 §3.5).
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ slog.Warn("task enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(issue.AssigneeID))
+ return db.AgentTaskQueue{}, err
+ }
+ originatorUserID := attr.UserID
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)
+ attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{
AgentID: issue.AssigneeID,
RuntimeID: agent.RuntimeID,
@@ -746,8 +992,15 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: forceFreshSession},
HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
OriginatorUserID: originatorUserID,
+ AccountableUserID: attr.AccountableUserID,
+ RuleVersionID: attr.RuleVersionID,
+ RerunOfTaskID: rerunOfTaskID,
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ DelegatedFromTaskID: attrDelegatedFrom,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
// Stamp the reviewed head so dedup can distinguish this run's target
// from a later request against a new HEAD (TEN-356).
HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),
@@ -778,13 +1031,13 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue
// Unlike EnqueueTaskForIssue, this takes an explicit agent ID rather than
// deriving it from the issue assignee.
func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "")
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{})
}
// EnqueueTaskForThreadParent creates a queued task for the agent who authored
// the direct parent comment a member replied to.
func (s *TaskService) EnqueueTaskForThreadParent(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "")
+ return s.enqueueMentionTask(ctx, issue, agentID, triggerCommentID, false, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{})
}
// EnqueueTaskForSquadLeader is the leader-role variant of EnqueueTaskForMention.
@@ -799,21 +1052,23 @@ func (s *TaskService) EnqueueTaskForThreadParent(ctx context.Context, issue db.I
// leader task was triggered (comment @squad, issue assign, autopilot,
// sub-issue done callback). See migration 127.
func (s *TaskService) EnqueueTaskForSquadLeader(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, triggerCommentID pgtype.UUID) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, squadID, false, "")
+ return s.enqueueMentionTask(ctx, issue, leaderID, triggerCommentID, true, squadID, false, "", pgtype.UUID{}, pgtype.UUID{})
}
// EnqueueTaskForSquadLeaderWithHandoff is the assign/promote variant carrying a
// handoff note into the leader run's opening context (MUL-3375). Empty note
-// behaves exactly like EnqueueTaskForSquadLeader.
-func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, handoffNote string) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, handoffNote)
+// behaves exactly like EnqueueTaskForSquadLeader. actorUserID is the member who
+// performed the assign/promote and becomes the accountable human (MUL-4302 §4);
+// invalid when the caller has no member actor.
+func (s *TaskService) EnqueueTaskForSquadLeaderWithHandoff(ctx context.Context, issue db.Issue, leaderID pgtype.UUID, squadID pgtype.UUID, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTask(ctx, issue, leaderID, pgtype.UUID{}, true, squadID, false, handoffNote, actorUserID, pgtype.UUID{})
}
-func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote)
+func (s *TaskService) enqueueMentionTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, nil, isLeader, squadID, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID)
}
-func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
slog.Error("mention task enqueue failed: agent not found", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -828,8 +1083,21 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, iss
return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")
}
- originatorUserID := s.resolveOriginatorForIssueTask(ctx, issue, triggerCommentID)
+ // An explicit mention / thread-parent / squad-leader hop from an
+ // agent-authored comment is a delegation (the parent task's human is
+ // copied); a member mention is direct_human. attr.UserID matches the
+ // pre-MUL-4302 value, so authorization is unchanged.
+ attr := s.attributionForIssueTask(ctx, issue, triggerCommentID, attribution.SourceDelegation, actorUserID)
+ // No precise human resolved → owner_fallback (accountable = agent owner), or
+ // refuse the enqueue if the workspace is fail-closed (MUL-4302 §3.5).
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ slog.Warn("mention task enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
+ return db.AgentTaskQueue{}, err
+ }
+ originatorUserID := attr.UserID
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)
+ attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{
AgentID: agentID,
RuntimeID: agent.RuntimeID,
@@ -843,8 +1111,15 @@ func (s *TaskService) enqueueMentionTaskWithCommentPlan(ctx context.Context, iss
HandoffNote: pgtype.Text{String: handoffNote, Valid: handoffNote != ""},
SquadID: squadID,
OriginatorUserID: originatorUserID,
+ AccountableUserID: attr.AccountableUserID,
+ RuleVersionID: attr.RuleVersionID,
+ RerunOfTaskID: rerunOfTaskID,
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ DelegatedFromTaskID: attrDelegatedFrom,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
// Stamp the reviewed head so dedup can distinguish this run's target
// from a later request against a new HEAD (TEN-356).
HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),
@@ -878,18 +1153,40 @@ func (s *TaskService) EnqueueDeferredAssigneeFallback(ctx context.Context, issue
return db.AgentTaskQueue{}, fmt.Errorf("agent has no runtime")
}
+ // The fallback assignee is reacting to the same trigger comment as the primary
+ // routed task, so resolve attribution from that comment (member author →
+ // direct_human; agent author → comment_source chain) and stamp it at creation.
+ // Promotion later only flips status, so stamping here keeps the eventual run
+ // off the NULL-source bypass (MUL-4302 §2). Overlay is intentionally left for
+ // the existing promotion path — this change is attribution-only. No direct
+ // actor here: the fallback is comment-routed, so attribution rides the comment.
+ attr := s.attributionForIssueTask(ctx, issue, triggerCommentID, attribution.SourceCommentSource, pgtype.UUID{})
+ // No precise human resolved → owner_fallback (accountable = agent owner), or
+ // refuse if the workspace is fail-closed (MUL-4302 §3.5).
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ slog.Warn("deferred fallback enqueue refused: attribution fail-closed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
+ return db.AgentTaskQueue{}, err
+ }
+ attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
isLeader := squadID.Valid
task, err := s.Queries.CreateDeferredAgentTask(ctx, db.CreateDeferredAgentTaskParams{
- AgentID: agentID,
- RuntimeID: agent.RuntimeID,
- IssueID: issue.ID,
- Priority: priorityToInt(issue.Priority),
- TriggerCommentID: triggerCommentID,
- TriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),
- IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
- SquadID: squadID,
- EscalationForTaskID: escalationForTaskID,
- FireAt: pgtype.Timestamptz{Time: fireAt, Valid: true},
+ AgentID: agentID,
+ RuntimeID: agent.RuntimeID,
+ IssueID: issue.ID,
+ Priority: priorityToInt(issue.Priority),
+ TriggerCommentID: triggerCommentID,
+ TriggerSummary: s.buildCommentTriggerSummary(ctx, issue.WorkspaceID, triggerCommentID),
+ IsLeaderTask: pgtype.Bool{Bool: isLeader, Valid: isLeader},
+ SquadID: squadID,
+ EscalationForTaskID: escalationForTaskID,
+ FireAt: pgtype.Timestamptz{Time: fireAt, Valid: true},
+ OriginatorUserID: attr.UserID,
+ AccountableUserID: attr.AccountableUserID,
+ OriginatorSource: attrSource,
+ DelegatedFromTaskID: attrDelegatedFrom,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
})
if err != nil {
slog.Error("deferred fallback enqueue failed", "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID), "error", err)
@@ -1000,6 +1297,22 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
return db.AgentTaskQueue{}, fmt.Errorf("marshal quick-create context: %w", err)
}
+ // The requester who submitted the quick-create modal is the direct_human
+ // originator and accountable. Quick-create is the ONE enqueue path with no
+ // antecedent row to point the uniform evidence pair at: the run's whole job is
+ // to CREATE the issue, so at enqueue time there is no comment / issue / session
+ // / run to reference (the issue is linked back later via LinkTaskToIssue).
+ // Evidence is therefore intentionally NULL; the accountable human is captured on
+ // originator/accountable_user_id, so this is not a NULL-source bypass — source
+ // is still stamped direct_human (MUL-4302 §2).
+ attr := attribution.DirectHumanRun(requesterID, "", pgtype.UUID{})
+ // An unresolved requester degrades to owner_fallback (accountable = agent
+ // owner), or is refused if the workspace is fail-closed (MUL-4302 §3.5).
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ return db.AgentTaskQueue{}, err
+ }
+ attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)
task, err := s.Queries.CreateQuickCreateTask(ctx, db.CreateQuickCreateTaskParams{
AgentID: agentID,
@@ -1007,8 +1320,12 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
Priority: priorityToInt("high"),
Context: contextJSON,
OriginatorUserID: requesterID,
+ AccountableUserID: attr.AccountableUserID,
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
})
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("create quick-create task: %w", err)
@@ -1086,20 +1403,39 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
return db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime
}
+ // The chat sender (initiator) is the direct_human originator and accountable.
+ // Evidence uses the uniform pair (kind=chat, ref=chat_session_id) so the
+ // attribution UI links to the conversation the same way it does for
+ // autopilot_run / issue_assignment — the dedicated chat_session_id column still
+ // exists for its own consumers. An unresolved sender (some Lark group messages)
+ // degrades to unattributed rather than a NULL-source bypass (MUL-4302 §2).
+ attr := attribution.DirectHumanRun(initiatorUserID, attribution.EvidenceChat, chatSession.ID)
+ // An unresolved sender degrades to owner_fallback (accountable = agent owner),
+ // or is refused if the workspace is fail-closed (MUL-4302 §3.5).
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ slog.Warn("chat task enqueue refused: attribution fail-closed", "chat_session_id", util.UUIDToString(chatSession.ID))
+ return db.AgentTaskQueue{}, err
+ }
+ attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)
task, err := s.Queries.CreateChatTask(ctx, db.CreateChatTaskParams{
- AgentID: chatSession.AgentID,
- RuntimeID: agent.RuntimeID,
- Priority: 2, // medium priority for chat
- ChatSessionID: chatSession.ID,
- InitiatorUserID: initiatorUserID,
- OriginatorUserID: initiatorUserID,
+ AgentID: chatSession.AgentID,
+ RuntimeID: agent.RuntimeID,
+ Priority: 2, // medium priority for chat
+ ChatSessionID: chatSession.ID,
+ InitiatorUserID: initiatorUserID,
+ OriginatorUserID: initiatorUserID,
+ AccountableUserID: attr.AccountableUserID,
ForceFreshSession: pgtype.Bool{
Bool: forceFreshSession,
Valid: true,
},
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
})
if err != nil {
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
@@ -1138,6 +1474,18 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chat
// network I/O and must not run with a DB transaction open.
overlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)
+ // Full attribution for the chat sender, resolved before the tx (the policy read
+ // + fallback must not run with a transaction open) — the same direct_human stamp
+ // EnqueueChatTask writes. Without this the direct-chat path was a bypass: it set
+ // originator_user_id but left accountable_user_id / source / evidence NULL,
+ // violating the one-way invariant and dropping the audit source (MUL-4302 §2).
+ attr := attribution.DirectHumanRun(initiatorUserID, attribution.EvidenceChat, session.ID)
+ attr, err := s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ return nil, err
+ }
+ attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
+
var out DirectChatSendResult
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
@@ -1146,10 +1494,14 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chat
Priority: 2, // medium priority for chat; matches EnqueueChatTask
ChatSessionID: session.ID,
InitiatorUserID: initiatorUserID,
- OriginatorUserID: initiatorUserID,
+ OriginatorUserID: attr.UserID,
+ AccountableUserID: attr.AccountableUserID,
ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},
RuntimeMcpOverlay: overlay.Overlay,
RuntimeConnectedApps: overlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
})
if err != nil {
return fmt.Errorf("create direct chat task: %w", err)
@@ -2803,11 +3155,24 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
// MaybeRetryFailedTask → CreateRetryTask) does NOT take this path, so
// MUL-1128's mid-flight resume contract is preserved.
//
+// ErrRerunInvokeNotAllowed signals that RerunIssue refused to rerun because the
+// current operator may not invoke the resolved target agent. The handler maps it
+// to a structured 403 (no task was cancelled or created).
+var ErrRerunInvokeNotAllowed = errors.New("rerun: operator not allowed to invoke target agent")
+
// Only tasks belonging to the target agent on this issue are cancelled.
// Tasks owned by other agents on the same issue (e.g. a parallel
// @-mention agent) are left alone — rerun must not collateral-cancel
// them.
-func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourceTaskID pgtype.UUID, triggerCommentID pgtype.UUID) (*db.AgentTaskQueue, error) {
+//
+// canInvoke re-validates that the current operator may invoke the RESOLVED
+// target agent, keyed on the historical agent for a task_id rerun and on the
+// current assignee/leader otherwise (MUL-4525). It runs AFTER the target is
+// resolved but BEFORE any prior task is cancelled or a new one is created, so a
+// caller who can see the issue but cannot invoke its private agent cannot use
+// rerun as a back door — and a blocked rerun mutates nothing. Pass nil only
+// from trusted internal callers (tests, backfill) that have already gated.
+func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourceTaskID pgtype.UUID, triggerCommentID pgtype.UUID, actorUserID pgtype.UUID, canInvoke func(agent db.Agent) bool) (*db.AgentTaskQueue, error) {
issue, err := s.Queries.GetIssue(ctx, issueID)
if err != nil {
return nil, fmt.Errorf("load issue: %w", err)
@@ -2868,6 +3233,21 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
}
}
+ // Re-validate invoke permission on the RESOLVED target before mutating
+ // anything (MUL-4525). For a task_id rerun this gates the historical agent,
+ // so a since-reassigned issue can't be used to re-fire a private agent the
+ // operator may only view. A block fails closed: no prior task is cancelled,
+ // no new task is created.
+ if canInvoke != nil {
+ targetAgent, err := s.Queries.GetAgent(ctx, agentID)
+ if err != nil {
+ return nil, fmt.Errorf("load target agent: %w", err)
+ }
+ if !canInvoke(targetAgent) {
+ return nil, ErrRerunInvokeNotAllowed
+ }
+ }
+
// Cancel only the target agent's active/queued tasks on this issue.
cancelled, err := s.Queries.CancelAgentTasksByIssueAndAgent(ctx, db.CancelAgentTasksByIssueAndAgentParams{
IssueID: issueID,
@@ -2886,7 +3266,12 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
- task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID)
+ // A manual rerun is a NEW direct_human trigger attributed to the rerunning
+ // member, not the original run's human (MUL-4302 §5); actorUserID carries them.
+ // sourceTaskID is the rerun lineage: it rides the CreateAgentTask insert
+ // (rerun_of_task_id) so the queued event / daemon claim never sees a NULL
+ // lineage, and it stays distinct from system-retry's retry_of_task_id (§5).
+ task, err := s.enqueueRerunTask(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, actorUserID, sourceTaskID)
if err != nil {
return nil, err
}
@@ -2957,12 +3342,12 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []p
// stays in sync; otherwise (squad member, prior assignee that has since been
// reassigned, mention agent) we use the mention path with the same
// force_fresh_session=true contract.
-func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID) (db.AgentTaskQueue, error) {
+func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "")
+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID)
}
- return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "")
+ return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID)
}
// HandleFailedTasks runs the post-failure side effects for a batch of
diff --git a/server/migrations/184_agent_task_attribution.down.sql b/server/migrations/184_agent_task_attribution.down.sql
new file mode 100644
index 0000000000..1e0f67cbe3
--- /dev/null
+++ b/server/migrations/184_agent_task_attribution.down.sql
@@ -0,0 +1,7 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS trigger_evidence_ref_id;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS trigger_evidence_kind;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS rule_version_id;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS rerun_of_task_id;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS retry_of_task_id;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS delegated_from_task_id;
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS originator_source;
diff --git a/server/migrations/184_agent_task_attribution.up.sql b/server/migrations/184_agent_task_attribution.up.sql
new file mode 100644
index 0000000000..c586e4f3b2
--- /dev/null
+++ b/server/migrations/184_agent_task_attribution.up.sql
@@ -0,0 +1,95 @@
+-- Human Attribution, Phase 1 foundation (MUL-4302, parent MUL-4274; upstream
+-- discussion GH #5108). Every agent run must be traceable to exactly one
+-- accountable human, and that attribution must be EXPLAINABLE: a report has to
+-- state not just WHO but at WHICH waterfall level the human was resolved
+-- (direct action, delegation copy, comment-source chain, autopilot rule owner,
+-- or degraded owner fallback). Today agent_task_queue.originator_user_id records
+-- the human but carries no provenance — a NULL originator could equally mean
+-- "autopilot" or "we failed to resolve a human who exists", and the two must be
+-- distinguishable for the compliance/coverage story.
+--
+-- This migration adds the provenance + lineage columns that the Attribution
+-- Resolver stamps at enqueue time. It deliberately does NOT change the value or
+-- semantics of originator_user_id, which feeds authorization decisions
+-- (canInvokeAgent A2A gate, Composio overlay history) — per the design axiom
+-- "attribution is on-behalf-of, never blame and never authorization"
+-- (MUL-4302 §1.3). These columns are audit/visibility metadata only.
+--
+-- Constraints honored (MUL-4302 §7 + workspace DB rules): NO foreign keys, NO
+-- cascades (integrity is resolved in the application layer), and NO CHECK
+-- constraint on the source enum so that a newly-modeled trigger path can add a
+-- source label without a schema migration. All columns are nullable with no
+-- default so the ALTER is a fast metadata-only change on the hot queue table
+-- (no table rewrite, no long lock).
+
+-- originator_source: which waterfall level resolved originator_user_id for this
+-- run. One of: 'direct_human', 'delegation', 'comment_source', 'rule_owner',
+-- 'owner_fallback', 'backfill', 'unattributed'. TEXT with no CHECK on purpose
+-- (see header). NULL only on rows that predate this migration.
+ALTER TABLE agent_task_queue
+ ADD COLUMN originator_source TEXT NULL;
+
+COMMENT ON COLUMN agent_task_queue.originator_source IS
+ 'Waterfall level that resolved originator_user_id for this run: direct_human | delegation | comment_source | rule_owner | owner_fallback | backfill | unattributed. Audit/visibility metadata only — never consulted for authorization. TEXT with no CHECK so new trigger paths can add a source without a migration (MUL-4302 §7). NULL on pre-migration rows.';
+
+-- delegated_from_task_id: for source='delegation', the parent task whose
+-- accountable human was COPIED onto this run (agent A @-mentions agent B, or an
+-- agent creates a sub-issue). The chain root stays stable and copying the value
+-- (not walking the chain) keeps delegation cycles harmless (MUL-4302 §3.2).
+-- No FK by design; a stale id degrades to "evidence not resolvable", never a
+-- corrupt run.
+ALTER TABLE agent_task_queue
+ ADD COLUMN delegated_from_task_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.delegated_from_task_id IS
+ 'For originator_source=delegation: the parent task whose accountable human was copied onto this run. Value is copied, not chained, so delegation cycles are harmless (MUL-4302 §3.2). No FK; app-layer integrity only.';
+
+-- retry_of_task_id / rerun_of_task_id: the design requires retry and rerun to be
+-- kept strictly apart in reporting (MUL-4302 §5). parent_task_id already links
+-- system auto-retries, but it is overloaded and does not distinguish the two.
+-- * retry_of_task_id — system transient-failure retry; INHERITS the parent's
+-- attribution unchanged (not a new attribution event).
+-- * rerun_of_task_id — human manual rerun of a historical task; a NEW
+-- direct_human attribution to the person who clicked rerun, with lineage
+-- preserved back to the original task.
+-- Both no-FK, nullable.
+ALTER TABLE agent_task_queue
+ ADD COLUMN retry_of_task_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.retry_of_task_id IS
+ 'System transient-failure retry lineage: the task this run re-attempts. Inherits the parent attribution unchanged. Kept distinct from rerun_of_task_id so retry vs rerun report separately (MUL-4302 §5). No FK.';
+
+ALTER TABLE agent_task_queue
+ ADD COLUMN rerun_of_task_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.rerun_of_task_id IS
+ 'Human manual-rerun lineage: the historical task a member re-ran. The rerun itself is a NEW direct_human attribution to the rerunning member; this column preserves the link to the original (MUL-4302 §5). No FK.';
+
+-- rule_version_id: for source='rule_owner', the published autopilot rule version
+-- whose publisher is the accountable human. The rule-version snapshot table and
+-- its wiring land in a later Phase 1 increment; the column ships now so the
+-- resolver contract and the queue schema are stable. No FK, nullable.
+ALTER TABLE agent_task_queue
+ ADD COLUMN rule_version_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.rule_version_id IS
+ 'For originator_source=rule_owner: the published autopilot rule version snapshot whose publisher is the accountable human. No FK; snapshot table wiring lands in a later Phase 1 increment (MUL-4302 §3.4/§7).';
+
+-- trigger_evidence_kind / trigger_evidence_ref_id: the direct cause of the run,
+-- so every attribution can jump to its evidence (which comment, which assign,
+-- which rule version, which external event). kind is a free TEXT tag
+-- ('comment' | 'issue_assignment' | 'autopilot_run' | 'rule_version' | 'rerun'
+-- | ...); ref_id points at that row. trigger_comment_id / autopilot_run_id
+-- still exist for their existing consumers — this pair is the uniform,
+-- kind-tagged evidence handle the attribution UI will link from (MUL-4302 §2).
+ALTER TABLE agent_task_queue
+ ADD COLUMN trigger_evidence_kind TEXT NULL;
+
+COMMENT ON COLUMN agent_task_queue.trigger_evidence_kind IS
+ 'Uniform kind tag for the direct cause of this run (comment | issue_assignment | autopilot_run | rule_version | rerun | ...), paired with trigger_evidence_ref_id. Free TEXT so new evidence kinds need no migration (MUL-4302 §2).';
+
+ALTER TABLE agent_task_queue
+ ADD COLUMN trigger_evidence_ref_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.trigger_evidence_ref_id IS
+ 'The row id referenced by trigger_evidence_kind (a comment id, autopilot_run id, rule_version id, source task id, ...). No FK; resolvable per-kind in the app layer (MUL-4302 §2).';
diff --git a/server/migrations/185_agent_task_accountable_user.down.sql b/server/migrations/185_agent_task_accountable_user.down.sql
new file mode 100644
index 0000000000..17e69262da
--- /dev/null
+++ b/server/migrations/185_agent_task_accountable_user.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS accountable_user_id;
diff --git a/server/migrations/185_agent_task_accountable_user.up.sql b/server/migrations/185_agent_task_accountable_user.up.sql
new file mode 100644
index 0000000000..099c0956a2
--- /dev/null
+++ b/server/migrations/185_agent_task_accountable_user.up.sql
@@ -0,0 +1,53 @@
+-- Human Attribution, Phase 1 — split the accountable human off originator_user_id
+-- (MUL-4302, decided by Bohan on the MUL-4302 thread).
+--
+-- Migration 184 stamped provenance (originator_source, evidence, lineage) ONTO
+-- originator_user_id, treating that one column as both "who authorized this run"
+-- and "who is accountable for it". Those are two different questions with two
+-- different lifetimes, and collapsing them onto one column is a latent hazard:
+--
+-- * originator_user_id is an AUTHORIZATION input. canInvokeAgent (the A2A gate)
+-- and the Composio overlay read it to decide "whose permission is this run
+-- acting under". It is legitimately NULL when no human lent their authority
+-- (autopilot schedule/webhook, or a chain that resolves to no human). NULL is
+-- the authorization system's only way to say "this run carries no human
+-- permission" — the owner-can-invoke-own-agent branch in canInvokeAgent means
+-- that forging a non-NULL owner here would turn every unresolved run into a
+-- fully-privileged one (fail-open). So this column must stay unforgeable.
+--
+-- * accountable_user_id is an AUDIT / visibility / cost output. The design axiom
+-- (MUL-4302 §1) requires it to be resolvable for every run, degrading to the
+-- rule publisher (rule_owner) or agent owner (owner_fallback) when no human is
+-- in the trigger chain. Its "never NULL for a precise attribution" property is
+-- descriptive (a best-effort label), never a grant of permission.
+--
+-- This migration adds the dedicated audit column. Authorization continues to read
+-- ONLY originator_user_id; audit / UI / usage read accountable_user_id + source +
+-- evidence. The one-way invariant the resolver enforces and §11 tests:
+--
+-- originator_user_id IS NOT NULL ⟹ accountable_user_id = originator_user_id
+--
+-- Divergence happens only when originator_user_id IS NULL (no human authorized the
+-- run) — there the audit side may still name a degraded accountable human while
+-- authorization correctly says "no one". Wiring the divergent sources (rule_owner,
+-- owner_fallback) is a later Phase 1 increment; this migration lands the column and
+-- the mirror-write so that split has a home without ever touching the authz path.
+--
+-- Constraints (MUL-4302 §7 + workspace DB rules): NO foreign key, NO cascade
+-- (integrity is resolved in the application layer). Nullable with no default so the
+-- ALTER is a fast metadata-only change on the hot queue table (no rewrite, no long
+-- lock).
+--
+-- NULL does NOT mean "pre-migration row" here. Unlike originator_source (which
+-- every new enqueue path now stamps non-NULL, migration 184), accountable_user_id
+-- is legitimately NULL on NEW rows too, whenever the row's audit source resolved
+-- no human yet: run_only autopilot writes originator_source='unattributed' with a
+-- NULL accountable until rule_owner lands, and any classified-unattributed path is
+-- the same. So NULL means "no accountable human resolved" — a pre-migration row OR
+-- a new not-yet-resolved / unattributed audit source — and readers must NOT treat
+-- NULL as pre-migration-only when reasoning about the invariant.
+ALTER TABLE agent_task_queue
+ ADD COLUMN accountable_user_id UUID NULL;
+
+COMMENT ON COLUMN agent_task_queue.accountable_user_id IS
+ 'The one human accountable for this run, for audit / visibility / cost only — NEVER consulted for authorization (that is originator_user_id). Invariant: when originator_user_id IS NOT NULL, this equals it; the two diverge only when originator_user_id IS NULL (autopilot rule_owner / degraded owner_fallback name an accountable human while authorization carries none). No FK, no cascade (MUL-4302 §1/§7). NULL means no accountable human was resolved: a pre-migration row, OR a NEW row whose audit source is not-yet-resolved / unattributed (e.g. run_only autopilot until rule_owner lands) — NOT pre-migration only.';
diff --git a/server/migrations/186_autopilot_rule_version.down.sql b/server/migrations/186_autopilot_rule_version.down.sql
new file mode 100644
index 0000000000..674e5bd084
--- /dev/null
+++ b/server/migrations/186_autopilot_rule_version.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS autopilot_rule_version;
diff --git a/server/migrations/186_autopilot_rule_version.up.sql b/server/migrations/186_autopilot_rule_version.up.sql
new file mode 100644
index 0000000000..77a1813414
--- /dev/null
+++ b/server/migrations/186_autopilot_rule_version.up.sql
@@ -0,0 +1,43 @@
+-- Human Attribution, Phase 1 — autopilot rule_owner snapshot table (MUL-4302 §3.4/§7).
+--
+-- An autopilot trigger (schedule / webhook / manual) enqueues a run that NO human
+-- authorized in the moment, so its authorization originator_user_id stays NULL. But
+-- the run is still accountable to a human for audit / cost: the member who last
+-- PUBLISHED the rule that fired it. "Publish" = a substantive action (create, enable,
+-- resume, or a change to the trigger condition / execution target / task
+-- instructions); cosmetic edits (rename, description) do NOT transfer accountability.
+--
+-- Each substantive publish appends one immutable row here, recording who published
+-- and a summary of the effective config at that moment. At dispatch time the resolver
+-- reads the autopilot's ACTIVE (latest) version and stamps the run:
+-- originator_source='rule_owner', accountable_user_id=published_by_id, and
+-- agent_task_queue.rule_version_id=<this row>. Authorization is untouched — this is
+-- the audit side of the accountable/originator split.
+--
+-- Immutable + append-only: a new publish never UPDATEs a prior row, so a run's
+-- rule_version_id always resolves to the exact config/publisher that was live when it
+-- fired, even after the rule is later re-published or the publisher leaves.
+--
+-- Constraints (MUL-4302 §7 + workspace DB rules): NO foreign key, NO cascade —
+-- integrity is resolved in the application layer. published_by_id is nullable
+-- (system-published rules have no member); a NULL publisher degrades the run to
+-- 'unattributed' rather than fabricating a human.
+CREATE TABLE IF NOT EXISTS autopilot_rule_version (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ autopilot_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ published_by_type TEXT NOT NULL,
+ published_by_id UUID NULL,
+ config_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Application-layer integrity only: proactively drop any *_fkey a tool might add,
+-- matching the workspace no-FK / no-cascade rule (see 152_chat_pinned_agent).
+ALTER TABLE autopilot_rule_version
+ DROP CONSTRAINT IF EXISTS autopilot_rule_version_autopilot_id_fkey,
+ DROP CONSTRAINT IF EXISTS autopilot_rule_version_workspace_id_fkey,
+ DROP CONSTRAINT IF EXISTS autopilot_rule_version_published_by_id_fkey;
+
+COMMENT ON TABLE autopilot_rule_version IS
+ 'Append-only snapshot of autopilot rule publishes (MUL-4302 §3.4). One row per substantive publish (create / enable / resume / trigger-condition / target / instructions change), recording the publisher + effective-config summary. Dispatch resolves the latest row for an autopilot as the run''s rule_owner accountable human. No FK, no cascade.';
diff --git a/server/migrations/187_autopilot_rule_version_index.down.sql b/server/migrations/187_autopilot_rule_version_index.down.sql
new file mode 100644
index 0000000000..92cd9f3ca5
--- /dev/null
+++ b/server/migrations/187_autopilot_rule_version_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_autopilot_rule_version_active;
diff --git a/server/migrations/187_autopilot_rule_version_index.up.sql b/server/migrations/187_autopilot_rule_version_index.up.sql
new file mode 100644
index 0000000000..297a744a1a
--- /dev/null
+++ b/server/migrations/187_autopilot_rule_version_index.up.sql
@@ -0,0 +1,9 @@
+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a
+-- transaction or a multi-command string.
+--
+-- Dispatch resolves an autopilot's ACTIVE rule version as "the newest row for this
+-- (workspace, autopilot)", so index on (workspace_id, autopilot_id, created_at DESC)
+-- to serve GetActiveAutopilotRuleVersion's ORDER BY created_at DESC LIMIT 1 without
+-- a scan as the append-only table grows.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_autopilot_rule_version_active
+ ON autopilot_rule_version (workspace_id, autopilot_id, created_at DESC);
diff --git a/server/migrations/188_workspace_attribution_fail_closed.down.sql b/server/migrations/188_workspace_attribution_fail_closed.down.sql
new file mode 100644
index 0000000000..f1815886b6
--- /dev/null
+++ b/server/migrations/188_workspace_attribution_fail_closed.down.sql
@@ -0,0 +1 @@
+ALTER TABLE workspace DROP COLUMN IF EXISTS attribution_fail_closed;
diff --git a/server/migrations/188_workspace_attribution_fail_closed.up.sql b/server/migrations/188_workspace_attribution_fail_closed.up.sql
new file mode 100644
index 0000000000..bbf4530e99
--- /dev/null
+++ b/server/migrations/188_workspace_attribution_fail_closed.up.sql
@@ -0,0 +1,17 @@
+-- Human Attribution, Phase 1 — per-workspace fail-closed policy (MUL-4302 §1/§3.5).
+--
+-- The accountable-human waterfall degrades to owner_fallback (accountable = agent
+-- owner) when no precise human resolves, so every run has an accountable human by
+-- default. Compliance/enterprise workspaces can instead opt into FAIL-CLOSED: a run
+-- that cannot be attributed to a precise human is NOT enqueued rather than falling
+-- back to the owner — better to block an unattributable run than to run it under a
+-- degraded label.
+--
+-- Default FALSE preserves today's behavior (owner_fallback) for every existing
+-- workspace. Adding a NOT NULL boolean WITH a constant default is a fast
+-- metadata-only change on modern Postgres (no table rewrite).
+ALTER TABLE workspace
+ ADD COLUMN attribution_fail_closed BOOLEAN NOT NULL DEFAULT FALSE;
+
+COMMENT ON COLUMN workspace.attribution_fail_closed IS
+ 'When TRUE, an agent run that resolves to no precise accountable human (would be owner_fallback) is refused at enqueue instead of degrading to the agent owner (MUL-4302 §3.5). Default FALSE = owner_fallback. Never affects authorization (originator_user_id).';
diff --git a/server/migrations/189_autopilot_trigger_publisher.down.sql b/server/migrations/189_autopilot_trigger_publisher.down.sql
new file mode 100644
index 0000000000..e14a28e4e5
--- /dev/null
+++ b/server/migrations/189_autopilot_trigger_publisher.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE autopilot_trigger DROP COLUMN IF EXISTS published_by_id;
+ALTER TABLE autopilot_trigger DROP COLUMN IF EXISTS published_by_type;
diff --git a/server/migrations/189_autopilot_trigger_publisher.up.sql b/server/migrations/189_autopilot_trigger_publisher.up.sql
new file mode 100644
index 0000000000..9213800ad9
--- /dev/null
+++ b/server/migrations/189_autopilot_trigger_publisher.up.sql
@@ -0,0 +1,32 @@
+-- Human Attribution — per-trigger responsible publisher (MUL-4302; Bohan + Elon).
+-- An autopilot schedule/webhook run is accountable to the human RESPONSIBLE for the
+-- firing trigger's current effective configuration — initially whoever created the
+-- trigger, then TRANSFERRED to whoever later makes a substantive edit that governs
+-- it (the trigger's own cron / filter / enabled state, or an autopilot-level
+-- target / instructions / enable change that affects all of its triggers). This models
+-- the "current effective automation version's responsible publisher" resolved PER
+-- firing trigger, so editing one trigger never reassigns responsibility for another.
+--
+-- Stored on the trigger row (not derived from the autopilot-scoped rule_version)
+-- precisely so per-trigger granularity holds. The resolver reads it as
+-- source=trigger_owner (accountable = this member, originator NULL — a scheduled /
+-- webhook fire carries no human authorization at fire time; the same authz-safe
+-- divergence as rule_owner).
+--
+-- Constraints (MUL-4302 §7 + workspace DB rules): NO foreign key, NO cascade
+-- (integrity is app-layer), nullable with no default so the ALTER is a fast
+-- metadata-only change. published_by_type is 'member' | 'agent'; only a 'member'
+-- publisher becomes the accountable human — an 'agent'-published trigger degrades to
+-- rule_owner like any other agent action. NULL means no publisher recorded (a
+-- trigger predating this migration), which degrades to rule_owner then owner_fallback.
+ALTER TABLE autopilot_trigger
+ ADD COLUMN published_by_type TEXT NULL;
+
+ALTER TABLE autopilot_trigger
+ ADD COLUMN published_by_id UUID NULL;
+
+COMMENT ON COLUMN autopilot_trigger.published_by_type IS
+ 'Actor type of the trigger''s current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. Consumed only for attribution (source=trigger_owner) — never authorization. NULL on pre-migration triggers (MUL-4302).';
+
+COMMENT ON COLUMN autopilot_trigger.published_by_id IS
+ 'The member/agent currently responsible for this trigger''s effective config (creator, then last substantive editor). For a member this is the accountable human of runs the trigger fires (source=trigger_owner). No FK, app-layer integrity. NULL on pre-migration triggers, which degrade to rule_owner (MUL-4302).';
diff --git a/server/migrations/190_agent_task_attribution_invariant_check.down.sql b/server/migrations/190_agent_task_attribution_invariant_check.down.sql
new file mode 100644
index 0000000000..3714d31a4a
--- /dev/null
+++ b/server/migrations/190_agent_task_attribution_invariant_check.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ DROP CONSTRAINT IF EXISTS agent_task_queue_accountable_matches_originator;
diff --git a/server/migrations/190_agent_task_attribution_invariant_check.up.sql b/server/migrations/190_agent_task_attribution_invariant_check.up.sql
new file mode 100644
index 0000000000..72b22b6375
--- /dev/null
+++ b/server/migrations/190_agent_task_attribution_invariant_check.up.sql
@@ -0,0 +1,58 @@
+-- Human Attribution — enforce the one-way invariant at the DB layer (MUL-4302;
+-- decided by Bohan + Elon on the MUL-4302 thread). The application collapses
+-- originator == accountable at a single chokepoint (finalizeAttribution) and every
+-- write path takes both from the same attribution.Result — but the #5192 comment-
+-- coalescing merge proved that ANOTHER feature's code can silently bypass that
+-- chokepoint and leave originator=B / accountable=A. A cross-column CHECK is exactly
+-- the class of bug this guards: any future write that breaks the invariant fails at
+-- enqueue time rather than silently mis-attributing an audited run.
+--
+-- originator_user_id IS NOT NULL ⟹ accountable_user_id = originator_user_id
+--
+-- This is NOT the source-enum CHECK the earlier ruling forbade (that ban existed so
+-- a new source label needs no migration); this locks a two-column equality, not an
+-- enumerable value, and carries no FK / cascade.
+--
+-- UPGRADE SAFETY — the `originator_source IS NULL` clause exempts legacy-writer /
+-- unbackfilled-lineage rows (Bohan chose the two-phase rollout on the MUL-4302 thread;
+-- raised by Elon). `NOT VALID` skips the initial scan, but Postgres STILL checks a
+-- pre-existing row whenever a later UPDATE touches it — even an UPDATE that leaves the
+-- attribution columns alone. Cross-deployment stale queued/running tasks predate
+-- `185_agent_task_accountable_user`, so they carry (originator_user_id set,
+-- accountable_user_id NULL); their next claim / complete / cancel by the new backend
+-- would fail a bare invariant CHECK.
+--
+-- `originator_source` was added by `184` with no default/backfill, so a NULL there does
+-- NOT strictly mean "row predates the migration" — it means the row was written by a
+-- writer that does not populate attribution: (a) rows created before this PR's
+-- migrations; (b) during a rolling deploy, NEW rows an older, not-yet-replaced backend
+-- INSERTs against the migrated schema; (c) a retry clone that inherits a legacy row's
+-- NULL lineage. All three are exactly the rows the transition must let keep flowing,
+-- and all resolve to "no attribution recorded", so exempting them is correct. Every
+-- attribution-aware write goes through finalizeAttribution, which always stamps a
+-- non-NULL source, so those rows stay under the FULL equality CHECK. Phase 3 backfills
+-- the exempt rows (real source + reconciled accountable), then drops this constraint
+-- and re-adds the strict form (without the exemption) + VALIDATE.
+--
+-- This does NOT reopen the #5192 bug class: that merge — and every real enqueue /
+-- coalesce path — stamps originator_source non-NULL, so an (originator=B,
+-- accountable=A) bypass is still rejected. Only the source-NULL (legacy-writer /
+-- unbackfilled) shape is exempt.
+--
+-- Added NOT VALID so the constraint is a fast metadata-only add on the hot queue table
+-- (no full-table ACCESS EXCLUSIVE scan); it enforces on every new INSERT/UPDATE
+-- immediately.
+--
+-- The `accountable_user_id IS NOT NULL AND` guard is load-bearing: a bare
+-- `accountable_user_id = originator_user_id` would let (originator=X, accountable=NULL)
+-- slip through — SQL evaluates `NULL = X` to UNKNOWN, and a CHECK passes on anything
+-- that is not FALSE. The bypass we most need to catch (originator set, accountable
+-- left NULL) is exactly that shape, so the NULL must be rejected explicitly.
+ALTER TABLE agent_task_queue
+ ADD CONSTRAINT agent_task_queue_accountable_matches_originator
+ CHECK (
+ originator_source IS NULL
+ OR originator_user_id IS NULL
+ OR (accountable_user_id IS NOT NULL AND accountable_user_id = originator_user_id)
+ )
+ NOT VALID;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index c191ca227f..d61bf0c163 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -190,7 +190,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE 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
+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
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -236,6 +236,14 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -244,7 +252,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE 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
+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
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -301,6 +309,14 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -316,7 +332,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE 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
+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
`
// Cancels active tasks belonging to a chat session. Called from
@@ -373,6 +389,14 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -388,7 +412,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE 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
+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
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -445,6 +469,14 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -460,7 +492,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 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
+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
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -521,6 +553,14 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -537,7 +577,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
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
+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
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -593,6 +633,14 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -613,9 +661,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id
)
-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 FROM cancelled
+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 FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -663,6 +711,14 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
+ RetryOfTaskID pgtype.UUID `json:"retry_of_task_id"`
+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
+ RuleVersionID pgtype.UUID `json:"rule_version_id"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -714,6 +770,14 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -730,7 +794,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', '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
+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
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -782,6 +846,14 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -822,7 +894,7 @@ WHERE id = (
LIMIT 1
FOR 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
+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
`
type ClaimAgentTaskParams struct {
@@ -882,6 +954,14 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -890,7 +970,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE 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
+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
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -938,6 +1018,14 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1075,7 +1163,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
WHERE 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
+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
`
type CompleteAgentTaskParams struct {
@@ -1133,6 +1221,14 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1314,7 +1410,8 @@ const createAgentTask = `-- name: CreateAgentTask :one
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, runtime_mcp_overlay, runtime_connected_apps
+ 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
)
VALUES (
$1, $2, $3, 'queued', $4, $5,
@@ -1331,9 +1428,16 @@ VALUES (
END,
$13,
$14,
- $15
+ $15,
+ $16,
+ $17,
+ $18,
+ $19,
+ $20,
+ $21,
+ $22
)
-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
+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
`
type CreateAgentTaskParams struct {
@@ -1350,8 +1454,15 @@ type CreateAgentTaskParams struct {
SquadID pgtype.UUID `json:"squad_id"`
HeadSha pgtype.Text `json:"head_sha"`
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
+ RuleVersionID pgtype.UUID `json:"rule_version_id"`
+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
// head_sha stamps the commit under review into the task's context JSONB so the
@@ -1376,8 +1487,15 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
arg.SquadID,
arg.HeadSha,
arg.OriginatorUserID,
+ arg.AccountableUserID,
arg.RuntimeMcpOverlay,
arg.RuntimeConnectedApps,
+ arg.OriginatorSource,
+ arg.DelegatedFromTaskID,
+ arg.RuleVersionID,
+ arg.RerunOfTaskID,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -1420,6 +1538,14 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1427,7 +1553,9 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
const createDeferredAgentTask = `-- name: CreateDeferredAgentTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at
+ trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,
+ originator_user_id, accountable_user_id, originator_source,
+ delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
$1, $2, $3, 'deferred', $4,
@@ -1436,27 +1564,43 @@ VALUES (
COALESCE($7::boolean, FALSE),
$8,
$9,
- $10
+ $10,
+ $11,
+ $12,
+ $13,
+ $14,
+ $15,
+ $16
)
-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
+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
`
type CreateDeferredAgentTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Priority int32 `json:"priority"`
- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
- IsLeaderTask pgtype.Bool `json:"is_leader_task"`
- SquadID pgtype.UUID `json:"squad_id"`
- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
- FireAt pgtype.Timestamptz `json:"fire_at"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Priority int32 `json:"priority"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
// Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them
// to queued. Used for comment-routing escalation: a thread-owner primary task
// gets a delayed assignee fallback without waking both agents at t=0.
+// Attribution is resolved and stamped at creation (not at promotion), from the
+// same trigger comment as the primary task, so the fallback assignee's run
+// carries a non-NULL source and evidence rather than bypassing attribution
+// (MUL-4302 §2).
func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferredAgentTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createDeferredAgentTask,
arg.AgentID,
@@ -1469,6 +1613,12 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
arg.SquadID,
arg.EscalationForTaskID,
arg.FireAt,
+ arg.OriginatorUserID,
+ arg.AccountableUserID,
+ arg.OriginatorSource,
+ arg.DelegatedFromTaskID,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -1511,6 +1661,14 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1518,15 +1676,20 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
const createQuickCreateTask = `-- name: CreateQuickCreateTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,
- runtime_mcp_overlay, runtime_connected_apps
+ accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
$1, $2, NULL, 'queued', $3, $4,
$5,
$6,
- $7
+ $7,
+ $8,
+ $9,
+ $10,
+ $11
)
-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
+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
`
type CreateQuickCreateTaskParams struct {
@@ -1535,13 +1698,20 @@ type CreateQuickCreateTaskParams struct {
Priority int32 `json:"priority"`
Context []byte `json:"context"`
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
// Quick-create tasks have no issue / chat / autopilot link; the entire job
// description (prompt, requester, workspace) lives in context JSONB. The
// daemon detects this variant via context.type == "quick_create".
+// The requester who opened the quick-create modal is a direct_human originator
+// and accountable; attribution provenance is stamped so this path is not a
+// NULL-source enqueue bypass (MUL-4302 §2).
func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCreateTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createQuickCreateTask,
arg.AgentID,
@@ -1549,8 +1719,12 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
arg.Priority,
arg.Context,
arg.OriginatorUserID,
+ arg.AccountableUserID,
arg.RuntimeMcpOverlay,
arg.RuntimeConnectedApps,
+ arg.OriginatorSource,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -1593,6 +1767,14 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1603,7 +1785,9 @@ 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, runtime_mcp_overlay, runtime_connected_apps,
+ 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
)
SELECT
@@ -1618,12 +1802,15 @@ SELECT
p.is_leader_task,
p.squad_id,
p.originator_user_id,
+ p.accountable_user_id,
$2,
$3,
+ p.originator_source, p.delegated_from_task_id, p.rule_version_id,
+ p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id
FROM agent_task_queue p
WHERE p.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
+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
`
type CreateRetryTaskParams struct {
@@ -1649,6 +1836,12 @@ type CreateRetryTaskParams struct {
// run has not changed. The Composio overlay follows the agent's invocation
// permission and uses the agent owner's connection (MUL-3963); originator is
// carried for A2A/audit, not as an originator == agent.owner_id gate.
+// A system retry is NOT a new attribution event (MUL-4302 §5): it inherits the
+// parent's accountable human, source label, delegation lineage, rule version,
+// and trigger evidence UNCHANGED, and records retry_of_task_id = p.id so retry
+// and manual rerun stay separable in reporting. parent_task_id keeps its
+// existing meaning for the retry/resume machinery; retry_of_task_id is the
+// attribution-facing lineage column.
//
// chat_input_task_id is inherited straight from the parent so the whole retry
// chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
@@ -1707,6 +1900,14 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1743,7 +1944,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-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
+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
`
type ExpireStaleQueuedTasksParams struct {
@@ -1823,6 +2024,14 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -1841,7 +2050,7 @@ WHERE id = $1
AND runtime_id = $2
AND 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
+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
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1897,6 +2106,14 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1911,7 +2128,7 @@ SET status = 'failed',
work_dir = COALESCE($5, work_dir),
prepare_lease_expires_at = NULL
WHERE 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
+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
`
type FailAgentTaskParams struct {
@@ -1980,6 +2197,14 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -2004,7 +2229,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
)
)
-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
+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
`
type FailStaleTasksParams struct {
@@ -2099,6 +2324,14 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -2234,7 +2467,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 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 FROM agent_task_queue
WHERE id = $1
`
@@ -2281,12 +2514,20 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
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 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 FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2346,6 +2587,14 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -2837,7 +3086,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 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 FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2896,6 +3145,14 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -2908,7 +3165,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
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 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 FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2962,6 +3219,14 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3080,7 +3345,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
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 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 FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -3144,6 +3409,14 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3156,7 +3429,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
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 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 FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -3210,6 +3483,14 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3222,7 +3503,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :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 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 FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3284,6 +3565,14 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3296,7 +3585,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :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 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 FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3360,6 +3649,14 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3372,7 +3669,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 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 FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -3426,6 +3723,14 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3438,15 +3743,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
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 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 FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-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 FROM (
- SELECT DISTINCT ON (atq.agent_id) 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
+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 FROM (
+ SELECT DISTINCT ON (atq.agent_id) 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
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -3522,6 +3827,14 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3539,7 +3852,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
+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
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -3600,6 +3913,14 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -3608,7 +3929,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET 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
+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
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -3656,6 +3977,14 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -3669,13 +3998,26 @@ SET coalesced_comment_ids = (
),
trigger_comment_id = $1::uuid,
trigger_summary = COALESCE($2, trigger_summary),
+ -- Re-attribution is ATOMIC (MUL-4302): folding a newly-arrived comment moves the
+ -- WHOLE attribution snapshot to that comment's human — person columns, source
+ -- label, delegation lineage, rule version, and evidence — computed by the caller
+ -- as one attribution.Result. Re-stamping only the person columns would leave a
+ -- run showing B accountable while still pointing at A's stale source / evidence /
+ -- level. accountable comes from the resolved Result (finalizeAttribution already
+ -- guaranteed originator ⟹ accountable == originator; the cross-column CHECK backs it).
originator_user_id = $3::uuid,
- runtime_mcp_overlay = $4,
- runtime_connected_apps = $5
+ accountable_user_id = $4::uuid,
+ originator_source = $5,
+ delegated_from_task_id = $6::uuid,
+ rule_version_id = $7::uuid,
+ trigger_evidence_kind = $8,
+ trigger_evidence_ref_id = $9::uuid,
+ runtime_mcp_overlay = $10,
+ runtime_connected_apps = $11
WHERE id = (
SELECT t.id FROM agent_task_queue t
- WHERE t.issue_id = $6
- AND t.agent_id = $7
+ WHERE t.issue_id = $12
+ AND t.agent_id = $13
AND t.status = 'queued'
ORDER BY t.created_at DESC
LIMIT 1
@@ -3687,6 +4029,12 @@ type MergeCommentIntoPendingTaskParams struct {
NewTriggerCommentID pgtype.UUID `json:"new_trigger_comment_id"`
NewTriggerSummary pgtype.Text `json:"new_trigger_summary"`
NewOriginatorUserID pgtype.UUID `json:"new_originator_user_id"`
+ NewAccountableUserID pgtype.UUID `json:"new_accountable_user_id"`
+ NewOriginatorSource pgtype.Text `json:"new_originator_source"`
+ NewDelegatedFromTaskID pgtype.UUID `json:"new_delegated_from_task_id"`
+ NewRuleVersionID pgtype.UUID `json:"new_rule_version_id"`
+ NewTriggerEvidenceKind pgtype.Text `json:"new_trigger_evidence_kind"`
+ NewTriggerEvidenceRefID pgtype.UUID `json:"new_trigger_evidence_ref_id"`
NewRuntimeMcpOverlay []byte `json:"new_runtime_mcp_overlay"`
NewRuntimeConnectedApps []byte `json:"new_runtime_connected_apps"`
IssueID pgtype.UUID `json:"issue_id"`
@@ -3746,6 +4094,12 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeComm
arg.NewTriggerCommentID,
arg.NewTriggerSummary,
arg.NewOriginatorUserID,
+ arg.NewAccountableUserID,
+ arg.NewOriginatorSource,
+ arg.NewDelegatedFromTaskID,
+ arg.NewRuleVersionID,
+ arg.NewTriggerEvidenceKind,
+ arg.NewTriggerEvidenceRefID,
arg.NewRuntimeMcpOverlay,
arg.NewRuntimeConnectedApps,
arg.IssueID,
@@ -3762,7 +4116,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-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
+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
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -3814,6 +4168,14 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3831,7 +4193,7 @@ SET status = 'queued'
WHERE runtime_id = ANY($1::uuid[])
AND status = 'deferred'
AND fire_at <= now()
-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
+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
`
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
@@ -3885,6 +4247,14 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -3911,7 +4281,7 @@ WHERE id = (
LIMIT 1
FOR 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
+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
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -3968,6 +4338,14 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -3987,7 +4365,7 @@ WHERE id IN (
LIMIT $4::int
FOR 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
+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
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -4058,6 +4436,14 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -4078,7 +4464,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE 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
+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
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -4136,6 +4522,14 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -4203,7 +4597,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
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
+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
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -4260,6 +4654,14 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -4358,7 +4760,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', '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
+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
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -4410,6 +4812,14 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index ae06911970..3564c37418 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -153,6 +153,55 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
return i, err
}
+const createAutopilotRuleVersion = `-- name: CreateAutopilotRuleVersion :one
+
+INSERT INTO autopilot_rule_version (
+ autopilot_id, workspace_id, published_by_type, published_by_id, config_summary
+)
+VALUES (
+ $1, $2, $3, $4,
+ COALESCE($5, '{}'::jsonb)
+)
+RETURNING id, autopilot_id, workspace_id, published_by_type, published_by_id, config_summary, created_at
+`
+
+type CreateAutopilotRuleVersionParams struct {
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PublishedByType string `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
+ ConfigSummary interface{} `json:"config_summary"`
+}
+
+// =====================
+// Autopilot Rule Version (rule_owner attribution, MUL-4302 §3.4)
+// =====================
+// Append one immutable rule-version snapshot on a substantive publish (create /
+// enable / resume / target / execution-mode change). published_by_* is the acting
+// member (or 'system' with NULL id for the failure monitor); config_summary is the
+// effective config at publish time. Dispatch reads the latest row for the autopilot
+// as the run's rule_owner accountable human.
+func (q *Queries) CreateAutopilotRuleVersion(ctx context.Context, arg CreateAutopilotRuleVersionParams) (AutopilotRuleVersion, error) {
+ row := q.db.QueryRow(ctx, createAutopilotRuleVersion,
+ arg.AutopilotID,
+ arg.WorkspaceID,
+ arg.PublishedByType,
+ arg.PublishedByID,
+ arg.ConfigSummary,
+ )
+ var i AutopilotRuleVersion
+ err := row.Scan(
+ &i.ID,
+ &i.AutopilotID,
+ &i.WorkspaceID,
+ &i.PublishedByType,
+ &i.PublishedByID,
+ &i.ConfigSummary,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const createAutopilotRun = `-- name: CreateAutopilotRun :one
INSERT INTO autopilot_run (
@@ -225,22 +274,52 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
const createAutopilotTask = `-- name: CreateAutopilotTask :one
-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
-VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-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
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,
+ originator_user_id, accountable_user_id, rule_version_id,
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+)
+VALUES (
+ $1, $2, NULL, 'queued', $3, $4, $5,
+ $6,
+ $7,
+ $8,
+ $9,
+ $10,
+ $11
+)
+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
`
type CreateAutopilotTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- Priority int32 `json:"priority"`
- AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Priority int32 `json:"priority"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ RuleVersionID pgtype.UUID `json:"rule_version_id"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
// =====================
// Task Queue (run_only mode)
// =====================
+// run_only autopilot dispatch. Attribution depends on the trigger:
+// - schedule / webhook / api: no human authorized the run, so originator_user_id
+// stays NULL and accountable_user_id is the rule_owner (the publisher of the
+// autopilot's active rule version), with rule_version_id recording the snapshot
+// (MUL-4302 §3.4) — the accountable-diverges-from-originator case.
+// - manual: a member clicked "run now", a direct human action, so originator and
+// accountable are BOTH that member (originator_source='direct_human'); no rule
+// version is involved (MUL-4302 §4).
+//
+// When no version/publisher resolves on the non-manual path, the caller passes NULL
+// accountable + originator_source='unattributed' so the row is still not a
+// NULL-source bypass (MUL-4302 §2).
func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createAutopilotTask,
arg.AgentID,
@@ -248,6 +327,12 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
arg.Priority,
arg.AutopilotRunID,
arg.TriggerSummary,
+ arg.OriginatorUserID,
+ arg.AccountableUserID,
+ arg.RuleVersionID,
+ arg.OriginatorSource,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -290,6 +375,14 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -297,26 +390,30 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
const createAutopilotTrigger = `-- name: CreateAutopilotTrigger :one
INSERT INTO autopilot_trigger (
autopilot_id, kind, enabled, cron_expression, timezone,
- next_run_at, webhook_token, label, provider, event_filters
+ next_run_at, webhook_token, label, provider, event_filters,
+ published_by_type, published_by_id
) VALUES (
$1, $2, $3, $4, $5,
$6, $7, $8,
COALESCE($9::text, 'generic'),
- $10
-) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters
+ $10,
+ $11, $12
+) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id
`
type CreateAutopilotTriggerParams struct {
- AutopilotID pgtype.UUID `json:"autopilot_id"`
- Kind string `json:"kind"`
- Enabled bool `json:"enabled"`
- CronExpression pgtype.Text `json:"cron_expression"`
- Timezone pgtype.Text `json:"timezone"`
- NextRunAt pgtype.Timestamptz `json:"next_run_at"`
- WebhookToken pgtype.Text `json:"webhook_token"`
- Label pgtype.Text `json:"label"`
- Provider pgtype.Text `json:"provider"`
- EventFilters []byte `json:"event_filters"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ Kind string `json:"kind"`
+ Enabled bool `json:"enabled"`
+ CronExpression pgtype.Text `json:"cron_expression"`
+ Timezone pgtype.Text `json:"timezone"`
+ NextRunAt pgtype.Timestamptz `json:"next_run_at"`
+ WebhookToken pgtype.Text `json:"webhook_token"`
+ Label pgtype.Text `json:"label"`
+ Provider pgtype.Text `json:"provider"`
+ EventFilters []byte `json:"event_filters"`
+ PublishedByType pgtype.Text `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
}
func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilotTriggerParams) (AutopilotTrigger, error) {
@@ -331,6 +428,8 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
arg.Label,
arg.Provider,
arg.EventFilters,
+ arg.PublishedByType,
+ arg.PublishedByID,
)
var i AutopilotTrigger
err := row.Scan(
@@ -349,6 +448,8 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
@@ -414,6 +515,36 @@ func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.U
return err
}
+const getActiveAutopilotRuleVersion = `-- name: GetActiveAutopilotRuleVersion :one
+SELECT id, autopilot_id, workspace_id, published_by_type, published_by_id, config_summary, created_at FROM autopilot_rule_version
+WHERE workspace_id = $1 AND autopilot_id = $2
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+type GetActiveAutopilotRuleVersionParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+}
+
+// The active version is the newest published row for the autopilot. Scoped by
+// workspace_id per the workspace query rule; autopilot_id is globally unique so the
+// workspace filter is a guard, not the selector.
+func (q *Queries) GetActiveAutopilotRuleVersion(ctx context.Context, arg GetActiveAutopilotRuleVersionParams) (AutopilotRuleVersion, error) {
+ row := q.db.QueryRow(ctx, getActiveAutopilotRuleVersion, arg.WorkspaceID, arg.AutopilotID)
+ var i AutopilotRuleVersion
+ err := row.Scan(
+ &i.ID,
+ &i.AutopilotID,
+ &i.WorkspaceID,
+ &i.PublishedByType,
+ &i.PublishedByID,
+ &i.ConfigSummary,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const getAutopilot = `-- name: GetAutopilot :one
SELECT id, workspace_id, title, description, assignee_id, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at, assignee_type, project_id FROM autopilot
WHERE id = $1
@@ -613,7 +744,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 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 FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -663,12 +794,21 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
const getAutopilotTrigger = `-- name: GetAutopilotTrigger :one
-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters FROM autopilot_trigger
+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id FROM autopilot_trigger
WHERE id = $1
`
@@ -691,12 +831,14 @@ func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (Auto
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
const getWebhookTriggerByToken = `-- name: GetWebhookTriggerByToken :one
-SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, a.workspace_id AS autopilot_workspace_id
+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, t.published_by_type, t.published_by_id, a.workspace_id AS autopilot_workspace_id
FROM autopilot_trigger t
JOIN autopilot a ON a.id = t.autopilot_id
WHERE t.kind = 'webhook'
@@ -719,6 +861,8 @@ type GetWebhookTriggerByTokenRow struct {
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
EventFilters []byte `json:"event_filters"`
+ PublishedByType pgtype.Text `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -746,6 +890,8 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgt
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
&i.AutopilotWorkspaceID,
)
return i, err
@@ -921,7 +1067,7 @@ func (q *Queries) ListAutopilotSubscribers(ctx context.Context, autopilotID pgty
const listAutopilotTriggers = `-- name: ListAutopilotTriggers :many
-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters FROM autopilot_trigger
+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id FROM autopilot_trigger
WHERE autopilot_id = $1
ORDER BY created_at ASC
`
@@ -954,6 +1100,8 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
); err != nil {
return nil, err
}
@@ -1157,7 +1305,7 @@ SET webhook_token = $2,
updated_at = now()
WHERE id = $1
AND kind = 'webhook'
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id
`
type RotateAutopilotTriggerWebhookTokenParams struct {
@@ -1187,6 +1335,8 @@ func (q *Queries) RotateAutopilotTriggerWebhookToken(ctx context.Context, arg Ro
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
@@ -1273,13 +1423,55 @@ func (q *Queries) SelectAutopilotsExceedingFailureThreshold(ctx context.Context,
return items, nil
}
+const setAutopilotTriggerPublisher = `-- name: SetAutopilotTriggerPublisher :exec
+UPDATE autopilot_trigger
+SET published_by_type = $2, published_by_id = $3, updated_at = now()
+WHERE id = $1
+`
+
+type SetAutopilotTriggerPublisherParams struct {
+ ID pgtype.UUID `json:"id"`
+ PublishedByType pgtype.Text `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
+}
+
+// Re-stamp a single trigger's responsible publisher after a substantive edit of
+// THAT trigger (cron / filter / enabled / webhook security). Future runs it fires
+// become accountable to this member (MUL-4302 trigger_owner transfer).
+func (q *Queries) SetAutopilotTriggerPublisher(ctx context.Context, arg SetAutopilotTriggerPublisherParams) error {
+ _, err := q.db.Exec(ctx, setAutopilotTriggerPublisher, arg.ID, arg.PublishedByType, arg.PublishedByID)
+ return err
+}
+
+const setAutopilotTriggerPublishersByAutopilot = `-- name: SetAutopilotTriggerPublishersByAutopilot :exec
+UPDATE autopilot_trigger
+SET published_by_type = $2, published_by_id = $3, updated_at = now()
+WHERE autopilot_id = $1
+`
+
+type SetAutopilotTriggerPublishersByAutopilotParams struct {
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ PublishedByType pgtype.Text `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
+}
+
+// Re-stamp ALL of an autopilot's triggers' responsible publisher after a substantive
+// AUTOPILOT-level edit (target / instructions / assignee / execution-mode / enable).
+// Such a change governs every trigger's future runs, so responsibility transfers to
+// the editing member for all of them; a per-trigger edit uses the single-trigger
+// variant so it never reassigns another trigger (MUL-4302).
+func (q *Queries) SetAutopilotTriggerPublishersByAutopilot(ctx context.Context, arg SetAutopilotTriggerPublishersByAutopilotParams) error {
+ _, err := q.db.Exec(ctx, setAutopilotTriggerPublishersByAutopilot, arg.AutopilotID, arg.PublishedByType, arg.PublishedByID)
+ return err
+}
+
const setAutopilotTriggerSigningSecret = `-- name: SetAutopilotTriggerSigningSecret :one
UPDATE autopilot_trigger
SET signing_secret = $2,
updated_at = now()
WHERE id = $1
AND kind = 'webhook'
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id
`
type SetAutopilotTriggerSigningSecretParams struct {
@@ -1311,6 +1503,8 @@ func (q *Queries) SetAutopilotTriggerSigningSecret(ctx context.Context, arg SetA
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
@@ -1320,7 +1514,7 @@ UPDATE autopilot_trigger
SET webhook_token = $2,
updated_at = now()
WHERE id = $1
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id
`
type SetAutopilotTriggerWebhookTokenParams struct {
@@ -1352,6 +1546,8 @@ func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAu
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
@@ -1712,7 +1908,7 @@ UPDATE autopilot_trigger SET
event_filters = COALESCE($7, event_filters),
updated_at = now()
WHERE id = $1
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id
`
type UpdateAutopilotTriggerParams struct {
@@ -1752,6 +1948,8 @@ func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilo
&i.Provider,
&i.SigningSecret,
&i.EventFilters,
+ &i.PublishedByType,
+ &i.PublishedByID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 22ff627ecd..dbaf81d44b 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -159,17 +159,21 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
- initiator_user_id, originator_user_id, force_fresh_session, runtime_mcp_overlay,
- runtime_connected_apps
+ initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
+ runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
$1, $2, NULL, 'queued', $3, $4, $5,
$6,
- COALESCE($7::boolean, FALSE),
- $8,
- $9
+ $7,
+ COALESCE($8::boolean, FALSE),
+ $9,
+ $10,
+ $11,
+ $12,
+ $13
)
-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
+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
`
type CreateChatTaskParams struct {
@@ -179,11 +183,18 @@ type CreateChatTaskParams struct {
ChatSessionID pgtype.UUID `json:"chat_session_id"`
InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
+// The chat sender (initiator) is a direct_human originator and accountable;
+// attribution provenance is stamped so this path is not a NULL-source enqueue
+// bypass (MUL-4302 §2).
func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createChatTask,
arg.AgentID,
@@ -192,9 +203,13 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.ChatSessionID,
arg.InitiatorUserID,
arg.OriginatorUserID,
+ arg.AccountableUserID,
arg.ForceFreshSession,
arg.RuntimeMcpOverlay,
arg.RuntimeConnectedApps,
+ arg.OriginatorSource,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
)
var i AgentTaskQueue
err := row.Scan(
@@ -237,6 +252,14 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
@@ -1244,7 +1267,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
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
+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
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -1296,6 +1319,14 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 0265ba98da..73e9db07b2 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -132,6 +132,22 @@ type AgentTaskQueue struct {
DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
+ // Waterfall level that resolved originator_user_id for this run: direct_human | delegation | comment_source | rule_owner | owner_fallback | backfill | unattributed. Audit/visibility metadata only — never consulted for authorization. TEXT with no CHECK so new trigger paths can add a source without a migration (MUL-4302 §7). NULL on pre-migration rows.
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ // For originator_source=delegation: the parent task whose accountable human was copied onto this run. Value is copied, not chained, so delegation cycles are harmless (MUL-4302 §3.2). No FK; app-layer integrity only.
+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
+ // System transient-failure retry lineage: the task this run re-attempts. Inherits the parent attribution unchanged. Kept distinct from rerun_of_task_id so retry vs rerun report separately (MUL-4302 §5). No FK.
+ RetryOfTaskID pgtype.UUID `json:"retry_of_task_id"`
+ // Human manual-rerun lineage: the historical task a member re-ran. The rerun itself is a NEW direct_human attribution to the rerunning member; this column preserves the link to the original (MUL-4302 §5). No FK.
+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
+ // For originator_source=rule_owner: the published autopilot rule version snapshot whose publisher is the accountable human. No FK; snapshot table wiring lands in a later Phase 1 increment (MUL-4302 §3.4/§7).
+ RuleVersionID pgtype.UUID `json:"rule_version_id"`
+ // Uniform kind tag for the direct cause of this run (comment | issue_assignment | autopilot_run | rule_version | rerun | ...), paired with trigger_evidence_ref_id. Free TEXT so new evidence kinds need no migration (MUL-4302 §2).
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ // The row id referenced by trigger_evidence_kind (a comment id, autopilot_run id, rule_version id, source task id, ...). No FK; resolvable per-kind in the app layer (MUL-4302 §2).
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ // The one human accountable for this run, for audit / visibility / cost only — NEVER consulted for authorization (that is originator_user_id). Invariant: when originator_user_id IS NOT NULL, this equals it; the two diverge only when originator_user_id IS NULL (autopilot rule_owner / degraded owner_fallback name an accountable human while authorization carries none). No FK, no cascade (MUL-4302 §1/§7). NULL means no accountable human was resolved: a pre-migration row, OR a NEW row whose audit source is not-yet-resolved / unattributed (e.g. run_only autopilot until rule_owner lands) — NOT pre-migration only.
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
}
type AgentToLabel struct {
@@ -183,6 +199,17 @@ type AutopilotCollaborator struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+// Append-only snapshot of autopilot rule publishes (MUL-4302 §3.4). One row per substantive publish (create / enable / resume / trigger-condition / target / instructions change), recording the publisher + effective-config summary. Dispatch resolves the latest row for an autopilot as the run's rule_owner accountable human. No FK, no cascade.
+type AutopilotRuleVersion struct {
+ ID pgtype.UUID `json:"id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PublishedByType string `json:"published_by_type"`
+ PublishedByID pgtype.UUID `json:"published_by_id"`
+ ConfigSummary []byte `json:"config_summary"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type AutopilotRun struct {
ID pgtype.UUID `json:"id"`
AutopilotID pgtype.UUID `json:"autopilot_id"`
@@ -225,6 +252,10 @@ type AutopilotTrigger struct {
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
EventFilters []byte `json:"event_filters"`
+ // Actor type of the trigger's current responsible publisher: member | agent. Set to the creator at creation and re-stamped to the editor on any substantive edit governing this trigger. Consumed only for attribution (source=trigger_owner) — never authorization. NULL on pre-migration triggers (MUL-4302).
+ PublishedByType pgtype.Text `json:"published_by_type"`
+ // The member/agent currently responsible for this trigger's effective config (creator, then last substantive editor). For a member this is the accountable human of runs the trigger fires (source=trigger_owner). No FK, app-layer integrity. NULL on pre-migration triggers, which degrade to rule_owner (MUL-4302).
+ PublishedByID pgtype.UUID `json:"published_by_id"`
}
type ChannelBindingToken struct {
@@ -993,6 +1024,8 @@ type Workspace struct {
IssuePrefix string `json:"issue_prefix"`
IssueCounter int32 `json:"issue_counter"`
AvatarUrl pgtype.Text `json:"avatar_url"`
+ // When TRUE, an agent run that resolves to no precise accountable human (would be owner_fallback) is refused at enqueue instead of degrading to the agent owner (MUL-4302 §3.5). Default FALSE = owner_fallback. Never affects authorization (originator_user_id).
+ AttributionFailClosed bool `json:"attribution_fail_closed"`
}
type WorkspaceInvitation struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 74b61d818d..e2999d62d1 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND 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
+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
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -87,6 +87,14 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
@@ -218,7 +226,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-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
+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
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -273,6 +281,14 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.DeliveredCommentIds,
&i.ChatInputTaskID,
&i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/user.sql.go b/server/pkg/db/generated/user.sql.go
index d355a7a7e5..1f9a35a26b 100644
--- a/server/pkg/db/generated/user.sql.go
+++ b/server/pkg/db/generated/user.sql.go
@@ -99,6 +99,46 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error
return i, err
}
+const getUsersByIDs = `-- name: GetUsersByIDs :many
+SELECT id, name, email, avatar_url FROM "user"
+WHERE id = ANY($1::uuid[])
+`
+
+type GetUsersByIDsRow struct {
+ ID pgtype.UUID `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ AvatarUrl pgtype.Text `json:"avatar_url"`
+}
+
+// Batch lookup from the GLOBAL user table (not gated on membership, so departed
+// members still render). Used to enrich attribution initiator / originator refs on
+// task responses without an N+1 (MUL-4302 §9). Returns only the display fields.
+func (q *Queries) GetUsersByIDs(ctx context.Context, ids []pgtype.UUID) ([]GetUsersByIDsRow, error) {
+ rows, err := q.db.Query(ctx, getUsersByIDs, ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []GetUsersByIDsRow{}
+ for rows.Next() {
+ var i GetUsersByIDsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Name,
+ &i.Email,
+ &i.AvatarUrl,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const joinCloudWaitlist = `-- name: JoinCloudWaitlist :one
UPDATE "user" SET
cloud_waitlist_email = $2,
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index a15cbcbe6a..4ce02976ef 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -14,7 +14,7 @@ import (
const createWorkspace = `-- name: CreateWorkspace :one
INSERT INTO workspace (name, slug, description, context, issue_prefix)
VALUES ($1, $2, $3, $4, $5)
-RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url
+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed
`
type CreateWorkspaceParams struct {
@@ -47,6 +47,7 @@ func (q *Queries) CreateWorkspace(ctx context.Context, arg CreateWorkspaceParams
&i.IssuePrefix,
&i.IssueCounter,
&i.AvatarUrl,
+ &i.AttributionFailClosed,
)
return i, err
}
@@ -145,7 +146,7 @@ func (q *Queries) GetDaemonWorkspace(ctx context.Context, id pgtype.UUID) (GetDa
}
const getWorkspace = `-- name: GetWorkspace :one
-SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url FROM workspace
+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspace
WHERE id = $1
`
@@ -165,12 +166,27 @@ func (q *Queries) GetWorkspace(ctx context.Context, id pgtype.UUID) (Workspace,
&i.IssuePrefix,
&i.IssueCounter,
&i.AvatarUrl,
+ &i.AttributionFailClosed,
)
return i, err
}
+const getWorkspaceAttributionFailClosed = `-- name: GetWorkspaceAttributionFailClosed :one
+SELECT attribution_fail_closed FROM workspace
+WHERE id = $1
+`
+
+// Lean read of the fail-closed attribution policy for the enqueue hot path
+// (MUL-4302 §3.5), avoiding a full workspace-row fetch.
+func (q *Queries) GetWorkspaceAttributionFailClosed(ctx context.Context, id pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, getWorkspaceAttributionFailClosed, id)
+ var attribution_fail_closed bool
+ err := row.Scan(&attribution_fail_closed)
+ return attribution_fail_closed, err
+}
+
const getWorkspaceBySlug = `-- name: GetWorkspaceBySlug :one
-SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url FROM workspace
+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspace
WHERE slug = $1
`
@@ -190,6 +206,7 @@ func (q *Queries) GetWorkspaceBySlug(ctx context.Context, slug string) (Workspac
&i.IssuePrefix,
&i.IssueCounter,
&i.AvatarUrl,
+ &i.AttributionFailClosed,
)
return i, err
}
@@ -247,7 +264,7 @@ func (q *Queries) ListDaemonWorkspaces(ctx context.Context, userID pgtype.UUID)
const listWorkspaces = `-- name: ListWorkspaces :many
SELECT w.id, w.name, w.slug, w.description, w.settings,
w.created_at, w.updated_at, w.context, w.repos,
- w.issue_prefix, w.issue_counter, w.avatar_url
+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
@@ -276,6 +293,7 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Wor
&i.IssuePrefix,
&i.IssueCounter,
&i.AvatarUrl,
+ &i.AttributionFailClosed,
); err != nil {
return nil, err
}
@@ -342,7 +360,7 @@ UPDATE workspace SET
avatar_url = COALESCE($8, avatar_url),
updated_at = now()
WHERE id = $1
-RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url
+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed
`
type UpdateWorkspaceParams struct {
@@ -381,6 +399,7 @@ func (q *Queries) UpdateWorkspace(ctx context.Context, arg UpdateWorkspaceParams
&i.IssuePrefix,
&i.IssueCounter,
&i.AvatarUrl,
+ &i.AttributionFailClosed,
)
return i, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index cdd2ea1c7d..e817ebf8b7 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -193,7 +193,8 @@ ORDER BY created_at DESC;
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, runtime_mcp_overlay, runtime_connected_apps
+ 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
)
VALUES (
$1, $2, $3, 'queued', $4, sqlc.narg(trigger_comment_id),
@@ -209,8 +210,15 @@ VALUES (
ELSE NULL
END,
sqlc.narg(originator_user_id),
+ sqlc.narg(accountable_user_id),
sqlc.narg(runtime_mcp_overlay),
- sqlc.narg(runtime_connected_apps)
+ sqlc.narg(runtime_connected_apps),
+ sqlc.narg(originator_source),
+ sqlc.narg(delegated_from_task_id),
+ sqlc.narg(rule_version_id),
+ sqlc.narg(rerun_of_task_id),
+ sqlc.narg(trigger_evidence_kind),
+ sqlc.narg(trigger_evidence_ref_id)
)
RETURNING *;
@@ -218,15 +226,23 @@ RETURNING *;
-- Quick-create tasks have no issue / chat / autopilot link; the entire job
-- description (prompt, requester, workspace) lives in context JSONB. The
-- daemon detects this variant via context.type == "quick_create".
+-- The requester who opened the quick-create modal is a direct_human originator
+-- and accountable; attribution provenance is stamped so this path is not a
+-- NULL-source enqueue bypass (MUL-4302 §2).
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,
- runtime_mcp_overlay, runtime_connected_apps
+ accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
$1, $2, NULL, 'queued', $3, $4,
sqlc.narg(originator_user_id),
+ sqlc.narg(accountable_user_id),
sqlc.narg(runtime_mcp_overlay),
- sqlc.narg(runtime_connected_apps)
+ sqlc.narg(runtime_connected_apps),
+ sqlc.narg(originator_source),
+ sqlc.narg(trigger_evidence_kind),
+ sqlc.narg(trigger_evidence_ref_id)
)
RETURNING *;
@@ -234,9 +250,15 @@ RETURNING *;
-- Deferred tasks are inert until PromoteDueDeferredTasksForRuntime flips them
-- to queued. Used for comment-routing escalation: a thread-owner primary task
-- gets a delayed assignee fallback without waking both agents at t=0.
+-- Attribution is resolved and stamped at creation (not at promotion), from the
+-- same trigger comment as the primary task, so the fallback assignee's run
+-- carries a non-NULL source and evidence rather than bypassing attribution
+-- (MUL-4302 §2).
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,
- trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at
+ trigger_summary, is_leader_task, squad_id, escalation_for_task_id, fire_at,
+ originator_user_id, accountable_user_id, originator_source,
+ delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
@agent_id, @runtime_id, @issue_id, 'deferred', @priority,
@@ -245,7 +267,13 @@ VALUES (
COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),
sqlc.narg(squad_id),
@escalation_for_task_id,
- @fire_at
+ @fire_at,
+ sqlc.narg(originator_user_id),
+ sqlc.narg(accountable_user_id),
+ sqlc.narg(originator_source),
+ sqlc.narg(delegated_from_task_id),
+ sqlc.narg(trigger_evidence_kind),
+ sqlc.narg(trigger_evidence_ref_id)
)
RETURNING *;
@@ -277,6 +305,12 @@ WHERE id = $1 AND issue_id IS NULL;
-- run has not changed. The Composio overlay follows the agent's invocation
-- permission and uses the agent owner's connection (MUL-3963); originator is
-- carried for A2A/audit, not as an originator == agent.owner_id gate.
+-- A system retry is NOT a new attribution event (MUL-4302 §5): it inherits the
+-- parent's accountable human, source label, delegation lineage, rule version,
+-- and trigger evidence UNCHANGED, and records retry_of_task_id = p.id so retry
+-- and manual rerun stay separable in reporting. parent_task_id keeps its
+-- existing meaning for the retry/resume machinery; retry_of_task_id is the
+-- attribution-facing lineage column.
--
-- chat_input_task_id is inherited straight from the parent so the whole retry
-- chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
@@ -297,7 +331,9 @@ 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, runtime_mcp_overlay, runtime_connected_apps,
+ 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
)
SELECT
@@ -312,8 +348,11 @@ SELECT
p.is_leader_task,
p.squad_id,
p.originator_user_id,
+ p.accountable_user_id,
sqlc.narg(runtime_mcp_overlay),
sqlc.narg(runtime_connected_apps),
+ p.originator_source, p.delegated_from_task_id, p.rule_version_id,
+ p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id
FROM agent_task_queue p
WHERE p.id = $1
@@ -918,7 +957,20 @@ SET coalesced_comment_ids = (
),
trigger_comment_id = @new_trigger_comment_id::uuid,
trigger_summary = COALESCE(sqlc.narg('new_trigger_summary'), trigger_summary),
+ -- Re-attribution is ATOMIC (MUL-4302): folding a newly-arrived comment moves the
+ -- WHOLE attribution snapshot to that comment's human — person columns, source
+ -- label, delegation lineage, rule version, and evidence — computed by the caller
+ -- as one attribution.Result. Re-stamping only the person columns would leave a
+ -- run showing B accountable while still pointing at A's stale source / evidence /
+ -- level. accountable comes from the resolved Result (finalizeAttribution already
+ -- guaranteed originator ⟹ accountable == originator; the cross-column CHECK backs it).
originator_user_id = sqlc.narg('new_originator_user_id')::uuid,
+ accountable_user_id = sqlc.narg('new_accountable_user_id')::uuid,
+ originator_source = sqlc.narg('new_originator_source'),
+ delegated_from_task_id = sqlc.narg('new_delegated_from_task_id')::uuid,
+ rule_version_id = sqlc.narg('new_rule_version_id')::uuid,
+ trigger_evidence_kind = sqlc.narg('new_trigger_evidence_kind'),
+ trigger_evidence_ref_id = sqlc.narg('new_trigger_evidence_ref_id')::uuid,
runtime_mcp_overlay = sqlc.narg('new_runtime_mcp_overlay'),
runtime_connected_apps = sqlc.narg('new_runtime_connected_apps')
WHERE id = (
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index f04a9ad82c..141591b5f6 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -78,6 +78,34 @@ WHERE id = $1;
UPDATE autopilot SET last_run_at = now(), updated_at = now()
WHERE id = $1;
+-- =====================
+-- Autopilot Rule Version (rule_owner attribution, MUL-4302 §3.4)
+-- =====================
+
+-- name: CreateAutopilotRuleVersion :one
+-- Append one immutable rule-version snapshot on a substantive publish (create /
+-- enable / resume / target / execution-mode change). published_by_* is the acting
+-- member (or 'system' with NULL id for the failure monitor); config_summary is the
+-- effective config at publish time. Dispatch reads the latest row for the autopilot
+-- as the run's rule_owner accountable human.
+INSERT INTO autopilot_rule_version (
+ autopilot_id, workspace_id, published_by_type, published_by_id, config_summary
+)
+VALUES (
+ @autopilot_id, @workspace_id, @published_by_type, sqlc.narg(published_by_id),
+ COALESCE(sqlc.narg(config_summary), '{}'::jsonb)
+)
+RETURNING *;
+
+-- name: GetActiveAutopilotRuleVersion :one
+-- The active version is the newest published row for the autopilot. Scoped by
+-- workspace_id per the workspace query rule; autopilot_id is globally unique so the
+-- workspace filter is a guard, not the selector.
+SELECT * FROM autopilot_rule_version
+WHERE workspace_id = $1 AND autopilot_id = $2
+ORDER BY created_at DESC
+LIMIT 1;
+
-- =====================
-- Autopilot Trigger CRUD
-- =====================
@@ -94,14 +122,34 @@ WHERE id = $1;
-- name: CreateAutopilotTrigger :one
INSERT INTO autopilot_trigger (
autopilot_id, kind, enabled, cron_expression, timezone,
- next_run_at, webhook_token, label, provider, event_filters
+ next_run_at, webhook_token, label, provider, event_filters,
+ published_by_type, published_by_id
) VALUES (
$1, $2, $3, sqlc.narg('cron_expression'), sqlc.narg('timezone'),
sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label'),
COALESCE(sqlc.narg('provider')::text, 'generic'),
- sqlc.narg('event_filters')
+ sqlc.narg('event_filters'),
+ sqlc.narg('published_by_type'), sqlc.narg('published_by_id')
) RETURNING *;
+-- name: SetAutopilotTriggerPublisher :exec
+-- Re-stamp a single trigger's responsible publisher after a substantive edit of
+-- THAT trigger (cron / filter / enabled / webhook security). Future runs it fires
+-- become accountable to this member (MUL-4302 trigger_owner transfer).
+UPDATE autopilot_trigger
+SET published_by_type = $2, published_by_id = $3, updated_at = now()
+WHERE id = $1;
+
+-- name: SetAutopilotTriggerPublishersByAutopilot :exec
+-- Re-stamp ALL of an autopilot's triggers' responsible publisher after a substantive
+-- AUTOPILOT-level edit (target / instructions / assignee / execution-mode / enable).
+-- Such a change governs every trigger's future runs, so responsibility transfers to
+-- the editing member for all of them; a per-trigger edit uses the single-trigger
+-- variant so it never reassigns another trigger (MUL-4302).
+UPDATE autopilot_trigger
+SET published_by_type = $2, published_by_id = $3, updated_at = now()
+WHERE autopilot_id = $1;
+
-- name: UpdateAutopilotTrigger :one
UPDATE autopilot_trigger SET
enabled = COALESCE(sqlc.narg('enabled')::boolean, enabled),
@@ -339,8 +387,31 @@ ORDER BY t.id;
-- =====================
-- name: CreateAutopilotTask :one
-INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
-VALUES ($1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary))
+-- run_only autopilot dispatch. Attribution depends on the trigger:
+-- * schedule / webhook / api: no human authorized the run, so originator_user_id
+-- stays NULL and accountable_user_id is the rule_owner (the publisher of the
+-- autopilot's active rule version), with rule_version_id recording the snapshot
+-- (MUL-4302 §3.4) — the accountable-diverges-from-originator case.
+-- * manual: a member clicked "run now", a direct human action, so originator and
+-- accountable are BOTH that member (originator_source='direct_human'); no rule
+-- version is involved (MUL-4302 §4).
+-- When no version/publisher resolves on the non-manual path, the caller passes NULL
+-- accountable + originator_source='unattributed' so the row is still not a
+-- NULL-source bypass (MUL-4302 §2).
+INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary,
+ originator_user_id, accountable_user_id, rule_version_id,
+ originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+)
+VALUES (
+ $1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary),
+ sqlc.narg(originator_user_id),
+ sqlc.narg(accountable_user_id),
+ sqlc.narg(rule_version_id),
+ sqlc.narg(originator_source),
+ sqlc.narg(trigger_evidence_kind),
+ sqlc.narg(trigger_evidence_ref_id)
+)
RETURNING *;
-- name: GetAutopilotTaskByRun :one
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index cdf09c7119..fef86178a8 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -197,17 +197,24 @@ SELECT * FROM chat_message
WHERE id = $1;
-- name: CreateChatTask :one
+-- The chat sender (initiator) is a direct_human originator and accountable;
+-- attribution provenance is stamped so this path is not a NULL-source enqueue
+-- bypass (MUL-4302 §2).
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
- initiator_user_id, originator_user_id, force_fresh_session, runtime_mcp_overlay,
- runtime_connected_apps
+ initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
+ runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id
)
VALUES (
$1, $2, NULL, 'queued', $3, $4, $5,
sqlc.narg(originator_user_id),
+ sqlc.narg(accountable_user_id),
COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),
sqlc.narg(runtime_mcp_overlay),
- sqlc.narg(runtime_connected_apps)
+ sqlc.narg(runtime_connected_apps),
+ sqlc.narg(originator_source),
+ sqlc.narg(trigger_evidence_kind),
+ sqlc.narg(trigger_evidence_ref_id)
)
RETURNING *;
diff --git a/server/pkg/db/queries/user.sql b/server/pkg/db/queries/user.sql
index 7d24d58a64..eef17ad013 100644
--- a/server/pkg/db/queries/user.sql
+++ b/server/pkg/db/queries/user.sql
@@ -6,6 +6,13 @@ WHERE id = $1;
SELECT * FROM "user"
WHERE email = $1;
+-- name: GetUsersByIDs :many
+-- Batch lookup from the GLOBAL user table (not gated on membership, so departed
+-- members still render). Used to enrich attribution initiator / originator refs on
+-- task responses without an N+1 (MUL-4302 §9). Returns only the display fields.
+SELECT id, name, email, avatar_url FROM "user"
+WHERE id = ANY(@ids::uuid[]);
+
-- name: CreateUser :one
INSERT INTO "user" (name, email, avatar_url)
VALUES ($1, $2, $3)
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index e04837730b..926dd2abde 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -1,7 +1,7 @@
-- name: ListWorkspaces :many
SELECT w.id, w.name, w.slug, w.description, w.settings,
w.created_at, w.updated_at, w.context, w.repos,
- w.issue_prefix, w.issue_counter, w.avatar_url
+ w.issue_prefix, w.issue_counter, w.avatar_url, w.attribution_fail_closed
FROM member m
JOIN workspace w ON w.id = m.workspace_id
WHERE m.user_id = $1
@@ -33,6 +33,12 @@ WHERE id = $1;
SELECT * FROM workspace
WHERE slug = $1;
+-- name: GetWorkspaceAttributionFailClosed :one
+-- Lean read of the fail-closed attribution policy for the enqueue hot path
+-- (MUL-4302 §3.5), avoiding a full workspace-row fetch.
+SELECT attribution_fail_closed FROM workspace
+WHERE id = $1;
+
-- name: CreateWorkspace :one
INSERT INTO workspace (name, slug, description, context, issue_prefix)
VALUES ($1, $2, $3, $4, $5)