Skip to content

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

Go

feat(docs): @mention agents in doc discussions (MUL-9933) (#11295)

Bohan Jiang76be143643be
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0ad59147b2..57e01a39bc 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -11,6 +11,7 @@ import {
DocCommentSchema,
DocCommentListSchema,
DocCollabTicketSchema,
+ DocTaskRunListSchema,
} from "../docs/schemas";
import type {
Doc,
@@ -22,6 +23,7 @@ import type {
DocTree,
DocVersion,
DocCollabTicket,
+ DocTaskRun,
CreateDocRequest,
UpdateDocRequest,
CreateDocFolderRequest,
@@ -1100,6 +1102,14 @@ export class ApiClient {
async deleteDocComment(docId: string, commentId: string): Promise<void> {
await this.fetch(`/api/docs/${docId}/comments/${commentId}`, { method: "DELETE" });
}
+ async listDocTaskRuns(docId: string): Promise<DocTaskRun[]> {
+ return parseWithFallback(
+ await this.fetch<unknown>(`/api/docs/${docId}/task-runs`),
+ DocTaskRunListSchema,
+ { tasks: [] },
+ { endpoint: "GET /api/docs/{id}/task-runs" },
+ ).tasks;
+ }
async listDocVersions(id: string): Promise<DocVersion[]> {
return parseWithFallback(
await this.fetch<unknown>(`/api/docs/${id}/versions`),
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 089154dfb4..9167e7620c 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2540,6 +2540,8 @@ export const AgentTaskSchema = z.object({
autopilot_run_id: z.string().optional(),
squad_id: z.string().optional().catch(undefined),
is_leader_task: z.boolean().optional().catch(undefined),
+ doc_id: z.string().optional().catch(undefined),
+ doc_thread_id: z.string().optional().catch(undefined),
parent_task_id: z.string().optional(),
attempt: z.number().optional(),
trigger_comment_id: z.string().optional(),
diff --git a/packages/core/docs/client.test.ts b/packages/core/docs/client.test.ts
index a2156e01f4..fd720ab4e8 100644
--- a/packages/core/docs/client.test.ts
+++ b/packages/core/docs/client.test.ts
@@ -100,6 +100,37 @@ describe("knowledge base client", () => {
expect(await client.listDocVersions("d1")).toEqual([]);
});
+ it("reads which discussion an agent's version came from, and tolerates a bad link", async () => {
+ const client = new ApiClient("https://api.example.test");
+ const version = {
+ doc_id: "d1", number: 2, title: "Runbook", author_type: "agent", author_id: "a1",
+ created_at: "2026-11-23T00:00:00Z", updated_at: "2026-11-23T00:00:00Z",
+ };
+ respond({ versions: [
+ { ...version, doc_thread_id: "c1", doc_thread_quote: "ship on Friday" },
+ { ...version, number: 1, doc_thread_id: 7 },
+ ] });
+ const [fromDiscussion, malformed] = await client.listDocVersions("d1");
+ expect(fromDiscussion).toMatchObject({ docThreadId: "c1", docThreadQuote: "ship on Friday" });
+ expect(malformed).toMatchObject({ number: 1, docThreadId: null, docThreadQuote: null });
+ });
+
+ it("lists a doc's discussion runs and falls back to none on a malformed response", async () => {
+ const client = new ApiClient("https://api.example.test");
+ const fetchMock = respond({ tasks: [
+ { id: "t1", agent_id: "a1", status: "running", doc_thread_id: "c1", error: null, can_cancel: true },
+ { id: "t2", status: 3 },
+ { id: "t3", agent_id: "a2", status: "failed", doc_thread_id: "c1", can_cancel: "yes" },
+ ] });
+ expect(await client.listDocTaskRuns("d1")).toMatchObject([
+ { id: "t1", agentId: "a1", docThreadId: "c1", canCancel: true },
+ { id: "t3", canCancel: false, error: null },
+ ]);
+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/api/docs/d1/task-runs");
+ respond({ tasks: "nope" });
+ expect(await client.listDocTaskRuns("d1")).toEqual([]);
+ });
+
it("sends the base revision and surfaces a stale write as a revision conflict", async () => {
const fetchMock = respond(
{
diff --git a/packages/core/docs/mutations.ts b/packages/core/docs/mutations.ts
index 3b7e6f44c8..55fea47bea 100644
--- a/packages/core/docs/mutations.ts
+++ b/packages/core/docs/mutations.ts
@@ -141,9 +141,25 @@ function useDocCommentsInvalidate() {
export function useCreateDocComment(docId: string) {
const invalidate = useDocCommentsInvalidate();
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
return useMutation({
mutationFn: (data: CreateDocCommentRequest) => api.createDocComment(docId, data),
- onSettled: () => invalidate(docId),
+ onSettled: () => {
+ invalidate(docId);
+ // A comment can start, or fold into, an agent's run.
+ qc.invalidateQueries({ queryKey: docKeys.tasks(wsId, docId) });
+ },
+ });
+}
+
+/** Stops an agent's run on one of the doc's discussions. */
+export function useCancelDocTaskRun(docId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (taskId: string) => api.cancelTaskById(taskId),
+ onSettled: () => qc.invalidateQueries({ queryKey: docKeys.tasks(wsId, docId) }),
});
}
diff --git a/packages/core/docs/queries.ts b/packages/core/docs/queries.ts
index 0025ea59c2..2c4ea6e174 100644
--- a/packages/core/docs/queries.ts
+++ b/packages/core/docs/queries.ts
@@ -12,8 +12,18 @@ export const docKeys = {
[...docKeys.all(wsId), "version", id, number] as const,
comments: (wsId: string, id: string) =>
[...docKeys.all(wsId), "comments", id] as const,
+ tasks: (wsId: string, id: string) =>
+ [...docKeys.all(wsId), "tasks", id] as const,
};
+/** Agent runs started from the doc's discussions, newest first. */
+export function docTaskRunsOptions(wsId: string, docId: string) {
+ return queryOptions({
+ queryKey: docKeys.tasks(wsId, docId),
+ queryFn: () => api.listDocTaskRuns(docId),
+ });
+}
+
export function docCommentsOptions(wsId: string, docId: string) {
return queryOptions({
queryKey: docKeys.comments(wsId, docId),
diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.ts
index 09ef11e779..9da746f722 100644
--- a/packages/core/docs/schemas.ts
+++ b/packages/core/docs/schemas.ts
@@ -123,6 +123,41 @@ export const DocCommentListSchema = z.object({
}),
),
});
+const cancelledBy = z.object({ type: z.string(), id: z.string().optional(), name: z.string().optional() });
+export const DocTaskRunSchema = z
+ .object({
+ id: z.string().min(1),
+ agent_id: z.string(),
+ doc_thread_id: z.string(),
+ status: z.string(),
+ failure_reason: z.string().default(""),
+ error: z.string().nullable().catch(null).default(null),
+ cancelled_by: cancelledBy.optional().catch(undefined),
+ created_at: z.string().default(""),
+ completed_at: z.string().nullable().catch(null).default(null),
+ can_cancel: z.boolean().catch(false).default(false),
+ })
+ .transform((r) => ({
+ id: r.id,
+ agentId: r.agent_id,
+ docThreadId: r.doc_thread_id,
+ status: r.status,
+ failureReason: r.failure_reason,
+ error: r.error,
+ cancelledBy: r.cancelled_by,
+ createdAt: r.created_at,
+ completedAt: r.completed_at,
+ canCancel: r.can_cancel,
+ }));
+// One unreadable run is dropped instead of hiding every discussion's status.
+export const DocTaskRunListSchema = z.object({
+ tasks: z.array(z.unknown()).transform((rows) =>
+ rows.flatMap((row) => {
+ const run = DocTaskRunSchema.safeParse(row);
+ return run.success ? [run.data] : [];
+ }),
+ ),
+});
export const DocVersionSchema = z
.object({
doc_id: z.string(),
@@ -135,6 +170,8 @@ export const DocVersionSchema = z
action_ref: z.number().nullable().default(null),
task_id: z.string().nullable().default(null),
issue_id: z.string().nullable().default(null),
+ doc_thread_id: z.string().nullable().catch(null).default(null),
+ doc_thread_quote: z.string().nullable().catch(null).default(null),
contributors: z
.array(z.object({ type: actor, id: z.string() }))
.catch([])
@@ -154,6 +191,8 @@ export const DocVersionSchema = z
actionRef: d.action_ref,
taskId: d.task_id,
issueId: d.issue_id,
+ docThreadId: d.doc_thread_id,
+ docThreadQuote: d.doc_thread_quote,
contributors: d.contributors,
createdAt: d.created_at,
updatedAt: d.updated_at,
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 059bd793a0..5aba488fad 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1237,10 +1237,16 @@ export function useRealtimeSync(
if (specificEvents.has(msg.type)) return;
const prefix = msg.type.split(":")[0] ?? "";
if (prefix === "task" && msg.type !== "task:progress") {
- const payload = msg.payload as { issue_id?: unknown };
+ const payload = msg.payload as { issue_id?: unknown; doc_id?: unknown };
const issueId = typeof payload?.issue_id === "string" && payload.issue_id ? payload.issue_id : null;
- // Debounce per issue so simultaneous runs cannot erase each other's refresh.
- debouncedRefresh(`issue-task:${issueId ?? "all"}`, () => {
+ const docId = typeof payload?.doc_id === "string" && payload.doc_id ? payload.doc_id : null;
+ const wsId = getCurrentWsId();
+ // A doc discussion run only changes that doc's run status.
+ if (docId) {
+ if (wsId) debouncedRefresh(`doc-task:${docId}`, () => {
+ qc.invalidateQueries({ queryKey: docKeys.tasks(wsId, docId) });
+ });
+ } else debouncedRefresh(`issue-task:${issueId ?? "all"}`, () => {
qc.invalidateQueries({ queryKey: issueId ? issueKeys.tasks(issueId) : issueKeys.tasksAll() });
// Events don't carry the ancestor chain needed to scope subtree projections.
if (issueId) qc.invalidateQueries({ queryKey: issueKeys.tasksAll(), predicate: (q) => q.queryKey[3] === "subtree" });
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 71b6028fa8..f91b6795c2 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -368,6 +368,10 @@ export interface AgentTask {
squad_id?: string;
/** True when this task runs the agent as a squad leader. */
is_leader_task?: boolean;
+ /** Non-empty when an agent was asked for in a doc discussion. */
+ doc_id?: string;
+ /** The doc discussion (its first comment's id) the run answers. */
+ doc_thread_id?: string;
/** Set when this task was created as an auto-retry of a parent task. */
parent_task_id?: string;
/** 1-based attempt counter; >1 means this is a retry. */
@@ -409,7 +413,7 @@ export interface AgentTask {
* remains quick_create after its result issue is linked, so consumers can
* distinguish creation work from later direct runs on that issue.
*/
- kind?: "comment" | "autopilot" | "chat" | "quick_create" | "direct";
+ kind?: "comment" | "autopilot" | "chat" | "quick_create" | "doc_comment" | "direct";
/**
* Local working directory pinned for this task by the daemon. Empty until
* the daemon reports a work_dir (typically once execution starts). This is
diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.ts
index 0ee9f97d65..de84f0e596 100644
--- a/packages/core/types/doc.ts
+++ b/packages/core/types/doc.ts
@@ -66,6 +66,22 @@ export interface DocTree {
folders: DocFolder[];
docs: DocSummary[];
}
+/** An agent's run on a doc discussion, as the discussion shows it. */
+export interface DocTaskRun {
+ id: string;
+ agentId: string;
+ docThreadId: string;
+ /** Open wire value; the task statuses (queued, running, failed, ...). */
+ status: string;
+ failureReason: string;
+ /** Only for viewers who can see the agent. */
+ error: string | null;
+ cancelledBy?: { type: string; id?: string; name?: string };
+ createdAt: string;
+ completedAt: string | null;
+ /** The viewer can see the agent and the run is still active. */
+ canCancel: boolean;
+}
export interface DocVersion {
docId: string;
number: number;
@@ -77,6 +93,10 @@ export interface DocVersion {
actionRef: number | null;
taskId: string | null;
issueId: string | null;
+ /** The discussion an agent was answering when it saved this version, with
+ * the text that discussion is about; null otherwise or once deleted. */
+ docThreadId: string | null;
+ docThreadQuote: string | null;
/** Everyone whose edits the version carries. Empty for versions saved
* before live co-editing; the author is the one then. */
contributors: { type: DocAuthorType; id: string }[];
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
index 200e52a47b..fe0baa613a 100644
--- a/packages/views/agents/components/tabs/activity-tab.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -5,6 +5,7 @@ import { forwardRef, memo, useCallback, useMemo, useState } from "react";
import {
ArrowUpRight,
CircleHelp,
+ FileText,
Hash,
MessageSquare,
Workflow,
@@ -520,7 +521,9 @@ function useTaskRowModel(task: AgentTask) {
? t(($) => $.tab_body.activity.source_chat_session)
: task.autopilot_run_id
? t(($) => $.tab_body.activity.source_autopilot_run)
- : t(($) => $.tab_body.activity.source_untracked)
+ : task.doc_id
+ ? t(($) => $.tab_body.activity.source_doc_comment)
+ : t(($) => $.tab_body.activity.source_untracked)
: null;
const SourceIcon = hasIssue
? Hash
@@ -528,14 +531,18 @@ function useTaskRowModel(task: AgentTask) {
? MessageSquare
: task.autopilot_run_id
? Workflow
- : CircleHelp;
+ : task.doc_id
+ ? FileText
+ : CircleHelp;
const sourceLabel = hasIssue
? t(($) => $.tab_body.activity.source_issue)
: task.chat_session_id
? t(($) => $.tab_body.activity.source_chat)
: task.autopilot_run_id
? t(($) => $.tab_body.activity.source_autopilot)
- : t(($) => $.tab_body.activity.source_untracked);
+ : task.doc_id
+ ? t(($) => $.tab_body.activity.source_doc)
+ : t(($) => $.tab_body.activity.source_untracked);
const title =
issue?.title ??
(hasIssue
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index bf51443265..a86aa8a4e7 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -852,6 +852,8 @@ export function AgentTranscriptDialog({
? t(($) => $.transcript.trigger_chat)
: task.kind === "quick_create"
? t(($) => $.transcript.trigger_quick_create)
+ : task.kind === "doc_comment" || task.doc_id
+ ? t(($) => $.transcript.trigger_doc_comment)
: task.kind === "direct"
? t(($) => $.transcript.trigger_direct)
: t(($) => $.transcript.trigger_initial);
diff --git a/packages/views/docs/components/doc-comments-panel.tsx b/packages/views/docs/components/doc-comments-panel.tsx
index 472f5a28a6..1e54e6b96a 100644
--- a/packages/views/docs/components/doc-comments-panel.tsx
+++ b/packages/views/docs/components/doc-comments-panel.tsx
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
+import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useReducedMotion } from "@multica/core/appearance";
import { AlertTriangle, Check, MessageSquare, RotateCcw, Trash2, X } from "@multica/ui/icons";
@@ -9,16 +10,19 @@ import { UI_EASE_OUT } from "@multica/ui/lib/motion";
import { cn } from "@multica/ui/lib/utils";
import { useAuthStore } from "@multica/core/auth";
import {
+ docTaskRunsOptions,
useCreateDocComment,
useDeleteDocComment,
useSetDocCommentResolved,
} from "@multica/core/docs";
-import type { DocComment } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { DocComment, DocTaskRun } from "@multica/core/types";
import { useActorName } from "@multica/core/workspace/hooks";
import { ContentEditor, ReadonlyContent, type ContentEditorRef } from "../../editor";
import { ActorAvatar } from "../../common/actor-avatar";
import { useT, useTimeAgo } from "../../i18n";
import type { DocAnchor } from "./doc-comment-anchors";
+import { DocThreadRun, docThreadRuns } from "./doc-thread-runs";
export interface DocThread {
root: DocComment;
@@ -76,6 +80,7 @@ function Composer({
defaultValue=""
placeholder={placeholder}
mentionHideGuests
+ mentionHideSquads
onUpdate={(md) => setEmpty(!md.trim())}
onSubmit={submit}
debounceMs={0}
@@ -156,6 +161,7 @@ function Quote({ text, missing }: { text: string; missing?: boolean }) {
function ThreadCard({
docId,
thread,
+ runs,
active,
missing,
onActivate,
@@ -163,6 +169,8 @@ function ThreadCard({
}: {
docId: string;
thread: DocThread;
+ /** Agent runs to show on this discussion; see docThreadRuns. */
+ runs: DocTaskRun[];
active: boolean;
missing: boolean;
onActivate: () => void;
@@ -210,6 +218,9 @@ function ThreadCard({
{[thread.root, ...thread.replies].map((c) => (
<Message key={c.id} comment={c} onDelete={own(c) ? () => void del(c) : undefined} />
))}
+ {runs.map((run) => (
+ <DocThreadRun key={run.id} docId={docId} run={run} />
+ ))}
{resolved ? (
<div className="mt-2 flex items-center gap-2 border-t pt-2 text-caption text-muted-foreground">
{t(($) => $.comments.resolved_by, {
@@ -275,6 +286,8 @@ function ThreadCard({
);
}
+const NO_RUNS: DocTaskRun[] = [];
+
/**
* The doc's discussions, beside the text. Open and resolved discussions sit
* on separate tabs; a discussion being started from a selection appears on
@@ -303,6 +316,8 @@ export function DocCommentsPanel({
}) {
const { t } = useT("docs");
const create = useCreateDocComment(docId);
+ const wsId = useWorkspaceId();
+ const { data: runs = NO_RUNS } = useQuery(docTaskRunsOptions(wsId, docId));
const [tab, setTab] = useState<"open" | "resolved">("open");
const open = threads.filter((th) => !th.root.resolvedAt);
const resolved = threads.filter((th) => th.root.resolvedAt);
@@ -372,6 +387,7 @@ export function DocCommentsPanel({
key={thread.root.id}
docId={docId}
thread={thread}
+ runs={docThreadRuns(runs, thread.root.id)}
active={thread.root.id === activeId}
missing={missing.has(thread.root.id)}
onActivate={() => onActivate(thread.root.id)}
diff --git a/packages/views/docs/components/doc-history-page.tsx b/packages/views/docs/components/doc-history-page.tsx
index 1dede866af..d1f2590b5a 100644
--- a/packages/views/docs/components/doc-history-page.tsx
+++ b/packages/views/docs/components/doc-history-page.tsx
@@ -18,7 +18,7 @@ import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { ReadonlyContent } from "../../editor";
import { BreadcrumbHeader } from "../../layout/breadcrumb-header";
-import { useNavigation } from "../../navigation";
+import { AppLink, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { DocNotFound } from "./doc-not-found";
import { DocsGate } from "./docs-gate";
@@ -42,6 +42,7 @@ function DocHistoryPageContent({ docId }: { docId: string }) {
const versions = useQuery(docVersionsOptions(wsId, docId));
const [selected, setSelected] = useState<number | null>(null);
const number = selected ?? versions.data?.[0]?.number ?? 1;
+ const selectedVersion = versions.data?.find((v) => v.number === number);
const version = useQuery({
...docVersionOptions(wsId, docId, number),
enabled: !!versions.data?.length,
@@ -114,6 +115,11 @@ function DocHistoryPageContent({ docId }: { docId: string }) {
{v.message}
</span>
)}
+ {v.docThreadId && (
+ <span className="block truncate text-caption text-muted-foreground">
+ {t(($) => $.history.from_discussion, { quote: v.docThreadQuote ?? "" })}
+ </span>
+ )}
<span className="block text-caption text-muted-foreground">
{new Date(v.updatedAt).toLocaleString()}
</span>
@@ -153,6 +159,14 @@ function DocHistoryPageContent({ docId }: { docId: string }) {
{t(($) => $.history.restore)}
</Button>
</div>
+ {selectedVersion?.docThreadId && (
+ <AppLink
+ href={`${p.docDetail(docId)}?thread=${encodeURIComponent(selectedVersion.docThreadId)}`}
+ className="-mt-4 mb-6 block truncate text-caption text-muted-foreground hover:text-foreground hover:underline"
+ >
+ {t(($) => $.history.from_discussion, { quote: selectedVersion.docThreadQuote ?? "" })}
+ </AppLink>
+ )}
<ReadonlyContent content={version.data.content ?? ""} />
</motion.div>
) : (
diff --git a/packages/views/docs/components/doc-thread-runs.test.ts b/packages/views/docs/components/doc-thread-runs.test.ts
new file mode 100644
index 0000000000..9ea1d44576
--- /dev/null
+++ b/packages/views/docs/components/doc-thread-runs.test.ts
@@ -0,0 +1,38 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { DocTaskRun } from "@multica/core/types";
+import { docThreadRuns } from "./doc-thread-runs";
+
+function run(id: string, agentId: string, docThreadId: string, status: string): DocTaskRun {
+ return { id, agentId, docThreadId, status, failureReason: "", error: null, createdAt: "", completedAt: null, canCancel: true };
+}
+
+describe("docThreadRuns", () => {
+ it("shows each agent's latest run on the discussion while it works or after it failed", () => {
+ // Newest first, as the server lists them.
+ const runs = [
+ run("t5", "writer", "c1", "running"),
+ run("t4", "reviewer", "c1", "failed"),
+ run("t3", "other", "c2", "queued"),
+ run("t2", "writer", "c1", "failed"),
+ run("t1", "editor", "c1", "completed"),
+ ];
+ expect(docThreadRuns(runs, "c1").map((r) => r.id)).toEqual(["t4", "t5"]);
+ expect(docThreadRuns(runs, "c2").map((r) => r.id)).toEqual(["t3"]);
+ });
+
+ it("keeps a working run visible when a follow-up queues behind it", () => {
+ const runs = [run("t2", "writer", "c1", "queued"), run("t1", "writer", "c1", "running")];
+ expect(docThreadRuns(runs, "c1").map((r) => r.id)).toEqual(["t1", "t2"]);
+ });
+
+ it("keeps a retry waiting for the runtime visible, in place of the failure it retries", () => {
+ const runs = [run("t2", "writer", "c1", "deferred"), run("t1", "writer", "c1", "failed")];
+ expect(docThreadRuns(runs, "c1").map((r) => r.id)).toEqual(["t2"]);
+ });
+
+ it("drops a failure once a newer run of the same agent finished", () => {
+ const runs = [run("t2", "writer", "c1", "completed"), run("t1", "writer", "c1", "failed")];
+ expect(docThreadRuns(runs, "c1")).toEqual([]);
+ });
+});
diff --git a/packages/views/docs/components/doc-thread-runs.test.tsx b/packages/views/docs/components/doc-thread-runs.test.tsx
new file mode 100644
index 0000000000..a6dbcd5c14
--- /dev/null
+++ b/packages/views/docs/components/doc-thread-runs.test.tsx
@@ -0,0 +1,68 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { DocTaskRun } from "@multica/core/types";
+import { DocThreadRun } from "./doc-thread-runs";
+import enAgents from "../../locales/en/agents.json";
+import enDocs from "../../locales/en/docs.json";
+import enIssues from "../../locales/en/issues.json";
+
+const { apiMock } = vi.hoisted(() => ({ apiMock: { cancelTaskById: vi.fn() } }));
+vi.mock("@multica/core/api", () => ({ api: apiMock }));
+vi.mock("@multica/core/hooks", async (original) => ({
+ ...await original<object>(), useWorkspaceId: () => "ws-1",
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Writer" }),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function run(status: string, extra: Partial<DocTaskRun> = {}): DocTaskRun {
+ return {
+ id: "t1", agentId: "a1", docThreadId: "c1", status, failureReason: "", error: null,
+ createdAt: "", completedAt: null, canCancel: true, ...extra,
+ };
+}
+
+function mount(task: DocTaskRun) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={{ en: { agents: enAgents, docs: enDocs, issues: enIssues } }}>
+ <DocThreadRun docId="d1" run={task} />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+it("stops a working run after confirmation", async () => {
+ apiMock.cancelTaskById.mockResolvedValue({});
+ mount(run("running"));
+ expect(screen.getByText("Writer")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Stop run" }));
+ await waitFor(() => expect(apiMock.cancelTaskById).toHaveBeenCalledWith("t1"));
+});
+
+it("offers no Stop to a viewer who cannot see the agent", () => {
+ mount(run("running", { canCancel: false }));
+ expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
+});
+
+it("shows how a failed run ended, with no way to stop it", () => {
+ mount(run("failed", { failureReason: "timeout", error: "deadline exceeded" }));
+ expect(screen.getByRole("status").textContent).not.toBe("");
+ expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
+});
+
+it("shows a retry waiting for the runtime as stoppable", () => {
+ mount(run("deferred"));
+ expect(screen.getByText("Waiting for the runtime to come back online")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Stop" })).toBeTruthy();
+});
diff --git a/packages/views/docs/components/doc-thread-runs.tsx b/packages/views/docs/components/doc-thread-runs.tsx
new file mode 100644
index 0000000000..f826ec0bcb
--- /dev/null
+++ b/packages/views/docs/components/doc-thread-runs.tsx
@@ -0,0 +1,107 @@
+"use client";
+import { useState } from "react";
+import { toast } from "sonner";
+import { AlertCircle, Loader2, Square } from "@multica/ui/icons";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";
+import { useCancelDocTaskRun } from "@multica/core/docs";
+import type { AgentTask, DocTaskRun } from "@multica/core/types";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { redactSecrets } from "../../common/task-transcript/redact";
+import { runOutcomeLabel } from "../../agents/components/tabs/task-failure";
+import { useStatusLabel } from "../../issues/components/task-run-labels";
+import { TerminateTaskConfirmDialog } from "../../issues/components/terminate-task-confirm-dialog";
+import { useT } from "../../i18n";
+
+// Deferred is a retry waiting for the agent's runtime to reconnect: it has
+// not run yet and can still be stopped.
+const ACTIVE_STATUSES = new Set(["queued", "dispatched", "waiting_local_directory", "running", "deferred"]);
+
+export function isActiveDocRun(run: DocTaskRun): boolean {
+ return ACTIVE_STATUSES.has(run.status);
+}
+
+/**
+ * The runs a discussion shows, oldest first: every run still queued or
+ * working, each with its own way to stop it, and an agent's failed run while
+ * it is that agent's latest on the discussion. A finished run shows as its
+ * reply; a stopped one shows nothing. `runs` is newest first.
+ */
+export function docThreadRuns(runs: readonly DocTaskRun[], threadId: string): DocTaskRun[] {
+ const seen = new Set<string>();
+ const shown: DocTaskRun[] = [];
+ for (const run of runs) {
+ if (run.docThreadId !== threadId) continue;
+ const latest = !seen.has(run.agentId);
+ seen.add(run.agentId);
+ if (isActiveDocRun(run) || (latest && run.status === "failed")) shown.push(run);
+ }
+ return shown.reverse();
+}
+
+export function DocThreadRun({ docId, run }: { docId: string; run: DocTaskRun }) {
+ const { t } = useT("issues");
+ const { t: tAgents } = useT("agents");
+ const { t: tDocs } = useT("docs");
+ const { getActorName } = useActorName();
+ const cancel = useCancelDocTaskRun(docId);
+ const [confirmStop, setConfirmStop] = useState(false);
+ const name = getActorName("agent", run.agentId);
+ const status = useStatusLabel(run.status as AgentTask["status"]);
+ const active = isActiveDocRun(run);
+ const outcome = { status: run.status, error: run.error, failure_reason: run.failureReason, cancelled_by: run.cancelledBy };
+ const label = run.status === "deferred"
+ ? tDocs(($) => $.comments.run_waiting_runtime)
+ : active ? status : (runOutcomeLabel(outcome, tAgents) ?? status);
+ const error = !active && run.error?.trim() ? redactSecrets(run.error.trim()) : "";
+ const stopping = cancel.isPending || cancel.isSuccess;
+ return (
+ <div className="mt-2 flex items-center gap-2 text-caption" data-run-id={run.id}>
+ <ActorAvatar actorType="agent" actorId={run.agentId} size="sm" />
+ <span className="truncate font-medium text-foreground">{name}</span>
+ <span role="status" className="flex min-w-0 items-center gap-1 text-muted-foreground">
+ {active ? (
+ <Loader2 className="size-3.5 shrink-0 animate-spin motion-reduce:animate-none" />
+ ) : (
+ <AlertCircle className="size-3.5 shrink-0 text-destructive" />
+ )}
+ {error && error !== label ? (
+ <Tooltip>
+ <TooltipTrigger render={<span className="truncate">{label}</span>} />
+ <TooltipContent side="top" className="flex-col items-start">
+ <span>{label}</span>
+ <span className="break-all font-mono text-muted-foreground">{error}</span>
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="truncate">{label}</span>
+ )}
+ </span>
+ {active && run.canCancel && (
+ <IconButton
+ size="icon-xs"
+ variant="ghost"
+ className="ml-auto text-muted-foreground"
+ label={stopping ? t(($) => $.inline_run.stopping) : t(($) => $.inline_run.stop)}
+ disabled={stopping}
+ onClick={() => setConfirmStop(true)}
+ >
+ {stopping ? (
+ <Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" />
+ ) : (
+ <Square className="size-3.5" />
+ )}
+ </IconButton>
+ )}
+ <TerminateTaskConfirmDialog
+ open={confirmStop}
+ onOpenChange={setConfirmStop}
+ showRunningNote={run.status !== "queued"}
+ onConfirm={() => {
+ cancel.mutateAsync(run.id).catch(() => toast.error(t(($) => $.execution_log.cancel_failed)));
+ }}
+ />
+ </div>
+ );
+}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 9048d3c806..48763287b0 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -204,6 +204,8 @@ interface ContentEditorBaseProps {
mentionContextItems?: MentionItem[];
/** Leave guests out of the @ list, for places guests cannot open (docs). */
mentionHideGuests?: boolean;
+ /** Leave squads out of the @ list, for places a squad cannot be asked (doc discussions). */
+ mentionHideSquads?: boolean;
/** Enable the `/` command picker. Defaults false. */
enableSlashCommands?: boolean;
/**
@@ -415,6 +417,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
mentionMode = "default",
mentionContextItems,
mentionHideGuests = false,
+ mentionHideSquads = false,
enableSlashCommands = false,
slashCommandMode = "skill",
showBlockHandles = false,
@@ -639,6 +642,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
mentionMode,
getMentionContextItems: () => mentionContextItemsRef.current,
mentionHideGuests,
+ mentionHideSquads,
enableSlashCommands,
slashCommandMode,
quickActionMenu: {
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 0fb097f469..d0becaba88 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -129,6 +129,7 @@ export interface EditorExtensionsOptions {
mentionMode?: "default" | "context";
getMentionContextItems?: () => MentionItem[];
mentionHideGuests?: boolean;
+ mentionHideSquads?: boolean;
/** When true, attach the `/` picker. Default false. */
enableSlashCommands?: boolean;
/**
@@ -227,7 +228,7 @@ export function createEditorExtensions(
...(options.disableMentions
? { suggestion: { allow: () => false } }
: options.queryClient
- ? { suggestion: createMentionSuggestion(options.queryClient, { mode: options.mentionMode, getContextItems: options.getMentionContextItems, hideGuests: options.mentionHideGuests }) }
+ ? { suggestion: createMentionSuggestion(options.queryClient, { mode: options.mentionMode, getContextItems: options.getMentionContextItems, hideGuests: options.mentionHideGuests, hideSquads: options.mentionHideSquads }) }
: {}),
}),
// Linear-style bare identifier → issue mention. Attached only when a
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index 946a058d7d..e0789fdcaf 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -500,6 +500,17 @@ describe("createMentionSuggestion", () => {
expect(members(createMentionSuggestion(qc, { hideGuests: true }))).toEqual(["u1"]);
});
+ it("leaves squads out where a squad cannot be asked", () => {
+ const qc = fakeQc({
+ squads: [{ id: "s1", name: "Design squad", leader_id: "a1", archived_at: null }],
+ });
+ const squads = (config: ReturnType<typeof createMentionSuggestion>) =>
+ (config.items!(itemArgs("design")) as MentionItem[]).filter((i) => i.type === "squad").map((i) => i.id);
+
+ expect(squads(createMentionSuggestion(qc))).toEqual(["s1"]);
+ expect(squads(createMentionSuggestion(qc, { hideSquads: true }))).toEqual([]);
+ });
+
it("matches cached live projects synchronously and leaves archived ones to the server", () => {
const qc = fakeQc({
projects: [
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 1fedb5b3ba..4f518aff15 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -839,6 +839,8 @@ interface MentionSuggestionOptions {
getContextItems?: () => MentionItem[];
/** Leave guests out of the member list, where the mention leads somewhere they cannot open. */
hideGuests?: boolean;
+ /** Leave squads out, where a squad cannot be asked (doc discussions). */
+ hideSquads?: boolean;
}
export function createMentionSuggestion(
@@ -920,6 +922,7 @@ export function createMentionSuggestion(
.filter(
(s) =>
!guest &&
+ !options.hideSquads &&
!s.archived_at &&
(s.name.toLowerCase().includes(q) || matchesPinyin(s.name, q)),
)
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index bce7cacbd3..884622a7cf 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -792,11 +792,13 @@
"source_issue": "Issue",
"source_chat": "Chat",
"source_autopilot": "Autopilot",
+ "source_doc": "Doc",
"source_untracked": "Untracked",
"source_quick_create": "Quick create",
"source_creating_issue": "Creating issue",
"source_chat_session": "Chat session",
"source_autopilot_run": "Autopilot run",
+ "source_doc_comment": "Doc comment",
"issue_short_fallback": "Issue {{prefix}}...",
"triggered_by": "Triggered by",
"open_issue_aria": "Open issue",
@@ -925,6 +927,7 @@
"trigger_retry": "Retry",
"trigger_chat": "From chat",
"trigger_quick_create": "Quick create",
+ "trigger_doc_comment": "From a doc comment",
"trigger_direct": "Direct assignment",
"run_info": "Run details",
"details_runtime": "Runtime",
diff --git a/packages/views/locales/en/docs.json b/packages/views/locales/en/docs.json
index ab074d49ee..e6dd4ecb2c 100644
--- a/packages/views/locales/en/docs.json
+++ b/packages/views/locales/en/docs.json
@@ -59,7 +59,8 @@
"title": "History",
"current": "Current",
"restore": "Restore this version",
- "loading": "Loading..."
+ "loading": "Loading...",
+ "from_discussion": "From comment: {{quote}}"
},
"not_found": {
"title": "Doc not found",
@@ -97,6 +98,7 @@
"save": "Could not post the comment",
"delete": "Could not delete the comment",
"resolve": "Could not update the comment"
- }
+ },
+ "run_waiting_runtime": "Waiting for the runtime to come back online"
}
}
diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.json
index 58a8508201..59c6bc2a40 100644
--- a/packages/views/locales/es/agents.json
+++ b/packages/views/locales/es/agents.json
@@ -767,11 +767,13 @@
"source_issue": "Tarea",
"source_chat": "Chat",
"source_autopilot": "Automatización",
+ "source_doc": "Documento",
"source_untracked": "Sin seguimiento",
"source_quick_create": "Creación rápida",
"source_creating_issue": "Creando tarea",
"source_chat_session": "Sesión de chat",
"source_autopilot_run": "Ejecución de automatización",
+ "source_doc_comment": "Comentario de documento",
"issue_short_fallback": "Tarea {{prefix}}…",
"triggered_by": "Disparada por",
"open_issue_aria": "Abrir tarea",
@@ -900,6 +902,7 @@
"trigger_retry": "Reintento",
"trigger_chat": "Desde el chat",
"trigger_quick_create": "Creación rápida",
+ "trigger_doc_comment": "Desde un comentario de documento",
"trigger_direct": "Asignación directa",
"run_info": "Detalles de la ejecución",
"details_runtime": "Runtime",
diff --git a/packages/views/locales/es/docs.json b/packages/views/locales/es/docs.json
index bee07fb325..4fff488b8a 100644
--- a/packages/views/locales/es/docs.json
+++ b/packages/views/locales/es/docs.json
@@ -59,7 +59,8 @@
"title": "Historial",
"current": "Actual",
"restore": "Restaurar esta versión",
- "loading": "Cargando..."
+ "loading": "Cargando...",
+ "from_discussion": "Desde el comentario: {{quote}}"
},
"not_found": {
"title": "Documento no encontrado",
@@ -97,6 +98,7 @@
"save": "No se pudo publicar el comentario",
"delete": "No se pudo eliminar el comentario",
"resolve": "No se pudo actualizar el comentario"
- }
+ },
+ "run_waiting_runtime": "Esperando a que el runtime vuelva a estar en línea"
}
}
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index 14e249d71e..3c95273dd3 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -792,11 +792,13 @@
"source_issue": "Tâche",
"source_chat": "Discussion",
"source_autopilot": "Automatisation",
+ "source_doc": "Document",
"source_untracked": "Non suivi",
"source_quick_create": "Création rapide",
"source_creating_issue": "Création de la tâche",
"source_chat_session": "Session de discussion",
"source_autopilot_run": "Exécution d'automatisation",
+ "source_doc_comment": "Commentaire de document",
"issue_short_fallback": "Tâche {{prefix}}…",
"triggered_by": "Déclenché par",
"open_issue_aria": "Ouvrir la tâche",
@@ -925,6 +927,7 @@
"trigger_retry": "Relance",
"trigger_chat": "Depuis une discussion",
"trigger_quick_create": "Création rapide",
+ "trigger_doc_comment": "Depuis un commentaire de document",
"trigger_direct": "Assignation directe",
"run_info": "Détails de l'exécution",
"details_runtime": "Runtime",
diff --git a/packages/views/locales/fr/docs.json b/packages/views/locales/fr/docs.json
index 4967162cb4..4a8781d29c 100644
--- a/packages/views/locales/fr/docs.json
+++ b/packages/views/locales/fr/docs.json
@@ -59,7 +59,8 @@
"title": "Historique",
"current": "Actuelle",
"restore": "Restaurer cette version",
- "loading": "Chargement..."
+ "loading": "Chargement...",
+ "from_discussion": "Depuis le commentaire : {{quote}}"
},
"not_found": {
"title": "Document introuvable",
@@ -97,6 +98,7 @@
"save": "Impossible de publier le commentaire",
"delete": "Impossible de supprimer le commentaire",
"resolve": "Impossible de mettre à jour le commentaire"
- }
+ },
+ "run_waiting_runtime": "En attente du retour en ligne du runtime"
}
}
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index f571d9075f..6a3376603d 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -627,11 +627,13 @@
"source_issue": "タスク",
"source_chat": "チャット",
"source_autopilot": "オートパイロット",
+ "source_doc": "ドキュメント",
"source_untracked": "未追跡",
"source_quick_create": "クイック作成",
"source_creating_issue": "タスクを作成中",
"source_chat_session": "チャットセッション",
"source_autopilot_run": "オートパイロット実行",
+ "source_doc_comment": "ドキュメントのコメント",
"issue_short_fallback": "タスク {{prefix}}...",
"triggered_by": "トリガーした人",
"open_issue_aria": "タスクを開く",
@@ -759,6 +761,7 @@
"trigger_retry": "再試行",
"trigger_chat": "チャットから",
"trigger_quick_create": "クイック作成",
+ "trigger_doc_comment": "ドキュメントのコメントから",
"trigger_direct": "直接アサイン",
"run_info": "実行の詳細",
"details_runtime": "ランタイム",
diff --git a/packages/views/locales/ja/docs.json b/packages/views/locales/ja/docs.json
index 424c8a3b26..3f0d7d80f5 100644
--- a/packages/views/locales/ja/docs.json
+++ b/packages/views/locales/ja/docs.json
@@ -59,7 +59,8 @@
"title": "履歴",
"current": "現在",
"restore": "このバージョンを復元",
- "loading": "読み込み中..."
+ "loading": "読み込み中...",
+ "from_discussion": "コメントから:{{quote}}"
},
"not_found": {
"title": "ドキュメントが見つかりません",
@@ -96,6 +97,7 @@
"save": "コメントを投稿できませんでした",
"delete": "コメントを削除できませんでした",
"resolve": "コメントを更新できませんでした"
- }
+ },
+ "run_waiting_runtime": "ランタイムのオンライン復帰を待機中"
}
}
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 6685cfd9d7..75b01ea455 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -627,11 +627,13 @@
"source_issue": "태스크",
"source_chat": "채팅",
"source_autopilot": "오토파일럿",
+ "source_doc": "문서",
"source_untracked": "추적 안 됨",
"source_quick_create": "빠른 생성",
"source_creating_issue": "태스크 생성 중",
"source_chat_session": "채팅 세션",
"source_autopilot_run": "오토파일럿 실행",
+ "source_doc_comment": "문서 댓글",
"issue_short_fallback": "태스크 {{prefix}}...",
"triggered_by": "트리거한 사람",
"open_issue_aria": "태스크 열기",
@@ -759,6 +761,7 @@
"trigger_retry": "재시도",
"trigger_chat": "채팅에서",
"trigger_quick_create": "빠른 생성",
+ "trigger_doc_comment": "문서 댓글에서",
"trigger_direct": "직접 지정",
"run_info": "실행 세부정보",
"details_runtime": "런타임",
diff --git a/packages/views/locales/ko/docs.json b/packages/views/locales/ko/docs.json
index 8b41f8a758..3c22d7989b 100644
--- a/packages/views/locales/ko/docs.json
+++ b/packages/views/locales/ko/docs.json
@@ -59,7 +59,8 @@
"title": "기록",
"current": "현재",
"restore": "이 버전 복원",
- "loading": "불러오는 중..."
+ "loading": "불러오는 중...",
+ "from_discussion": "댓글에서: {{quote}}"
},
"not_found": {
"title": "문서를 찾을 수 없습니다",
@@ -96,6 +97,7 @@
"save": "댓글을 게시하지 못했습니다",
"delete": "댓글을 삭제하지 못했습니다",
"resolve": "댓글을 업데이트할 수 없습니다"
- }
+ },
+ "run_waiting_runtime": "런타임이 다시 온라인이 되기를 기다리는 중"
}
}
diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.json
index c2979f32fe..1cadb9542a 100644
--- a/packages/views/locales/ru/agents.json
+++ b/packages/views/locales/ru/agents.json
@@ -838,11 +838,13 @@
"source_issue": "Задача",
"source_chat": "Чат",
"source_autopilot": "Автопилот",
+ "source_doc": "Документ",
"source_untracked": "Неотслеживаемый",
"source_quick_create": "Быстрое создание",
"source_creating_issue": "Создание задачи",
"source_chat_session": "Сессия чата",
"source_autopilot_run": "Запуск автопилота",
+ "source_doc_comment": "Комментарий в документе",
"issue_short_fallback": "Задача {{prefix}}…",
"triggered_by": "Инициировано",
"open_issue_aria": "Открыть задачу",
@@ -975,6 +977,7 @@
"trigger_retry": "Повтор",
"trigger_chat": "Из чата",
"trigger_quick_create": "Быстрое создание",
+ "trigger_doc_comment": "Из комментария в документе",
"trigger_direct": "Прямое назначение",
"run_info": "Сведения о запуске",
"details_runtime": "Среда выполнения",
diff --git a/packages/views/locales/ru/docs.json b/packages/views/locales/ru/docs.json
index 7c32998fcd..57952584b9 100644
--- a/packages/views/locales/ru/docs.json
+++ b/packages/views/locales/ru/docs.json
@@ -59,7 +59,8 @@
"title": "История",
"current": "Текущая",
"restore": "Восстановить эту версию",
- "loading": "Загрузка..."
+ "loading": "Загрузка...",
+ "from_discussion": "Из комментария: {{quote}}"
},
"not_found": {
"title": "Документ не найден",
@@ -99,6 +100,7 @@
"save": "Не удалось отправить комментарий",
"delete": "Не удалось удалить комментарий",
"resolve": "Не удалось обновить комментарий"
- }
+ },
+ "run_waiting_runtime": "Ожидание, пока среда выполнения снова будет в сети"
}
}
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index c7a1c7b9de..18b7006c53 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -768,11 +768,13 @@
"source_issue": "任务",
"source_chat": "聊天",
"source_autopilot": "自动化",
+ "source_doc": "文档",
"source_untracked": "未追踪",
"source_quick_create": "快速创建",
"source_creating_issue": "正在创建任务",
"source_chat_session": "聊天会话",
"source_autopilot_run": "自动化运行",
+ "source_doc_comment": "文档评论",
"issue_short_fallback": "任务 {{prefix}}...",
"triggered_by": "触发来源",
"open_issue_aria": "打开任务",
@@ -900,6 +902,7 @@
"trigger_retry": "重试",
"trigger_chat": "来自对话",
"trigger_quick_create": "快速创建",
+ "trigger_doc_comment": "文档评论触发",
"trigger_direct": "直接指派",
"run_info": "运行详情",
"details_runtime": "运行时",
diff --git a/packages/views/locales/zh-Hans/docs.json b/packages/views/locales/zh-Hans/docs.json
index 867b9629f0..d329a73078 100644
--- a/packages/views/locales/zh-Hans/docs.json
+++ b/packages/views/locales/zh-Hans/docs.json
@@ -59,7 +59,8 @@
"title": "历史",
"current": "当前",
"restore": "恢复此版本",
- "loading": "加载中..."
+ "loading": "加载中...",
+ "from_discussion": "来自评论:{{quote}}"
},
"not_found": {
"title": "未找到该文档",
@@ -96,6 +97,7 @@
"save": "评论发送失败",
"delete": "评论删除失败",
"resolve": "无法更新评论状态"
- }
+ },
+ "run_waiting_runtime": "等待运行环境重新上线"
}
}
diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.json
index 185b34663c..137bcdea4d 100644
--- a/packages/views/locales/zh-Hant/agents.json
+++ b/packages/views/locales/zh-Hant/agents.json
@@ -768,11 +768,13 @@
"source_issue": "任務",
"source_chat": "聊天",
"source_autopilot": "自動化",
+ "source_doc": "文件",
"source_untracked": "未追蹤",
"source_quick_create": "快速建立",
"source_creating_issue": "正在建立任務",
"source_chat_session": "聊天會話",
"source_autopilot_run": "自動化執行",
+ "source_doc_comment": "文件評論",
"issue_short_fallback": "任務 {{prefix}}...",
"triggered_by": "觸發來源",
"open_issue_aria": "開啟任務",
@@ -900,6 +902,7 @@
"trigger_retry": "重試",
"trigger_chat": "來自對話",
"trigger_quick_create": "快速建立",
+ "trigger_doc_comment": "文件評論觸發",
"trigger_direct": "直接指派",
"run_info": "執行詳情",
"details_runtime": "執行時",
diff --git a/packages/views/locales/zh-Hant/docs.json b/packages/views/locales/zh-Hant/docs.json
index 6be8b0447c..672dfe7139 100644
--- a/packages/views/locales/zh-Hant/docs.json
+++ b/packages/views/locales/zh-Hant/docs.json
@@ -59,7 +59,8 @@
"title": "歷史",
"current": "目前",
"restore": "還原此版本",
- "loading": "載入中..."
+ "loading": "載入中...",
+ "from_discussion": "來自評論:{{quote}}"
},
"not_found": {
"title": "未找到該文件",
@@ -96,6 +97,7 @@
"save": "評論送出失敗",
"delete": "評論刪除失敗",
"resolve": "無法更新評論"
- }
+ },
+ "run_waiting_runtime": "等待執行環境重新上線"
}
}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index a3760b9072..ad6a807cca 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "753_agent_task_queue_doc_idx": "idx_agent_task_queue_doc",
"749_app_tool_call_quota_period_scope_idx": "uq_app_tool_call_quota_period_scope",
"751_app_tool_call_workspace_metered_idx": "idx_app_tool_call_workspace_metered",
"736_task_usage_hourly_squad_uq_idx": "uq_task_usage_hourly_squad_key_idx",
diff --git a/server/cmd/multica/cmd_doc.go b/server/cmd/multica/cmd_doc.go
index 24586a8873..43f3ef5d0f 100644
--- a/server/cmd/multica/cmd_doc.go
+++ b/server/cmd/multica/cmd_doc.go
@@ -123,7 +123,22 @@ var docRestoreCmd = &cobra.Command{
var docCommentCmd = &cobra.Command{
Use: "comment",
- Short: "Read the discussion on a doc",
+ Short: "Read and reply to the discussion on a doc",
+ Long: "Read the comment threads people left on a doc, and reply in them. " +
+ "Starting a discussion, resolving one and deleting comments are reserved for people.",
+}
+
+var docCommentAddCmd = &cobra.Command{
+ Use: "add <doc-id>",
+ Short: "Reply in a doc discussion",
+ Long: "Reply in an existing discussion on a doc. --parent is the discussion's first comment, " +
+ "or any reply in it (the reply joins the same discussion).\n\n" +
+ "Pass the reply with --content, --content-file or --content-stdin; prefer --content-file for anything " +
+ "longer than a line. @mentions use the mention links from the doc's discussion, e.g. " +
+ "`[@Name](mention://member/<user-id>)`.\n\n" +
+ "Starting a discussion, resolving one and deleting comments are reserved for people.",
+ Args: exactArgs(1),
+ RunE: runDocCommentAdd,
}
var docCommentListCmd = &cobra.Command{
@@ -131,9 +146,11 @@ var docCommentListCmd = &cobra.Command{
Short: "List the comment threads on a doc",
Long: "List the comment threads on a doc, each root comment followed by its replies. " +
"A root comment's QUOTE (anchor_quote in --output json) is the doc text it was left on.\n\n" +
- "Resolved threads are hidden unless you pass --include-resolved. " +
+ "Pass --thread <comment-id> to list one discussion only. " +
+ "Resolved threads are hidden unless you pass --include-resolved or --thread. " +
"The table shortens long comments; --output json has the full text.\n\n" +
- "Writing in doc discussions (commenting, replying, resolving) is reserved for people, so there are no write commands.",
+ "Reply in a thread with `multica doc comment add`. Starting a discussion, resolving one and " +
+ "deleting comments are reserved for people.",
Args: exactArgs(1),
RunE: runDocCommentList,
}
@@ -179,7 +196,13 @@ func init() {
docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd, docEditCmd, docMoveCmd,
docHistoryCmd, docRestoreCmd, docCommentCmd, docFolderCmd)
docFolderCmd.AddCommand(docFolderListCmd, docFolderCreateCmd, docFolderUpdateCmd, docFolderMoveCmd)
- docCommentCmd.AddCommand(docCommentListCmd)
+ docCommentCmd.AddCommand(docCommentListCmd, docCommentAddCmd)
+ docCommentAddCmd.Flags().String("parent", "", "Comment id in the discussion to reply in (required)")
+ docCommentAddCmd.Flags().String("content", "", "Reply in Markdown")
+ docCommentAddCmd.Flags().String("content-file", "", "Read the reply from a UTF-8 file")
+ docCommentAddCmd.Flags().Bool("content-stdin", false, "Read the reply from stdin")
+ docCommentAddCmd.Flags().String("output", "json", "Output format: table or json")
+ docCommentListCmd.Flags().String("thread", "", "Only this discussion: its first comment's id")
docHistoryCmd.Flags().Int("version", 0, "Show this version with its content instead of listing versions")
docHistoryCmd.Flags().String("output", "", "Output format: table or json for the list (default table); json or content with --version (default json)")
docRestoreCmd.Flags().Int("version", 0, "Version number from doc history to restore (required)")
@@ -739,6 +762,7 @@ func runDocCommentList(cmd *cobra.Command, args []string) error {
// Group replies under their root, keeping the server's chronological order.
includeResolved, _ := cmd.Flags().GetBool("include-resolved")
+ thread, _ := cmd.Flags().GetString("thread")
var roots []map[string]any
replies := map[string][]map[string]any{}
for _, c := range result.Comments {
@@ -746,10 +770,17 @@ func runDocCommentList(cmd *cobra.Command, args []string) error {
replies[parent] = append(replies[parent], c)
continue
}
- if includeResolved || strVal(c, "resolved_at") == "" {
+ if thread != "" {
+ if strVal(c, "id") == thread {
+ roots = append(roots, c)
+ }
+ } else if includeResolved || strVal(c, "resolved_at") == "" {
roots = append(roots, c)
}
}
+ if thread != "" && len(roots) == 0 {
+ return fmt.Errorf("discussion %s not found on this doc", thread)
+ }
threads := make([]map[string]any, 0, len(result.Comments))
for _, root := range roots {
threads = append(threads, root)
@@ -777,6 +808,44 @@ func runDocCommentList(cmd *cobra.Command, args []string) error {
return nil
}
+func runDocCommentAdd(cmd *cobra.Command, args []string) error {
+ parent, _ := cmd.Flags().GetString("parent")
+ if strings.TrimSpace(parent) == "" {
+ return fmt.Errorf("--parent is required: replies go in an existing discussion")
+ }
+ content, hasContent, err := resolveSkillContentFlag(cmd)
+ if err != nil {
+ return err
+ }
+ if !hasContent || strings.TrimSpace(content) == "" {
+ return fmt.Errorf("reply is empty: pass --content, --content-file or --content-stdin")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ id, err := resolveDocRef(ctx, client, args[0], false)
+ if err != nil {
+ return err
+ }
+ var comment map[string]any
+ body := map[string]any{"content": content, "parent_id": parent}
+ if err := client.PostJSON(ctx, "/api/docs/"+id+"/comments", body, &comment); err != nil {
+ return fmt.Errorf("reply in doc discussion: %w", err)
+ }
+ if output, _ := cmd.Flags().GetString("output"); output == "table" {
+ cli.PrintTable(os.Stdout, []string{"ID", "REPLY TO", "COMMENT"}, [][]string{{
+ strVal(comment, "id"), strVal(comment, "parent_id"), oneLine(strVal(comment, "content"), 80),
+ }})
+ return nil
+ }
+ return cli.PrintJSON(os.Stdout, comment)
+}
+
func printDocFolderSummary(folder map[string]any, output string) error {
if output == "table" {
parent := strVal(folder, "parent_id")
diff --git a/server/cmd/multica/cmd_doc_test.go b/server/cmd/multica/cmd_doc_test.go
index 751faa0da2..c75a00c898 100644
--- a/server/cmd/multica/cmd_doc_test.go
+++ b/server/cmd/multica/cmd_doc_test.go
@@ -41,9 +41,9 @@ func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {
if len(expectedFolder) != 0 {
t.Fatalf("missing doc folder commands: %v", expectedFolder)
}
- // Writing in doc discussions is human-only on the server.
- if names := commandNames(docCommentCmd); len(names) != 1 || names[0] != "list" {
- t.Fatalf("doc comment commands = %v, want only list", names)
+ // Agents reply in doc discussions; resolving and deleting stay with people.
+ if names := commandNames(docCommentCmd); len(names) != 2 || names[0] != "add" || names[1] != "list" {
+ t.Fatalf("doc comment commands = %v, want add and list", names)
}
if !docFolderUpdateCmd.HasAlias("rename") {
t.Fatal("doc folder update should accept rename as an alias")
@@ -91,7 +91,8 @@ func TestDocHelpRendersWriteRules(t *testing.T) {
}{
{docUpdateCmd, []string{"--base-revision", "refused, with nothing written", "never resend the same body"}},
{docEditCmd, []string{"without --replace-all, appears more than once", "this or --old-file is required", "this or --new-file is required"}},
- {docCommentListCmd, []string{"reserved for people"}},
+ {docCommentListCmd, []string{"reserved for people", "multica doc comment add"}},
+ {docCommentAddCmd, []string{"--parent string", "reserved for people"}},
{docMoveCmd, []string{`--folder string`, `or "root" for the top level`}},
{docFolderCreateCmd, []string{`--parent string`, `or "root" for the top level`}},
{docFolderMoveCmd, []string{`--parent string`, `or "root" for the top level`}},
@@ -677,6 +678,22 @@ func TestRunDocCommentListGroupsThreadsAndHidesResolved(t *testing.T) {
t.Fatalf("--include-resolved list = %v", ids)
}
+ setDocFlag(t, docCommentListCmd, "thread", "c-done")
+ out, err = captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("list --thread: %v", err)
+ }
+ threads = nil
+ _ = json.Unmarshal([]byte(out), &threads)
+ if ids := commentIDs(threads); strings.Join(ids, ",") != "c-done,c-done-reply" {
+ t.Fatalf("--thread list = %v, want only that discussion even when resolved", ids)
+ }
+ setDocFlag(t, docCommentListCmd, "thread", "c-missing")
+ if _, err = captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) }); err == nil {
+ t.Fatal("--thread with an unknown discussion should fail")
+ }
+ setDocFlag(t, docCommentListCmd, "thread", "")
+
setDocFlag(t, docCommentListCmd, "output", "table")
out, err = captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) })
if err != nil {
@@ -689,6 +706,40 @@ func TestRunDocCommentListGroupsThreadsAndHidesResolved(t *testing.T) {
}
}
+func TestRunDocCommentAddRepliesInDiscussion(t *testing.T) {
+ const docID = "11111111-2222-3333-4444-555555555555"
+ var gotPath string
+ var gotBody map[string]any
+ setDocTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPath = r.URL.Path
+ _ = json.NewDecoder(r.Body).Decode(&gotBody)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": "c-new", "parent_id": "c-root", "content": "Done."})
+ })
+
+ setDocFlag(t, docCommentAddCmd, "content", "")
+ setDocFlag(t, docCommentAddCmd, "parent", "")
+ if _, err := captureStdout(t, func() error { return runDocCommentAdd(docCommentAddCmd, []string{docID}) }); err == nil ||
+ !strings.Contains(err.Error(), "--parent") {
+ t.Fatalf("a reply without --parent must fail, got %v", err)
+ }
+
+ setDocFlag(t, docCommentAddCmd, "parent", "c-root")
+ setDocFlag(t, docCommentAddCmd, "content", "Done.")
+ setDocFlag(t, docCommentAddCmd, "output", "json")
+ out, err := captureStdout(t, func() error { return runDocCommentAdd(docCommentAddCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("add: %v", err)
+ }
+ if gotPath != "/api/docs/"+docID+"/comments" || gotBody["parent_id"] != "c-root" || gotBody["content"] != "Done." {
+ t.Fatalf("request = %s %v", gotPath, gotBody)
+ }
+ if !strings.Contains(out, "c-new") {
+ t.Fatalf("output missing the new comment: %s", out)
+ }
+}
+
func commentIDs(comments []map[string]any) []string {
ids := make([]string, 0, len(comments))
for _, c := range comments {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f565d6b57d..6d3c050326 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2445,12 +2445,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/move", h.MoveDoc)
r.Get("/versions", h.ListDocVersions)
r.Get("/versions/{number}", h.GetDocVersion)
+ r.Get("/task-runs", h.ListDocTaskRuns)
r.Route("/comments", func(r chi.Router) {
r.Get("/", h.ListDocComments)
- // Writing in discussions is human-only until agents can take part.
+ // Agents reply in discussions; the rest stays with people.
+ r.Post("/", h.CreateDocComment)
r.Group(func(r chi.Router) {
r.Use(handler.RequireHumanActor)
- r.Post("/", h.CreateDocComment)
r.Post("/{docCommentId}/resolve", h.ResolveDocComment)
r.Post("/{docCommentId}/reopen", h.ReopenDocComment)
r.Delete("/{docCommentId}", h.DeleteDocComment)
diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.go
index 3a9e7d2c64..6e668491fb 100644
--- a/server/internal/attribution/attribution.go
+++ b/server/internal/attribution/attribution.go
@@ -119,6 +119,9 @@ const (
// 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"
+ // EvidenceDocComment points at the doc discussion comment that started
+ // the run (MUL-9933).
+ EvidenceDocComment EvidenceKind = "doc_comment"
)
// TriggerKind enumerates every path that can enqueue a run. Kept as an explicit
@@ -137,6 +140,7 @@ const (
KindStageWakeup TriggerKind = "stage_wakeup"
KindQuickCreate TriggerKind = "quick_create"
KindChat TriggerKind = "chat"
+ KindDocComment TriggerKind = "doc_comment"
KindAutopilotSchedule TriggerKind = "autopilot_schedule"
KindAutopilotWebhook TriggerKind = "autopilot_webhook"
KindAutopilotManual TriggerKind = "autopilot_manual"
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 466377040c..38ff0fdb93 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -216,6 +216,7 @@ func daemonCommonCapabilities() []string {
protocol.DaemonCapabilityWorkflowStatusRulesV1,
protocol.DaemonCapabilityWorkflowStatusMapV1,
protocol.DaemonCapabilityCLICommentSteerV1,
+ protocol.DaemonCapabilityDocCommentV1,
}
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f50363416d..32c28be613 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5714,6 +5714,9 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i
if taskTarget == "" && t.ChatSessionID != "" {
taskTarget = "chat:" + t.ChatSessionID
}
+ if taskTarget == "" && t.DocID != "" {
+ taskTarget = "doc:" + t.DocID
+ }
d.logger.Info("task received", "task", t.ID, "target", taskTarget)
taskWG.Add(1)
d.activeTasks.Add(1)
@@ -6927,6 +6930,9 @@ func gcMetaForTask(task Task) (execenv.GCMeta, bool) {
case task.AutopilotRunID != "":
meta.Kind = execenv.GCKindAutopilotRun
meta.AutopilotRunID = task.AutopilotRunID
+ case task.DocID != "":
+ meta.Kind = execenv.GCKindDoc
+ meta.DocID = task.DocID
case task.IssueID != "":
meta.Kind = execenv.GCKindIssue
meta.IssueID = task.IssueID
@@ -7430,7 +7436,7 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] != "workdir" {
return "", false
}
- if task.AgentID == "" || (task.IssueID == "" && task.ChatSessionID == "") {
+ if task.AgentID == "" || (task.IssueID == "" && task.ChatSessionID == "" && task.DocID == "") {
return "", false
}
// Managed-env provenance is written only for non-local resumable envs, so
@@ -7452,6 +7458,7 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
AgentID string `json:"agent_id"`
IssueID string `json:"issue_id"`
ChatSessionID string `json:"chat_session_id"`
+ DocID string `json:"doc_id"`
}
if json.Unmarshal(data, &marker) != nil {
return "", false
@@ -7465,6 +7472,12 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
}
return workdir, true
}
+ if task.DocID != "" {
+ if prov.DocID != task.DocID || marker.DocID != task.DocID {
+ return "", false
+ }
+ return workdir, true
+ }
if prov.ChatSessionID != task.ChatSessionID || marker.ChatSessionID != task.ChatSessionID {
return "", false
}
@@ -8419,6 +8432,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
ProjectArchived: task.ProjectArchived,
ProjectResources: convertProjectResourcesForEnv(task.ProjectResources),
ChatSessionID: task.ChatSessionID,
+ DocID: task.DocID,
ChatChannelType: task.ChatChannelType,
ChatChannelDeliversFiles: task.ChatChannelDeliversFiles,
DocsEnabled: task.DocsEnabled,
diff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.go
index c1b926a9a4..4395cd582f 100644
--- a/server/internal/daemon/diskusage.go
+++ b/server/internal/daemon/diskusage.go
@@ -368,6 +368,8 @@ func parentIDForMeta(meta *execenv.GCMeta) string {
return strings.TrimSpace(meta.AutopilotRunID)
case execenv.GCKindQuickCreate:
return strings.TrimSpace(meta.TaskID)
+ case execenv.GCKindDoc:
+ return strings.TrimSpace(meta.DocID)
default:
return ""
}
diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.go
index 30fcefdb0b..dd6cb1e3e0 100644
--- a/server/internal/daemon/execenv/codex_home.go
+++ b/server/internal/daemon/execenv/codex_home.go
@@ -413,11 +413,13 @@ func codexSessionStoreNamespace(profile string) string {
func codexSessionStoreKey(profile string, task TaskContextForEnv) string {
storeID := sanitizePathSegment(task.IssueID)
if storeID == "" {
- chatID := sanitizePathSegment(task.ChatSessionID)
- if chatID == "" {
+ if chatID := sanitizePathSegment(task.ChatSessionID); chatID != "" {
+ storeID = "chat_" + chatID
+ } else if docID := sanitizePathSegment(task.DocID); docID != "" {
+ storeID = "doc_" + docID
+ } else {
return ""
}
- storeID = "chat_" + chatID
}
agent := sanitizePathSegment(task.AgentID)
if agent == "" {
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index 50dadf6d17..20e2943783 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -28,6 +28,7 @@ type taskContextMarkerFile struct {
AgentID string `json:"agent_id,omitempty"`
IssueID string `json:"issue_id,omitempty"`
ChatSessionID string `json:"chat_session_id,omitempty"`
+ DocID string `json:"doc_id,omitempty"`
}
// EnsureWorkspacesRootMarker writes a persistent daemon-task marker at
@@ -215,6 +216,7 @@ func writeTaskContextMarker(workDir string, ctx TaskContextForEnv, manifest *sid
AgentID: ctx.AgentID,
IssueID: ctx.IssueID,
ChatSessionID: ctx.ChatSessionID,
+ DocID: ctx.DocID,
}
data, err := json.MarshalIndent(payload, "", " ")
if err != nil {
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index f56901b5d7..70491881bc 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -170,6 +170,7 @@ type TaskContextForEnv struct {
ProjectArchived bool // project is archived; rendered as a note in the Project Context section
ProjectResources []ProjectResourceForEnv // resources attached to the project
ChatSessionID string // non-empty for chat tasks
+ DocID string // non-empty for doc discussion tasks (MUL-9933)
// ChatChannelType is the IM platform behind a chat session ("slack",
// "feishu", "wecom"); empty for a web/mobile chat. It names the surface in
// the brief's copy; what that surface can DELIVER is the separate field
@@ -659,15 +660,16 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// follow-up can be claimed the instant the prior task completes — before
// the prior handler writes .gc_meta.json — so reuse eligibility must be
// provable from an artifact that exists the moment the env is created. Only
- // managed (non-local_directory) issue and chat envs get this marker; that is
- // exactly the set with a durable conversation scope. Non-fatal: a write failure
+ // managed (non-local_directory) issue, chat and doc discussion envs get this
+ // marker; that is exactly the set with a durable conversation scope. Non-fatal: a write failure
// only costs the next follow-up its session reuse (it falls back to a fresh
// session), which must never block dispatching this task.
- if params.LocalWorkDir == "" && (params.Task.IssueID != "" || params.Task.ChatSessionID != "") {
+ if params.LocalWorkDir == "" && (params.Task.IssueID != "" || params.Task.ChatSessionID != "" || params.Task.DocID != "") {
if err := WriteManagedEnvProvenance(envRoot, ManagedEnvProvenance{
WorkspaceID: params.WorkspaceID,
IssueID: params.Task.IssueID,
ChatSessionID: params.Task.ChatSessionID,
+ DocID: params.Task.DocID,
AgentID: params.Task.AgentID,
}); err != nil && logger != nil {
logger.Warn("execenv: write managed env provenance failed (non-fatal); a follow-up may start a fresh session", "error", err)
@@ -1173,6 +1175,9 @@ const (
GCKindChat GCMetaKind = "chat"
GCKindAutopilotRun GCMetaKind = "autopilot_run"
GCKindQuickCreate GCMetaKind = "quick_create"
+ // GCKindDoc is a doc discussion run's env, reused by the agent's next run
+ // on the same doc (MUL-9933).
+ GCKindDoc GCMetaKind = "doc"
)
// GCMeta is persisted to .gc_meta.json inside the env root so the GC loop
@@ -1190,6 +1195,7 @@ type GCMeta struct {
IssueID string `json:"issue_id,omitempty"`
ChatSessionID string `json:"chat_session_id,omitempty"`
AutopilotRunID string `json:"autopilot_run_id,omitempty"`
+ DocID string `json:"doc_id,omitempty"`
TaskID string `json:"task_id,omitempty"`
WorkspaceID string `json:"workspace_id"`
CompletedAt time.Time `json:"completed_at"`
@@ -1271,6 +1277,7 @@ type ManagedEnvProvenance struct {
WorkspaceID string `json:"workspace_id"`
IssueID string `json:"issue_id,omitempty"`
ChatSessionID string `json:"chat_session_id,omitempty"`
+ DocID string `json:"doc_id,omitempty"`
AgentID string `json:"agent_id"`
}
diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.go
index ea09a49329..0d65cf8dad 100644
--- a/server/internal/daemon/execenv/local_worktree.go
+++ b/server/internal/daemon/execenv/local_worktree.go
@@ -137,8 +137,8 @@ func (p LocalWorktreeParams) owner() branchOwner {
// tail. The id is what the branch BELONGS to, and only it decides whether a
// later task may continue that branch: identifiers are per-workspace and
// human-chosen, so two workspaces can mint the same one for different issues.
-// Tasks with neither an issue nor a chat session have no conversation to
-// continue and get "", "".
+// Doc discussion runs continue per doc. Tasks with none of these have no
+// conversation to continue and get "", "".
func localWorktreeConversation(params PrepareParams) (key, id string) {
if params.Task.IssueID != "" {
if params.IssueIdentifier != "" {
@@ -149,6 +149,9 @@ func localWorktreeConversation(params PrepareParams) (key, id string) {
if params.Task.ChatSessionID != "" {
return "chat-" + taskKey(params.Task.ChatSessionID), params.Task.ChatSessionID
}
+ if params.Task.DocID != "" {
+ return "doc-" + taskKey(params.Task.DocID), params.Task.DocID
+ }
return "", ""
}
diff --git a/server/internal/daemon/execenv/runtime_config_kind.go b/server/internal/daemon/execenv/runtime_config_kind.go
index 645e76982b..379c4dd897 100644
--- a/server/internal/daemon/execenv/runtime_config_kind.go
+++ b/server/internal/daemon/execenv/runtime_config_kind.go
@@ -6,7 +6,7 @@ package execenv
// flag that once gated it against a legacy verbose brief was retired in
// MUL-4297, so this is now the only brief).
//
-// Four kinds, mutually exclusive in practice. classifyTask documents the
+// Five kinds, mutually exclusive in practice. classifyTask documents the
// tiebreak rule that applies if a future caller accidentally violates the
// mutex.
type taskKind int
@@ -32,12 +32,14 @@ const (
kindQuickCreate
// kindChat: interactive chat session, no issue.
kindChat
+ // kindDocComment: answering a doc discussion (MUL-9933), no issue.
+ kindDocComment
)
// classifyTask maps a TaskContextForEnv to the single taskKind the slim
// brief should be assembled for. Precedence (documented for the tiebreak
// case, although the daemon never sets two specific-kind flags at once):
-// chat → quick-create → autopilot run-only → issue.
+// chat → doc discussion → quick-create → autopilot run-only → issue.
//
// Deliberately does not read ctx.TriggerCommentID: the classification must
// not vary across runs of the same resumed session, or the brief's bytes
@@ -46,6 +48,8 @@ func classifyTask(ctx TaskContextForEnv) taskKind {
switch {
case ctx.ChatSessionID != "":
return kindChat
+ case ctx.DocID != "":
+ return kindDocComment
case ctx.QuickCreatePrompt != "":
return kindQuickCreate
case ctx.AutopilotRunID != "":
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 75d7ca49b9..c2c3606363 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -295,7 +295,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use one `--until-*` condition so no run starts before it holds; check the rule's `last_error` for missing PR links or snapshots, which are retried automatically. Conditions, PR rules and actor filters: `multica issue wakeup create --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
if ctx.DocsEnabled {
- b.WriteString("- `multica doc list|search|get|create|edit|update|move|history|restore|comment|folder` — workspace docs and folders (`doc folder list|create|update|move`); `doc search <query>` matches titles and content; people may be editing a doc live, so change part of it with `doc edit <id> --old <exact text> --new <text>` (`--old-file` / `--new-file` for multi-line text or anything with code or quotes); `doc update` rewrites the whole doc and needs `--base-revision` from `multica doc get`; `doc comment list <id>` shows the open review threads on a doc; `doc history` / `doc restore` read and roll back versions (details: `multica doc update --help`, `multica doc edit --help`).\n")
+ b.WriteString("- `multica doc list|search|get|create|edit|update|move|history|restore|comment|folder` — workspace docs and folders (`doc folder list|create|update|move`); `doc search <query>` matches titles and content; people may be editing a doc live, so change part of it with `doc edit <id> --old <exact text> --new <text>` (`--old-file` / `--new-file` for multi-line text or anything with code or quotes); `doc update` rewrites the whole doc and needs `--base-revision` from `multica doc get`; `doc comment list <id>` shows the open review threads on a doc and `doc comment add <id> --parent <comment-id>` replies in one; `doc history` / `doc restore` read and roll back versions (details: `multica doc update --help`, `multica doc edit --help`).\n")
}
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file` with a file inside your working directory; full flags: `multica issue comment add --help`.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch; re-running it keeps a checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches; a clean, fully pushed checkout on another branch starts over on a new branch. `--fresh` discards uncommitted and untracked files for a new branch; commits stay on the old branch, so push any you still need first.\n\n")
@@ -638,6 +638,17 @@ func writeWorkflowChat(b *strings.Builder) {
b.WriteString("- Keep responses concise and direct\n\n")
}
+// writeWorkflowDocComment emits the stable rules of a doc discussion run
+// (MUL-9933). The doc, the discussion and the reply command change per turn
+// and travel in the per-turn user message.
+func writeWorkflowDocComment(b *strings.Builder) {
+ b.WriteString("**You were asked for in a discussion on a Multica doc.** There is no Multica issue for this run; the per-turn user message names the doc, the discussion and the comment to answer.\n\n")
+ b.WriteString("- Read the doc and the whole discussion before answering.\n")
+ b.WriteString("- You may change the doc when the discussion asks for it or it is clearly the best answer; every change is kept in the doc's history.\n")
+ b.WriteString("- You can only reply in the discussion that asked for you. Starting a discussion, resolving one and deleting comments are left to people.\n")
+ b.WriteString("- If the task requires code, use `multica repo checkout <url>` to get it first.\n\n")
+}
+
// writeWorkflowQuickCreate emits the quick-create workflow's hard
// guardrails.
func writeWorkflowQuickCreate(b *strings.Builder) {
@@ -1002,6 +1013,10 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
case kindQuickCreate:
b.WriteString("This is a quick-create task. There is NO existing issue to comment on. Your final stdout is captured automatically, and the platform turns it into the user's success or `quick_create_failed` inbox item based on whether `multica issue create` succeeded. What to print in each case is stated once, under `## Workflow`.\n\n")
b.WriteString("**Delivering files here:** your stdout is text-only. A file that belongs to the new issue goes on the `multica issue create` call itself via `--attachment <path>`; never put its path in the description or in your stdout line.\n")
+ case kindDocComment:
+ b.WriteString("⚠️ **Your result MUST be delivered as one reply in the doc discussion, with the `multica doc comment add` command the per-turn user message gives you.** The user does NOT see your terminal output or run logs — only the discussion.\n\n")
+ b.WriteString("Keep the reply concise and natural — state the outcome, not the process. Do NOT post progress updates.\n\n")
+ b.WriteString("**Delivering files here:** a doc reply carries no attachments. Describe what you produced in words; do not link its path.\n")
case kindChat:
b.WriteString("This is a chat session. Your reply is delivered directly to the chat window the user is reading.\n\n")
// Two-layer channel policy (MUL-4899). This is the DELIVERY layer, and
@@ -1052,18 +1067,18 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
// The Section × Kind matrix encoded below (skip = elide section, keep
// = always emit, △ = data-driven inside the helper):
//
-// Section | comment | assign | autopilot | quick_create | chat
-// ----------------------+---------+--------+-----------+--------------+------
-// Available Commands | full | full | full | minimal | full
-// Issue Body Formatting | ✓ | ✓ | ✓ | ✓ | ✓
-// Comment Formatting | ✓ | ✓ | — | — | —
-// Repositories | △ | △ | △ | — | △
-// Project Context | △ | △ | △ | △ | △
-// Instruction Precedence| — | ✓ | — | — | —
-// Sub-issue Creation | ✓ | ✓ | — | — | —
-// Skills | ✓ | ✓ | ✓ | ✓ | ✓
-// Mentions | ✓ | ✓ | — | — | —
-// Attachments | ✓ | ✓ | — | — | —
+// Section | comment | assign | autopilot | quick_create | chat | doc_comment
+// ----------------------+---------+--------+-----------+--------------+------+------------
+// Available Commands | full | full | full | minimal | full | full
+// Issue Body Formatting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓
+// Comment Formatting | ✓ | ✓ | — | — | — | —
+// Repositories | △ | △ | △ | — | △ | △
+// Project Context | △ | △ | △ | △ | △ | △
+// Instruction Precedence| — | ✓ | — | — | — | —
+// Sub-issue Creation | ✓ | ✓ | — | — | — | —
+// Skills | ✓ | ✓ | ✓ | ✓ | ✓ | ✓
+// Mentions | ✓ | ✓ | — | — | — | ✓
+// Attachments | ✓ | ✓ | — | — | — | —
//
// Always-on rows — Header, Background Task Safety, Agent Identity,
// Requesting User, Workspace Context, Connected Apps,
@@ -1110,6 +1125,8 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {
switch kind {
case kindChat:
writeWorkflowChat(&b)
+ case kindDocComment:
+ writeWorkflowDocComment(&b)
case kindQuickCreate:
writeWorkflowQuickCreate(&b)
case kindAutopilotRunOnly:
@@ -1131,6 +1148,9 @@ func buildMetaSkillContentSlim(provider string, ctx TaskContextForEnv) string {
writeMentions(&b, ctx.DocsEnabled)
writeAttachments(&b)
}
+ if kind == kindDocComment {
+ writeMentions(&b, ctx.DocsEnabled)
+ }
writeAlwaysUseCLI(&b)
writeOutput(&b, kind, ctx)
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 075e75399c..a08f2bf52e 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -2326,6 +2326,7 @@ func TestBriefByteIdenticalAcrossRunsForEveryKind(t *testing.T) {
"chat": {ChatSessionID: "chat-1", ChatChannelType: ChannelTypeSlack, AgentID: "a-1", AgentName: "Eve"},
"quick-create": {QuickCreatePrompt: "make an issue", AgentID: "a-1", AgentName: "Eve"},
"autopilot": {AutopilotRunID: "run-1", AutopilotID: "ap-1", AgentID: "a-1", AgentName: "Eve"},
+ "doc-comment": {DocID: "doc-1", AgentID: "a-1", AgentName: "Eve"},
// WeCom is the channel a real deployment flips the file-delivery
// verdict on. The Slack row above catches the same leak today, but only
// because the brief's copy is channel-agnostic; scope that copy to
@@ -2681,3 +2682,21 @@ func TestEveryBriefThatTeachesJSONOutputAlsoWarnsAgainstMergingStderr(t *testing
}
}
}
+
+// A doc discussion run delivers into the discussion, not onto an issue
+// (MUL-9933): its brief must not send the agent to `multica issue comment add`.
+func TestDocCommentBriefDeliversIntoDiscussion(t *testing.T) {
+ t.Parallel()
+
+ brief := buildMetaSkillContentSlim("claude", TaskContextForEnv{DocID: "doc-1", AgentID: "a-1", AgentName: "Eve", DocsEnabled: true})
+ for _, want := range []string{"discussion on a Multica doc", "`multica doc comment add`", "## Mentions"} {
+ if !strings.Contains(brief, want) {
+ t.Fatalf("doc brief missing %q:\n%s", want, brief)
+ }
+ }
+ for _, unwanted := range []string{"Final results MUST be delivered via `multica issue comment add`", "## Sub-issue Creation", "## Comment Formatting"} {
+ if strings.Contains(brief, unwanted) {
+ t.Fatalf("doc brief must not contain %q", unwanted)
+ }
+ }
+}
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index b28bb4c7b0..6ee622c9a5 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -390,6 +390,8 @@ func (d *Daemon) applyGCActionWithChatMeta(ctx context.Context, taskDir string,
attrs = append(attrs, "autopilot_run", checkedMeta.AutopilotRunID)
case execenv.GCKindQuickCreate:
attrs = append(attrs, "task", checkedMeta.TaskID)
+ case execenv.GCKindDoc:
+ attrs = append(attrs, "doc", checkedMeta.DocID)
}
}
d.logger.Info("gc: removed", attrs...)
@@ -588,6 +590,8 @@ func (d *Daemon) shouldCleanTaskDirForKind(ctx context.Context, taskDir string,
return d.gcDecisionAutopilotRun(ctx, taskDir, meta)
case execenv.GCKindQuickCreate:
return d.gcDecisionQuickCreate(ctx, taskDir, meta)
+ case execenv.GCKindDoc:
+ return d.gcDecisionDoc(taskDir, meta)
default:
// Unknown kind: fall back to mtime-based orphan cleanup so a future
// daemon writing a kind we don't recognize doesn't get insta-wiped.
@@ -780,6 +784,23 @@ func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *exece
return gcActionSkip, gcRemovalDetails{}
}
+// gcDecisionDoc keeps a doc discussion env for the agent's next run on the
+// doc. A doc has no end state, so the env goes once no run has used it for
+// GCTTL; every run rewrites the meta, which restarts that clock.
+func (d *Daemon) gcDecisionDoc(taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {
+ if strings.TrimSpace(meta.DocID) == "" || meta.CompletedAt.IsZero() {
+ return d.orphanByMTime(taskDir, "incomplete doc meta")
+ }
+ idle := time.Since(meta.CompletedAt)
+ if idle > d.cfg.GCTTL {
+ return gcActionClean, gcRemovalDetails{reason: "idle doc env retention expired", retention: d.cfg.GCTTL}
+ }
+ if d.cfg.GCArtifactTTL > 0 && idle > d.cfg.GCArtifactTTL {
+ return gcActionCleanArtifacts, gcRemovalDetails{}
+ }
+ return gcActionSkip, gcRemovalDetails{}
+}
+
func (d *Daemon) gcDecisionAutopilotRun(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {
if strings.TrimSpace(meta.AutopilotRunID) == "" {
return d.orphanByMTime(taskDir, "empty autopilot run id")
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index 882cd03d8b..236b2f30e7 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -2606,6 +2606,12 @@ func TestGCMetaForTask(t *testing.T) {
want: execenv.GCKindQuickCreate,
idOK: func(m execenv.GCMeta) bool { return m.TaskID == "t4" },
},
+ {
+ name: "doc discussion task",
+ task: Task{ID: "t6", WorkspaceID: "ws", DocID: "d1"},
+ want: execenv.GCKindDoc,
+ idOK: func(m execenv.GCMeta) bool { return m.DocID == "d1" },
+ },
{
name: "chat wins over issue when both set (defensive ordering)",
task: Task{ID: "t5", WorkspaceID: "ws", IssueID: "i1", ChatSessionID: "c1"},
diff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.go
index 85137fe26e..cb11f1fb57 100644
--- a/server/internal/daemon/leader_workdir_reuse_test.go
+++ b/server/internal/daemon/leader_workdir_reuse_test.go
@@ -137,6 +137,44 @@ func TestShouldReusePriorWorkdirChatAcceptsMatchingConversation(t *testing.T) {
}
}
+// A doc discussion run continues in the env its agent last used on the same
+// doc (MUL-9933), and never in one from another doc.
+func TestShouldReusePriorWorkdirDocAcceptsMatchingDoc(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ workDir := filepath.Join(root, "ws-doc", "12345678", "workdir")
+ markerPath := filepath.Join(workDir, execenv.TaskContextMarkerRelPath)
+ if err := os.MkdirAll(filepath.Dir(markerPath), 0o755); err != nil {
+ t.Fatalf("mkdir marker dir: %v", err)
+ }
+ marker := []byte(`{"managed_by":"` + execenv.TaskContextMarkerManagedBy + `","agent_id":"agent-doc","doc_id":"doc-1"}`)
+ if err := os.WriteFile(markerPath, marker, 0o644); err != nil {
+ t.Fatalf("write marker: %v", err)
+ }
+ if err := execenv.WriteManagedEnvProvenance(filepath.Dir(workDir), execenv.ManagedEnvProvenance{
+ WorkspaceID: "ws-doc", DocID: "doc-1", AgentID: "agent-doc",
+ }); err != nil {
+ t.Fatalf("write provenance: %v", err)
+ }
+
+ task := leaderReuseTestTask("task-doc")
+ task.WorkspaceID = "ws-doc"
+ task.IssueID = ""
+ task.DocID = "doc-1"
+ task.AgentID = "agent-doc"
+ task.IsLeaderTask = false
+ task.PriorWorkDir = workDir
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); !ok {
+ t.Fatalf("doc task did not reuse its doc's workdir %q", workDir)
+ }
+
+ task.DocID = "doc-2"
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
+ t.Fatal("doc task reused a workdir belonging to another doc")
+ }
+}
+
// TestShouldReusePriorWorkdirDeclinesRemovedDirectory covers an automatic retry
// whose parent's workdir was GC'd between the failure and the claim (MUL-7034):
// the server still offers the recorded path, and the daemon must decline it so
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index a7f73cff1c..97af7b4dd5 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -377,6 +377,9 @@ func buildPromptBodyWithOptions(task Task, provider string, opts promptOpts) str
if task.ChatSessionID != "" {
return buildChatPromptWithOptions(task, opts)
}
+ if task.DocID != "" {
+ return buildDocCommentPrompt(task)
+ }
if task.TriggerCommentID != "" {
return buildCommentPromptWithOptions(task, provider, opts)
}
diff --git a/server/internal/daemon/prompt_doc.go b/server/internal/daemon/prompt_doc.go
new file mode 100644
index 0000000000..0deb86ac8b
--- /dev/null
+++ b/server/internal/daemon/prompt_doc.go
@@ -0,0 +1,46 @@
+package daemon
+
+import (
+ "fmt"
+ "strings"
+)
+
+// buildDocCommentPrompt is the per-turn prompt of a run started from a doc
+// discussion (MUL-9933). The doc, discussion and reply command are re-emitted
+// on every turn: runs on one doc share a session, so a resumed session must
+// never reply under an earlier discussion's --parent.
+func buildDocCommentPrompt(task Task) string {
+ var b strings.Builder
+ b.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")
+ fmt.Fprintf(&b, "You were asked for in a discussion on the doc %q (doc ID: %s, discussion ID: %s).\n\n", task.DocTitle, task.DocID, task.DocThreadID)
+ if quote := strings.TrimSpace(task.DocThreadQuote); quote != "" {
+ b.WriteString("The discussion is about this text in the doc (it may have changed since):\n\n")
+ writeQuoted(&b, quote)
+ }
+ if content := strings.TrimSpace(task.DocCommentContent); content != "" {
+ author := task.DocCommentAuthorName
+ if author == "" {
+ author = "Someone"
+ }
+ fmt.Fprintf(&b, "[NEW COMMENT] %s just wrote this in the discussion. Focus on THIS comment — earlier ones are context:\n\n", author)
+ writeQuoted(&b, content)
+ } else {
+ b.WriteString("The comment that asked for you has been deleted. Read the discussion and answer what is still open in it.\n\n")
+ }
+
+ b.WriteString("Workflow:\n\n")
+ fmt.Fprintf(&b, "1. Read the doc: `multica doc get %s --output content`.\n", task.DocID)
+ fmt.Fprintf(&b, "2. Read the whole discussion: `multica doc comment list %s --thread %s --output json`.\n", task.DocID, task.DocThreadID)
+ b.WriteString("3. Do what the comment asks. When it asks for a change to the doc, or changing the doc is clearly the best answer, make the change yourself: `multica doc edit` for targeted changes, `multica doc update` only to rewrite the whole doc (see `multica doc --help`). Every change is kept in the doc's history and can be restored.\n")
+ b.WriteString("4. Reply in this discussion before you exit — this step is mandatory. Write the reply to a UTF-8 file in your working directory, then post it:\n\n")
+ fmt.Fprintf(&b, " multica doc comment add %s --parent %s --content-file ./reply.md --output table && rm ./reply.md\n\n", task.DocID, task.DocThreadID)
+ b.WriteString("Post one reply with your result, not progress updates. You can only reply in this discussion: starting a new one, resolving it and deleting comments are left to people.\n")
+ return b.String()
+}
+
+func writeQuoted(b *strings.Builder, text string) {
+ for _, line := range strings.Split(text, "\n") {
+ fmt.Fprintf(b, "> %s\n", line)
+ }
+ b.WriteString("\n")
+}
diff --git a/server/internal/daemon/prompt_doc_test.go b/server/internal/daemon/prompt_doc_test.go
new file mode 100644
index 0000000000..8af382cf4c
--- /dev/null
+++ b/server/internal/daemon/prompt_doc_test.go
@@ -0,0 +1,41 @@
+package daemon
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestBuildPromptDocCommentNamesDiscussionAndReplyCommand(t *testing.T) {
+ t.Parallel()
+
+ task := Task{
+ ID: "task-1", AgentID: "agent-1",
+ DocID: "doc-1", DocThreadID: "thread-1", DocCommentID: "comment-2",
+ DocTitle: "Launch plan",
+ DocThreadQuote: "We ship on Friday.",
+ DocCommentContent: "Can you move this to Monday?\nAnd say why.",
+ DocCommentAuthorName: "Bohan",
+ }
+ prompt := BuildPrompt(task, "claude")
+ for _, want := range []string{
+ `"Launch plan"`,
+ "> We ship on Friday.",
+ "[NEW COMMENT] Bohan",
+ "> Can you move this to Monday?\n> And say why.",
+ "multica doc get doc-1 --output content",
+ "multica doc comment list doc-1 --thread thread-1 --output json",
+ "multica doc comment add doc-1 --parent thread-1 --content-file ./reply.md --output table && rm ./reply.md",
+ } {
+ if !strings.Contains(prompt, want) {
+ t.Fatalf("prompt missing %q:\n%s", want, prompt)
+ }
+ }
+ if strings.Contains(prompt, "multica issue") {
+ t.Fatalf("doc prompt must not send the agent to issue commands:\n%s", prompt)
+ }
+
+ task.DocCommentContent = ""
+ if prompt := BuildPrompt(task, "claude"); !strings.Contains(prompt, "has been deleted") {
+ t.Fatalf("prompt for a deleted trigger should say so:\n%s", prompt)
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index d4691ba1e0..19487fd0cb 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -160,6 +160,13 @@ type Task struct {
AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt
AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api
AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
+ DocID string `json:"doc_id,omitempty"` // non-empty for doc discussion tasks (MUL-9933)
+ DocThreadID string `json:"doc_thread_id,omitempty"` // the discussion's first comment; replies go under it
+ DocCommentID string `json:"doc_comment_id,omitempty"` // the comment that triggered the run
+ DocTitle string `json:"doc_title,omitempty"` // the doc's title
+ DocThreadQuote string `json:"doc_thread_quote,omitempty"` // the doc text the discussion is about
+ DocCommentContent string `json:"doc_comment_content,omitempty"` // the triggering comment; empty when it was deleted before the claim
+ DocCommentAuthorName string `json:"doc_comment_author_name,omitempty"` // who wrote the triggering comment
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
QuickCreatePriority string `json:"quick_create_priority,omitempty"` // explicit priority selected in quick-create
QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-create
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 02f8cdf763..83b78725e8 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -579,6 +579,13 @@ type AgentTaskResponse struct {
AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt
AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api
AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
+ DocID string `json:"doc_id,omitempty"` // doc discussion runs (MUL-9933): the doc
+ DocThreadID string `json:"doc_thread_id,omitempty"` // the discussion's first comment
+ DocCommentID string `json:"doc_comment_id,omitempty"` // the comment that triggered the run
+ DocTitle string `json:"doc_title,omitempty"` // claim only: the doc's title
+ DocThreadQuote string `json:"doc_thread_quote,omitempty"` // claim only: the text the discussion is about
+ DocCommentContent string `json:"doc_comment_content,omitempty"` // claim only: the triggering comment
+ DocCommentAuthorName string `json:"doc_comment_author_name,omitempty"` // claim only: who wrote it
QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
QuickCreatePriority string `json:"quick_create_priority,omitempty"` // explicit priority selected in quick-create
QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-create
@@ -616,7 +623,7 @@ type AgentTaskResponse struct {
InitiatorID string `json:"initiator_id,omitempty"` // originator user UUID
InitiatorName string `json:"initiator_name,omitempty"` // originator display name
InitiatorEmail string `json:"initiator_email,omitempty"` // originator email
- Kind string `json:"kind"` // source discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "direct" — quick-create remains stable after its result issue is linked
+ Kind string `json:"kind"` // source discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "doc_comment" | "direct" — quick-create remains stable after its result issue is linked
// 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
@@ -973,6 +980,9 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
// issue link for navigation but retains its quick_create kind.
ChatSessionID: uuidToString(t.ChatSessionID),
AutopilotRunID: uuidToString(t.AutopilotRunID),
+ DocID: uuidToString(t.DocID),
+ DocThreadID: uuidToString(t.DocThreadID),
+ DocCommentID: uuidToString(t.DocCommentID),
Kind: computeTaskKind(t),
// Attribution labels + evidence + lineage + raw user ids (pure). Names are
// hydrated separately on user-facing surfaces (MUL-4302 §9).
@@ -1142,6 +1152,9 @@ func computeTaskKind(t db.AgentTaskQueue) string {
if uuidToString(t.AutopilotRunID) != "" {
return "autopilot"
}
+ if uuidToString(t.DocID) != "" {
+ return "doc_comment"
+ }
var contextKind struct {
Type string `json:"type"`
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index c04653896c..11d909d7de 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4115,6 +4115,14 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
projectCtx.applyTo(&resp)
}
+ // Doc discussion run (MUL-9933): the workspace comes from the task
+ // context; the doc, discussion and resume session from their own rows.
+ if task.DocID.Valid {
+ if failure := h.applyDocCommentClaim(r, task, &resp, runtimeID, runtimeWorkspaceID); failure != nil {
+ return resp, deliveredCommentIDs, issueSnapshot, agentSkillCount, builtinSkillCount, failure
+ }
+ }
+
// Quick-create task: no issue / chat / autopilot link — workspace and
// prompt come from the task's context JSONB. Resolve workspace from
// there so the isolation check below has something to compare.
@@ -6835,6 +6843,17 @@ func (h *Handler) loadTaskForUser(w http.ResponseWriter, r *http.Request) (db.Ag
if !h.requireTaskVisible(w, r, wsID, task, http.StatusNotFound, "task not found") {
return db.AgentTaskQueue{}, false
}
+ // A doc discussion run has no project to gate it, and every doc reader
+ // sees its status. Its transcript follows the agent's own visibility, as
+ // the discussion's run list does (MUL-9933).
+ if task.DocID.Valid {
+ agent, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{ID: task.AgentID, WorkspaceID: parseUUID(wsID)})
+ actorType, actorID := h.resolveActor(r, requestUserID(r), wsID)
+ if err != nil || !h.canAccessPrivateAgent(r.Context(), agent, actorType, actorID, wsID) {
+ writeError(w, http.StatusNotFound, "task not found")
+ return db.AgentTaskQueue{}, false
+ }
+ }
return task, true
}
diff --git a/server/internal/handler/doc.go b/server/internal/handler/doc.go
index a1dfb2d410..29873671da 100644
--- a/server/internal/handler/doc.go
+++ b/server/internal/handler/doc.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "log/slog"
"net/http"
"strconv"
"strings"
@@ -87,6 +88,11 @@ type DocVersionResponse struct {
ActionRef *int32 `json:"action_ref"`
TaskID *string `json:"task_id"`
IssueID *string `json:"issue_id"`
+ // DocThreadID and DocThreadQuote name the discussion an agent was
+ // answering when it made this edit; null when it was not, or when that
+ // discussion has since been deleted.
+ DocThreadID *string `json:"doc_thread_id"`
+ DocThreadQuote *string `json:"doc_thread_quote"`
// Contributors lists everyone whose edits the version carries. Versions
// saved before live co-editing have none; their author is the one.
Contributors []DocContributor `json:"contributors"`
@@ -166,20 +172,26 @@ func docVersionToResponse(v db.DocVersion, withContent bool) DocVersionResponse
}
func docVersionRowToResponse(v db.ListDocVersionsRow) DocVersionResponse {
+ var threadQuote *string
+ if v.DocThreadID.Valid {
+ threadQuote = &v.DocThreadQuote
+ }
return DocVersionResponse{
- DocID: uuidToString(v.DocID),
- Number: v.Number,
- Title: v.Title,
- AuthorType: v.AuthorType,
- AuthorID: uuidToString(v.AuthorID),
- Message: v.Message,
- Action: v.Action,
- ActionRef: int4ToPtr(v.ActionRef),
- TaskID: uuidToPtr(v.TaskID),
- IssueID: uuidToPtr(v.IssueID),
- Contributors: parseDocContributors(v.Contributors),
- CreatedAt: timestampToString(v.CreatedAt),
- UpdatedAt: timestampToString(v.UpdatedAt),
+ DocThreadID: uuidToPtr(v.DocThreadID),
+ DocThreadQuote: threadQuote,
+ DocID: uuidToString(v.DocID),
+ Number: v.Number,
+ Title: v.Title,
+ AuthorType: v.AuthorType,
+ AuthorID: uuidToString(v.AuthorID),
+ Message: v.Message,
+ Action: v.Action,
+ ActionRef: int4ToPtr(v.ActionRef),
+ TaskID: uuidToPtr(v.TaskID),
+ IssueID: uuidToPtr(v.IssueID),
+ Contributors: parseDocContributors(v.Contributors),
+ CreatedAt: timestampToString(v.CreatedAt),
+ UpdatedAt: timestampToString(v.UpdatedAt),
}
}
@@ -647,6 +659,10 @@ func (h *Handler) DeleteDoc(w http.ResponseWriter, r *http.Request) {
writeError(w, 500, "failed to delete doc")
return
}
+ // Runs answering the doc's discussions have nothing left to answer.
+ if err := h.TaskService.CancelTasksForDoc(ctx, id); err != nil {
+ slog.Warn("delete doc: cancel doc runs failed", "doc_id", uuidToString(id), "error", err)
+ }
h.publish(protocol.EventDocDeleted, workspaceID, actorType, actorID, map[string]any{"doc_id": uuidToString(id)})
w.WriteHeader(http.StatusNoContent)
}
diff --git a/server/internal/handler/doc_comment.go b/server/internal/handler/doc_comment.go
index d05ea2866a..6971d52e6b 100644
--- a/server/internal/handler/doc_comment.go
+++ b/server/internal/handler/doc_comment.go
@@ -1,9 +1,7 @@
package handler
import (
- "context"
"encoding/json"
- "log/slog"
"net/http"
"strings"
"time"
@@ -12,9 +10,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/inbox"
- "github.com/multica-ai/multica/server/internal/projectaccess"
- "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/dbid"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -23,16 +19,14 @@ import (
// Doc comments are discussions on a doc's text (MUL-8370). A root comment
// carries the anchor — the quoted text and a little context on each side,
// which clients re-locate by text after every save — and replies hang off the
-// root, one level deep. Writing is human-only for now; agents join in a later
-// change.
+// root, one level deep. Agents take part by replying (MUL-9933): an agent can
+// answer in an existing discussion but cannot start one, and resolving,
+// reopening and deleting stay with people.
const (
docCommentMaxContent = 20000
docCommentMaxQuote = 4000
docCommentMaxContext = 64
-
- inboxTypeDocComment = "doc_comment"
- inboxTypeDocMentioned = "doc_mentioned"
)
type DocCommentResponse struct {
@@ -121,10 +115,16 @@ func (h *Handler) CreateDocComment(w http.ResponseWriter, r *http.Request) {
return
}
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ if actorType != "member" && req.ParentID == nil {
+ writeError(w, http.StatusForbidden, "agents can only reply in an existing discussion")
+ return
+ }
params := db.CreateDocCommentParams{
ID: dbid.NewV7(), WorkspaceID: wsUUID, DocID: doc.ID, Content: content,
}
var root db.DocComment
+ var replyTo *db.DocComment
if req.ParentID != nil {
parentUUID, ok := parseUUIDOrBadRequest(w, *req.ParentID, "parent_id")
if !ok {
@@ -139,7 +139,10 @@ func (h *Handler) CreateDocComment(w http.ResponseWriter, r *http.Request) {
}
return
}
- // One level of replies: answering a reply joins its discussion.
+ // One level of replies: answering a reply joins its discussion. The
+ // comment answered still decides which agent a plain reply is for.
+ answered := parent
+ replyTo = &answered
if parent.ParentID.Valid {
parent, err = h.Queries.GetDocComment(r.Context(), db.GetDocCommentParams{ID: parent.ParentID, DocID: doc.ID, WorkspaceID: wsUUID})
if err != nil {
@@ -160,9 +163,9 @@ func (h *Handler) CreateDocComment(w http.ResponseWriter, r *http.Request) {
params.AnchorSuffix = firstRunes(strings.ReplaceAll(req.AnchorSuffix, "\x00", ""), docCommentMaxContext)
}
- actorType, actorID := h.resolveActor(r, userID, workspaceID)
params.AuthorType = actorType
params.AuthorID = parseUUID(actorID)
+ params.SourceTaskID, _ = h.docTaskContext(r, actorType)
comment, err := h.Queries.CreateDocComment(r.Context(), params)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create comment")
@@ -174,75 +177,11 @@ func (h *Handler) CreateDocComment(w http.ResponseWriter, r *http.Request) {
h.publish(protocol.EventDocCommentChanged, workspaceID, actorType, actorID, map[string]any{
"doc_id": uuidToString(doc.ID), "comment_id": uuidToString(comment.ID),
})
- h.notifyDocComment(r.Context(), doc, root, comment, actorType, actorID)
+ service.NotifyDocComment(r.Context(), h.Queries, h.Bus, doc, root, comment, actorType, actorID)
+ h.triggerDocCommentAgents(r, doc, root, replyTo, comment, actorType, actorID)
writeJSON(w, http.StatusCreated, docCommentToResponse(comment))
}
-// notifyDocComment tells the members a new comment is for: everyone it
-// @mentions, and everyone who already wrote in the discussion. The author and
-// guests are never notified, and a member gets one item even when both apply.
-func (h *Handler) notifyDocComment(ctx context.Context, doc db.Doc, root, comment db.DocComment, actorType, actorID string) {
- author := uuidToString(comment.AuthorID)
- mentioned := map[string]bool{}
- for _, m := range util.ParseMentions(comment.Content) {
- if m.Type == "member" && m.ID != author {
- mentioned[m.ID] = true
- }
- }
- participants := map[string]bool{}
- if ids, err := h.Queries.ListDocThreadParticipants(ctx, db.ListDocThreadParticipantsParams{
- WorkspaceID: doc.WorkspaceID, DocID: doc.ID, RootID: root.ID,
- }); err == nil {
- for _, id := range ids {
- if s := uuidToString(id); s != author && !mentioned[s] {
- participants[s] = true
- }
- }
- }
- details, _ := json.Marshal(map[string]string{
- "doc_id": uuidToString(doc.ID),
- "thread_id": uuidToString(root.ID),
- "comment_id": uuidToString(comment.ID),
- "quote": firstRunes(root.AnchorQuote, 200),
- })
- body := firstRunes(comment.Content, 500)
- deliver := func(recipient, kind string) {
- recipientUUID, err := util.ParseUUID(recipient)
- if err != nil {
- return
- }
- // Docs are closed to guests (and to anyone outside the workspace), so
- // a notification carrying the doc's title and text must not reach them.
- member, err := h.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
- UserID: recipientUUID, WorkspaceID: doc.WorkspaceID,
- })
- if err != nil || projectaccess.IsGuestRole(member.Role) {
- return
- }
- if _, _, err := inbox.Deliver(ctx, h.Queries, h.Bus, inbox.Notification{Params: db.CreateInboxItemParams{
- ID: dbid.NewV7(),
- WorkspaceID: doc.WorkspaceID,
- RecipientType: "member",
- RecipientID: recipientUUID,
- Type: kind,
- Severity: "info",
- Title: doc.Title,
- Body: pgtype.Text{String: body, Valid: true},
- ActorType: pgtype.Text{String: actorType, Valid: true},
- ActorID: parseUUID(actorID),
- Details: details,
- }}); err != nil {
- slog.Warn("doc comment notification failed", "doc_id", uuidToString(doc.ID), "recipient_id", recipient, "error", err)
- }
- }
- for id := range mentioned {
- deliver(id, inboxTypeDocMentioned)
- }
- for id := range participants {
- deliver(id, inboxTypeDocComment)
- }
-}
-
func (h *Handler) loadDocComment(w http.ResponseWriter, r *http.Request, doc db.Doc) (db.DocComment, bool) {
commentUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "docCommentId"), "comment id")
if !ok {
diff --git a/server/internal/handler/doc_task.go b/server/internal/handler/doc_task.go
new file mode 100644
index 0000000000..d6731cd5cc
--- /dev/null
+++ b/server/internal/handler/doc_task.go
@@ -0,0 +1,228 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+
+ "github.com/jackc/pgx/v5"
+
+ "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"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// Agents in doc discussions (MUL-9933). The routing follows issue comments:
+//
+// - a comment that @mentions agents starts a run for each of them;
+// - a member's reply with no mention goes to the agent whose comment it
+// answers, else to the agent that last took part in the discussion; a
+// reply that names a member, @all or a squad goes to them instead;
+// - an agent's comment only starts runs for the agents it @mentions, never
+// for itself;
+// - who may start a run for an agent is canInvokeAgent, as on issues.
+//
+// Squads are not supported in doc discussions.
+
+// docCommentAgentIDs returns the agents a new doc comment hands work to.
+// replyTo is the comment the new one answers, before replies are folded onto
+// the discussion's first comment; nil for a new discussion.
+func (h *Handler) docCommentAgentIDs(ctx context.Context, doc db.Doc, root db.DocComment, replyTo *db.DocComment, comment db.DocComment, actorType, actorID string) []string {
+ mentions := util.ParseMentions(comment.Content)
+ var mentioned []string
+ for _, m := range mentions {
+ if m.Type != "agent" || (actorType == "agent" && m.ID == actorID) {
+ continue
+ }
+ mentioned = append(mentioned, m.ID)
+ }
+ if len(mentioned) > 0 {
+ return mentioned
+ }
+ // A comment that names anyone — a member, @all, or a squad, which doc
+ // discussions do not run — is addressed to them, not to the discussion's
+ // agent.
+ if actorType != "member" || !comment.ParentID.Valid || hasMemberMention(mentions) ||
+ hasAgentOrSquadMention(mentions) || util.HasMentionAll(mentions) {
+ return nil
+ }
+ // Answering an agent's comment goes to that agent, as replying to an
+ // agent's issue comment does, even when another agent spoke since.
+ if replyTo != nil && replyTo.AuthorType == "agent" {
+ return []string{uuidToString(replyTo.AuthorID)}
+ }
+ agentID, err := h.Queries.GetDocThreadContinuationAgent(ctx, db.GetDocThreadContinuationAgentParams{
+ DocID: doc.ID, DocThreadID: root.ID, WorkspaceID: doc.WorkspaceID,
+ })
+ if err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("doc comment: find discussion agent failed", "doc_id", uuidToString(doc.ID), "thread_id", uuidToString(root.ID), "error", err)
+ }
+ return nil
+ }
+ return []string{uuidToString(agentID)}
+}
+
+// triggerDocCommentAgents starts (or folds the comment into) a run for each
+// agent the comment hands work to. A target that cannot run — unknown, not
+// invocable by this author, archived, or without a runtime — is skipped.
+func (h *Handler) triggerDocCommentAgents(r *http.Request, doc db.Doc, root db.DocComment, replyTo *db.DocComment, comment db.DocComment, actorType, actorID string) {
+ ctx := r.Context()
+ agentIDs := h.docCommentAgentIDs(ctx, doc, root, replyTo, comment, actorType, actorID)
+ if len(agentIDs) == 0 {
+ return
+ }
+ workspaceID := uuidToString(doc.WorkspaceID)
+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)
+ seen := map[string]bool{}
+ for _, id := range agentIDs {
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+ agentUUID, err := util.ParseUUID(id)
+ if err != nil {
+ continue
+ }
+ agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: agentUUID, WorkspaceID: doc.WorkspaceID})
+ if err != nil {
+ continue
+ }
+ if !h.canInvokeAgent(ctx, agent, actorType, actorID, originator, workspaceID) || agent.ArchivedAt.Valid || !agent.RuntimeID.Valid {
+ continue
+ }
+ if _, _, err := h.TaskService.EnqueueDocCommentTask(ctx, agent, doc, comment); err != nil {
+ slog.Warn("doc comment: start agent run failed",
+ "doc_id", uuidToString(doc.ID), "comment_id", uuidToString(comment.ID), "agent_id", id, "error", err)
+ }
+ }
+}
+
+// DocTaskRunResponse is what a discussion shows of an agent's run on it: its
+// state, and whether the viewer may stop it. A run's error is shown only to
+// those who can see the agent, as its other run surfaces do.
+type DocTaskRunResponse struct {
+ ID string `json:"id"`
+ AgentID string `json:"agent_id"`
+ DocThreadID string `json:"doc_thread_id"`
+ Status string `json:"status"`
+ FailureReason string `json:"failure_reason,omitempty"`
+ Error *string `json:"error"`
+ CancelledBy *TaskCancellationActor `json:"cancelled_by,omitempty"`
+ CreatedAt string `json:"created_at"`
+ CompletedAt *string `json:"completed_at"`
+ CanCancel bool `json:"can_cancel"`
+}
+
+// ListDocTaskRuns lists a doc's recent agent runs, newest first, so its
+// discussions can show what each agent is doing.
+func (h *Handler) ListDocTaskRuns(w http.ResponseWriter, r *http.Request) {
+ userID, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ doc, ok := h.loadDoc(w, r, wsUUID)
+ if !ok {
+ return
+ }
+ rows, err := h.Queries.ListDocTasks(r.Context(), doc.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list runs")
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ visible := map[string]bool{}
+ canSee := func(agentID string) bool {
+ if v, ok := visible[agentID]; ok {
+ return v
+ }
+ agent, err := h.Queries.GetAgentInWorkspace(r.Context(), db.GetAgentInWorkspaceParams{ID: parseUUID(agentID), WorkspaceID: wsUUID})
+ visible[agentID] = err == nil && h.canAccessPrivateAgent(r.Context(), agent, actorType, actorID, workspaceID)
+ return visible[agentID]
+ }
+ resp := make([]DocTaskRunResponse, len(rows))
+ for i, t := range rows {
+ run := DocTaskRunResponse{
+ ID: uuidToString(t.ID),
+ AgentID: uuidToString(t.AgentID),
+ DocThreadID: uuidToString(t.DocThreadID),
+ Status: t.Status,
+ CancelledBy: taskCancellationActorToResponse(t),
+ CreatedAt: timestampToString(t.CreatedAt),
+ CompletedAt: timestampToPtr(t.CompletedAt),
+ }
+ if t.FailureReason.Valid {
+ run.FailureReason = t.FailureReason.String
+ }
+ if canSee(run.AgentID) {
+ run.Error = textToPtr(t.Error)
+ switch t.Status {
+ case "queued", "dispatched", "running", "waiting_local_directory", "deferred":
+ run.CanCancel = true
+ }
+ }
+ resp[i] = run
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"tasks": resp})
+}
+
+// applyDocCommentClaim fills a doc discussion run's claim: the doc, the
+// discussion and its trigger comment, plus the session and workdir this agent
+// last used on the doc. A daemon that cannot run doc discussions gets the task
+// failed with an update hint, which the discussion shows as the run's outcome.
+func (h *Handler) applyDocCommentClaim(r *http.Request, task *db.AgentTaskQueue, resp *AgentTaskResponse, runtimeID, runtimeWorkspaceID string) *claimBuildFailure {
+ ctx := r.Context()
+ if !requestHasClientCapability(r, protocol.DaemonCapabilityDocCommentV1) {
+ return h.failClaimedTaskBeforeLaunch(ctx, task,
+ "This agent's runtime is too old to answer doc comments. Update the Multica CLI on that machine, then ask again.",
+ taskfailure.ReasonAgentRuntimeVersionUnsupported,
+ "error_doc_comment_unsupported", http.StatusConflict, "daemon does not support doc discussion tasks")
+ }
+ dc, ok := service.ParseDocCommentContext(*task)
+ if !ok {
+ return h.failClaimedTaskBeforeLaunch(ctx, task,
+ "Task identity is invalid: the doc discussion context is missing.",
+ taskfailure.ReasonInvalidTaskIdentity,
+ "error_invalid_task_identity", http.StatusConflict, "doc discussion context is missing")
+ }
+ resp.WorkspaceID = dc.WorkspaceID
+ if failure := h.rejectClaimOnWorkspaceMismatch(ctx, task, resp.WorkspaceID, runtimeID, runtimeWorkspaceID, false); failure != nil {
+ return failure
+ }
+ wsUUID := parseUUID(dc.WorkspaceID)
+ doc, err := h.Queries.GetDoc(ctx, db.GetDocParams{ID: task.DocID, WorkspaceID: wsUUID})
+ if err != nil {
+ return h.rejectClaimSourceLoad(ctx, task, err, "doc", uuidToString(task.DocID))
+ }
+ root, err := h.Queries.GetDocComment(ctx, db.GetDocCommentParams{ID: task.DocThreadID, DocID: doc.ID, WorkspaceID: wsUUID})
+ if err != nil {
+ return h.rejectClaimSourceLoad(ctx, task, err, "doc discussion", uuidToString(task.DocThreadID))
+ }
+ resp.DocTitle = doc.Title
+ resp.ThreadName = doc.Title
+ resp.DocThreadQuote = root.AnchorQuote
+ // A trigger reply deleted before the claim leaves the discussion to read.
+ if trigger, err := h.Queries.GetDocComment(ctx, db.GetDocCommentParams{ID: task.DocCommentID, DocID: doc.ID, WorkspaceID: wsUUID}); err == nil {
+ resp.DocCommentContent = trigger.Content
+ resp.DocCommentAuthorName = h.actorDisplayName(ctx, wsUUID, trigger.AuthorType, trigger.AuthorID)
+ }
+
+ switch {
+ case !task.ForceFreshSession:
+ prior, err := h.Queries.GetLastDocTaskSession(ctx, db.GetLastDocTaskSessionParams{AgentID: task.AgentID, DocID: task.DocID})
+ if err == nil && prior.SessionID.Valid {
+ if prior.RuntimeID == task.RuntimeID {
+ resp.PriorSessionID = prior.SessionID.String
+ }
+ if prior.WorkDir.Valid {
+ resp.PriorWorkDir = prior.WorkDir.String
+ }
+ }
+ case task.RetryOfTaskID.Valid:
+ applyFreshSessionRetryWorkdir(*task, resp, requestHasClientCapability(r, protocol.DaemonCapabilityCheckoutKeepsWorkV1))
+ }
+ return nil
+}
diff --git a/server/internal/handler/doc_task_test.go b/server/internal/handler/doc_task_test.go
new file mode 100644
index 0000000000..867c6a381e
--- /dev/null
+++ b/server/internal/handler/doc_task_test.go
@@ -0,0 +1,503 @@
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/pkg/taskfailure"
+)
+
+// docTaskRow is the part of a doc discussion run these tests assert on.
+type docTaskRow struct {
+ ID, AgentID, Status, ThreadID, CommentID, Originator string
+}
+
+func docTasksFor(t *testing.T, docID string) []docTaskRow {
+ t.Helper()
+ rows, err := testPool.Query(context.Background(), `
+ SELECT id::text, agent_id::text, status, doc_thread_id::text, doc_comment_id::text,
+ COALESCE(originator_user_id::text, '')
+ FROM agent_task_queue WHERE doc_id = $1 ORDER BY created_at, id`, docID)
+ if err != nil {
+ t.Fatalf("list doc tasks: %v", err)
+ }
+ defer rows.Close()
+ var out []docTaskRow
+ for rows.Next() {
+ var r docTaskRow
+ if err := rows.Scan(&r.ID, &r.AgentID, &r.Status, &r.ThreadID, &r.CommentID, &r.Originator); err != nil {
+ t.Fatalf("scan doc task: %v", err)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+func TestDocCommentMentionsStartAgentRunsInTheDiscussion(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ stamp := time.Now().UnixNano()
+ writer := createHandlerTestAgent(t, fmt.Sprintf("Doc Writer %d", stamp), nil)
+ reviewer := createHandlerTestAgent(t, fmt.Sprintf("Doc Reviewer %d", stamp), nil)
+ colleague := dbfx.User(t, "Lin Mo", fmt.Sprintf("lin-mo-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, colleague, "member")
+ squad := dbfx.Squad(t, fmt.Sprintf("Doc Squad %d", stamp), writer)
+
+ post := func(body map[string]any) DocCommentResponse {
+ t.Helper()
+ var c DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", body), "id", doc.ID)).Want(http.StatusCreated).JSON(&c)
+ return c
+ }
+ asAgent := func(req *http.Request, agentID, taskID string) *http.Request {
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agentID)
+ req.Header.Set("X-Task-ID", taskID)
+ return req
+ }
+ mention := func(kind, id string) string { return fmt.Sprintf("[@X](mention://%s/%s)", kind, id) }
+
+ // A mention starts a run on the discussion, scoped to the doc.
+ root := post(map[string]any{"content": "Tighten this. " + mention("agent", writer), "anchor_quote": "Original"})
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 1 || tasks[0].AgentID != writer || tasks[0].ThreadID != root.ID || tasks[0].CommentID != root.ID || tasks[0].Status != "queued" {
+ t.Fatalf("mention should queue one run for the discussion: %+v", tasks)
+ }
+ if tasks[0].Originator != testUserID {
+ t.Fatalf("the run acts for the member who asked: %+v", tasks[0])
+ }
+ var runs struct {
+ Tasks []DocTaskRunResponse `json:"tasks"`
+ }
+ testutil.Call(t, testHandler.ListDocTaskRuns, withURLParam(newRequest("GET", "/task-runs", nil), "id", doc.ID)).Want(http.StatusOK).JSON(&runs)
+ if len(runs.Tasks) != 1 || runs.Tasks[0].DocThreadID != root.ID || runs.Tasks[0].Status != "queued" || !runs.Tasks[0].CanCancel {
+ t.Fatalf("task-runs: %+v", runs.Tasks)
+ }
+
+ // A follow-up before the run starts folds into it.
+ followUp := post(map[string]any{"content": "Also keep it short.", "parent_id": root.ID})
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 1 || tasks[0].CommentID != followUp.ID {
+ t.Fatalf("a queued run should absorb the follow-up: %+v", tasks)
+ }
+
+ // Once it ran, a reply without a mention continues with the same agent.
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1", tasks[0].ID)
+ firstRun := tasks[0].ID
+ post(map[string]any{"content": "One more pass please.", "parent_id": root.ID})
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 2 || tasks[1].AgentID != writer || tasks[1].Status != "queued" {
+ t.Fatalf("a plain reply should continue with the discussion's agent: %+v", tasks)
+ }
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1", tasks[1].ID)
+
+ // Talking to a person, or naming a squad, starts nothing.
+ post(map[string]any{"content": "What do you think? " + mention("member", colleague), "parent_id": root.ID})
+ post(map[string]any{"content": "Squad, take a look " + mention("squad", squad), "parent_id": root.ID})
+ if got := len(docTasksFor(t, doc.ID)); got != 2 {
+ t.Fatalf("member and squad mentions must not start runs, have %d", got)
+ }
+
+ // The agent replies in the discussion; its own reply does not wake it.
+ var agentReply DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, asAgent(withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Done — tightened.", "parent_id": root.ID,
+ }), "id", doc.ID), writer, firstRun)).Want(http.StatusCreated).JSON(&agentReply)
+ if agentReply.AuthorType != "agent" || agentReply.AuthorID != writer {
+ t.Fatalf("agent reply author: %+v", agentReply)
+ }
+ if n := dbfx.Count(t, "SELECT count(*) FROM doc_comment WHERE id = $1 AND source_task_id = $2", agentReply.ID, firstRun); n != 1 {
+ t.Fatal("an agent reply records the run that wrote it")
+ }
+ if got := len(docTasksFor(t, doc.ID)); got != 2 {
+ t.Fatalf("an agent's own reply must not start a run, have %d", got)
+ }
+
+ // Agents cannot start a discussion.
+ testutil.Call(t, testHandler.CreateDocComment, asAgent(withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "New topic", "anchor_quote": "Original",
+ }), "id", doc.ID), writer, firstRun)).Want(http.StatusForbidden)
+
+ // An agent handing off to another agent acts for the same person.
+ testutil.Call(t, testHandler.CreateDocComment, asAgent(withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Can you review? " + mention("agent", reviewer), "parent_id": root.ID,
+ }), "id", doc.ID), writer, firstRun)).Want(http.StatusCreated)
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 3 || tasks[2].AgentID != reviewer || tasks[2].Originator != testUserID {
+ t.Fatalf("agent mention should start the reviewer's run for the same person: %+v", tasks)
+ }
+
+ // A doc edit made by a discussion run links back to the discussion.
+ var updated DocResponse
+ testutil.Call(t, testHandler.UpdateDoc, asAgent(withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{
+ "base_revision": doc.Revision, "content": "# First\n\nTighter",
+ }), "id", doc.ID), writer, firstRun)).Want(http.StatusOK).JSON(&updated)
+ var versions struct {
+ Versions []DocVersionResponse `json:"versions"`
+ }
+ testutil.Call(t, testHandler.ListDocVersions, withURLParam(newRequest("GET", "/versions", nil), "id", doc.ID)).Want(http.StatusOK).JSON(&versions)
+ if len(versions.Versions) == 0 || versions.Versions[0].DocThreadID == nil || *versions.Versions[0].DocThreadID != root.ID ||
+ versions.Versions[0].DocThreadQuote == nil || *versions.Versions[0].DocThreadQuote != "Original" {
+ t.Fatalf("latest version should name its discussion: %+v", versions.Versions)
+ }
+ if last := versions.Versions[len(versions.Versions)-1]; last.DocThreadID != nil {
+ t.Fatalf("a member's version names no discussion: %+v", last)
+ }
+
+ // Deleting the doc stops its pending runs.
+ testutil.Call(t, testHandler.DeleteDoc, withURLParam(newRequest("DELETE", "/api/docs", nil), "id", doc.ID)).Want(http.StatusNoContent)
+ for _, task := range docTasksFor(t, doc.ID) {
+ if task.Status != "completed" && task.Status != "cancelled" {
+ t.Fatalf("doc delete left an active run: %+v", task)
+ }
+ }
+}
+
+func TestDocCommentClaimCarriesDiscussionAndResumesDocSession(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ agentID := createHandlerTestAgent(t, fmt.Sprintf("Doc Claim %d", time.Now().UnixNano()), nil)
+
+ var root DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Fix this [@A](mention://agent/" + agentID + ")", "anchor_quote": "Original",
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&root)
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 1 {
+ t.Fatalf("want one run, have %+v", tasks)
+ }
+ // An earlier run of this agent on the same doc left a session behind.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now(),
+ session_id = 'doc-session', work_dir = '/tmp/doc-workdir' WHERE id = $1`, tasks[0].ID)
+ var next DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "And this one", "parent_id": root.ID,
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&next)
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 2 {
+ t.Fatalf("want a second run, have %+v", tasks)
+ }
+
+ task, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(tasks[1].ID))
+ if err != nil {
+ t.Fatalf("load task: %v", err)
+ }
+ resp := taskToResponse(task, testWorkspaceID)
+ req := newRequest("POST", "/claim", nil)
+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityDocCommentV1)
+ if failure := testHandler.applyDocCommentClaim(req, &task, &resp, uuidToString(task.RuntimeID), testWorkspaceID); failure != nil {
+ t.Fatalf("claim failed: %+v", failure)
+ }
+ if resp.WorkspaceID != testWorkspaceID || resp.DocTitle != doc.Title || resp.DocThreadQuote != "Original" ||
+ resp.DocCommentContent != "And this one" || resp.DocCommentAuthorName == "" {
+ t.Fatalf("claim context: %+v", resp)
+ }
+ if resp.PriorSessionID != "doc-session" || resp.PriorWorkDir != "/tmp/doc-workdir" {
+ t.Fatalf("claim should resume the agent's session on this doc: session=%q workdir=%q", resp.PriorSessionID, resp.PriorWorkDir)
+ }
+
+ // A run whose doc is gone is cancelled instead of dispatched.
+ testPool.Exec(context.Background(), "UPDATE agent_task_queue SET doc_id = gen_random_uuid() WHERE id = $1", tasks[1].ID)
+ orphan, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(tasks[1].ID))
+ if err != nil {
+ t.Fatalf("load task: %v", err)
+ }
+ orphanResp := taskToResponse(orphan, testWorkspaceID)
+ if failure := testHandler.applyDocCommentClaim(req, &orphan, &orphanResp, uuidToString(orphan.RuntimeID), testWorkspaceID); failure == nil {
+ t.Fatal("a run whose doc is gone must not be dispatched")
+ }
+ var status string
+ dbfx.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id = $1", tasks[1].ID).Scan(&status)
+ if status != "cancelled" {
+ t.Fatalf("orphaned doc run status = %q, want cancelled", status)
+ }
+ testPool.Exec(context.Background(), "DELETE FROM agent_task_queue WHERE id = $1", tasks[1].ID)
+}
+
+// A run that ends without replying still answers its discussion with its
+// final output; one that replied gets no second reply.
+func TestDocCommentRunWithoutReplyPostsItsOutput(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ agentID := createHandlerTestAgent(t, fmt.Sprintf("Doc Fallback %d", time.Now().UnixNano()), nil)
+ var root DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Summarize [@A](mention://agent/" + agentID + ")", "anchor_quote": "Original",
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&root)
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 1 {
+ t.Fatalf("want one run, have %+v", tasks)
+ }
+ complete := func(taskID string) {
+ t.Helper()
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'running', started_at = now(), dispatched_at = now() WHERE id = $1", taskID)
+ if _, err := testHandler.TaskService.CompleteTask(context.Background(),
+ parseUUID(taskID), []byte(`{"output":"The section says we ship Friday."}`), "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ }
+ replies := func() int {
+ return dbfx.Count(t, "SELECT count(*) FROM doc_comment WHERE doc_id = $1 AND parent_id = $2 AND author_type = 'agent' AND author_id = $3", doc.ID, root.ID, agentID)
+ }
+
+ // A comment the run left in another discussion does not answer this one.
+ var other DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Unrelated", "anchor_quote": "First",
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&other)
+ elsewhere := withURLParam(newRequest("POST", "/comments", map[string]any{"content": "Noted.", "parent_id": other.ID}), "id", doc.ID)
+ elsewhere.Header.Set("X-Actor-Source", "task_token")
+ elsewhere.Header.Set("X-Agent-ID", agentID)
+ elsewhere.Header.Set("X-Task-ID", tasks[0].ID)
+ testutil.Call(t, testHandler.CreateDocComment, elsewhere).Want(http.StatusCreated)
+ notified := func() int {
+ return dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE recipient_id = $1 AND type = 'doc_comment' AND details->>'thread_id' = $2", testUserID, root.ID)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), "DELETE FROM inbox_item WHERE details->>'doc_id' = $1", doc.ID)
+ })
+
+ complete(tasks[0].ID)
+ if notified() != 1 {
+ t.Fatalf("the fallback reply should notify the discussion's author like any reply, have %d", notified())
+ }
+ if replies() != 1 {
+ t.Fatalf("a run that never replied should answer with its output, have %d agent replies", replies())
+ }
+ if n := dbfx.Count(t, "SELECT count(*) FROM doc_comment WHERE parent_id = $1 AND source_task_id = $2 AND content = 'The section says we ship Friday.'", root.ID, tasks[0].ID); n != 1 {
+ t.Fatal("the fallback reply records its run and carries the output")
+ }
+
+ // The next run replies itself; completion adds nothing.
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Shorter please", "parent_id": root.ID,
+ }), "id", doc.ID)).Want(http.StatusCreated)
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 2 {
+ t.Fatalf("want a second run, have %+v", tasks)
+ }
+ req := withURLParam(newRequest("POST", "/comments", map[string]any{"content": "Friday.", "parent_id": root.ID}), "id", doc.ID)
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agentID)
+ req.Header.Set("X-Task-ID", tasks[1].ID)
+ testutil.Call(t, testHandler.CreateDocComment, req).Want(http.StatusCreated)
+ complete(tasks[1].ID)
+ if replies() != 2 {
+ t.Fatalf("a run that replied must not get a fallback reply, have %d agent replies", replies())
+ }
+}
+
+// A daemon that cannot run doc discussions must not get one: it would build an
+// issue prompt with no issue. The run fails before launch with an update hint.
+func TestDocCommentClaimFailsOnDaemonWithoutDocSupport(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ agentID := createHandlerTestAgent(t, fmt.Sprintf("Doc Old Daemon %d", time.Now().UnixNano()), nil)
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Fix this [@A](mention://agent/" + agentID + ")", "anchor_quote": "Original",
+ }), "id", doc.ID)).Want(http.StatusCreated)
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 1 {
+ t.Fatalf("want one run, have %+v", tasks)
+ }
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1", tasks[0].ID)
+ task, err := testHandler.Queries.GetAgentTask(context.Background(), parseUUID(tasks[0].ID))
+ if err != nil {
+ t.Fatalf("load task: %v", err)
+ }
+ resp := taskToResponse(task, testWorkspaceID)
+ if failure := testHandler.applyDocCommentClaim(newRequest("POST", "/claim", nil), &task, &resp, uuidToString(task.RuntimeID), testWorkspaceID); failure == nil {
+ t.Fatal("a daemon without doc support must not get the run")
+ }
+ var status, reason string
+ dbfx.QueryRow(t, "SELECT status, COALESCE(failure_reason, '') FROM agent_task_queue WHERE id = $1", tasks[0].ID).Scan(&status, &reason)
+ if status != "failed" || reason != string(taskfailure.ReasonAgentRuntimeVersionUnsupported) {
+ t.Fatalf("run = %s/%s, want failed with runtime_version_unsupported", status, reason)
+ }
+}
+
+// A follow-up folded into a queued run moves the run to the follow-up's
+// author: who it acts for, and the connected apps it carries.
+func TestDocCommentFollowUpMovesQueuedRunToItsAuthor(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ stamp := time.Now().UnixNano()
+ agentID := createHandlerTestAgent(t, fmt.Sprintf("Doc Fold %d", stamp), nil)
+ colleague := dbfx.User(t, "Qin Lu", fmt.Sprintf("qin-lu-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, colleague, "member")
+
+ var root DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Check this [@A](mention://agent/" + agentID + ")", "anchor_quote": "Original",
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&root)
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 1 || tasks[0].Originator != testUserID {
+ t.Fatalf("want one run for the first member, have %+v", tasks)
+ }
+ // Stand in for the first member's connected apps on the queued run.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET runtime_mcp_overlay = '{"servers":["first-member"]}'::jsonb,
+ runtime_connected_apps = '[{"toolkit":"first-member"}]'::jsonb WHERE id = $1`, tasks[0].ID)
+
+ req := withURLParam(newRequest("POST", "/comments", map[string]any{"content": "Also the intro", "parent_id": root.ID}), "id", doc.ID)
+ req.Header.Set("X-User-ID", colleague)
+ testutil.Call(t, testHandler.CreateDocComment, req).Want(http.StatusCreated)
+
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 1 || tasks[0].Originator != colleague {
+ t.Fatalf("the folded run should act for the follow-up's author: %+v", tasks)
+ }
+ var accountable, evidence string
+ var keptApps bool
+ dbfx.QueryRow(t, `SELECT COALESCE(accountable_user_id::text, ''), COALESCE(trigger_evidence_ref_id::text, ''),
+ runtime_mcp_overlay IS NOT NULL OR runtime_connected_apps IS NOT NULL
+ FROM agent_task_queue WHERE id = $1`, tasks[0].ID).Scan(&accountable, &evidence, &keptApps)
+ if accountable != colleague || evidence != tasks[0].CommentID {
+ t.Fatalf("attribution must move with the run: accountable=%s evidence=%s", accountable, evidence)
+ }
+ if keptApps {
+ t.Fatal("the run must not keep the first member's connected apps")
+ }
+}
+
+// Answering an agent's comment goes to that agent, even when another agent
+// spoke in the discussion since.
+func TestDocCommentReplyGoesToTheAgentItAnswers(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ testPool.Exec(ctx, "DELETE FROM doc_comment WHERE doc_id = $1", doc.ID)
+ })
+ stamp := time.Now().UnixNano()
+ first := createHandlerTestAgent(t, fmt.Sprintf("Doc First %d", stamp), nil)
+ second := createHandlerTestAgent(t, fmt.Sprintf("Doc Second %d", stamp), nil)
+ var root DocCommentResponse
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "[@A](mention://agent/" + first + ") [@B](mention://agent/" + second + ") thoughts?", "anchor_quote": "Original",
+ }), "id", doc.ID)).Want(http.StatusCreated).JSON(&root)
+ tasks := docTasksFor(t, doc.ID)
+ if len(tasks) != 2 {
+ t.Fatalf("want a run per agent, have %+v", tasks)
+ }
+ runOf := map[string]string{tasks[0].AgentID: tasks[0].ID, tasks[1].AgentID: tasks[1].ID}
+ dbfx.Exec(t, "UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE doc_id = $1", doc.ID)
+ reply := func(agentID, content string) DocCommentResponse {
+ t.Helper()
+ var c DocCommentResponse
+ req := withURLParam(newRequest("POST", "/comments", map[string]any{"content": content, "parent_id": root.ID}), "id", doc.ID)
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agentID)
+ req.Header.Set("X-Task-ID", runOf[agentID])
+ testutil.Call(t, testHandler.CreateDocComment, req).Want(http.StatusCreated).JSON(&c)
+ return c
+ }
+ firstReply := reply(first, "First take.")
+ reply(second, "Second take.")
+
+ testutil.Call(t, testHandler.CreateDocComment, withURLParam(newRequest("POST", "/comments", map[string]any{
+ "content": "Can you expand on that?", "parent_id": firstReply.ID,
+ }), "id", doc.ID)).Want(http.StatusCreated)
+ tasks = docTasksFor(t, doc.ID)
+ if len(tasks) != 3 || tasks[2].AgentID != first {
+ t.Fatalf("a reply to the first agent's comment should go to it: %+v", tasks)
+ }
+}
+
+// The run list shows each run's state to every doc reader, but its error and
+// the way to stop it only to those who can see the agent.
+func TestDocTaskRunsHideDetailsOfAgentsTheViewerCannotSee(t *testing.T) {
+ doc := createDocForTest(t)
+ t.Cleanup(func() {
+ ctx := context.Background()
+ testPool.Exec(ctx, "DELETE FROM agent_task_queue WHERE doc_id = $1", doc.ID)
+ })
+ stamp := time.Now().UnixNano()
+ private := dbfx.Agent(t, fmt.Sprintf("Doc Private %d", stamp), handlerTestRuntimeID(t), testutil.Cols{"visibility": "private"})
+ t.Cleanup(func() { testPool.Exec(context.Background(), "DELETE FROM agent WHERE id = $1", private) })
+ colleague := dbfx.User(t, "He Yu", fmt.Sprintf("he-yu-%[email protected]", stamp))
+ dbfx.Member(t, testWorkspaceID, colleague, "member")
+ thread := "01a20000-0000-7000-8000-000000000001"
+ docContext := testutil.Raw(fmt.Sprintf(`'{"type":"doc_comment","workspace_id":"%s"}'::jsonb`, testWorkspaceID))
+ failedRun := dbfx.Task(t, private, testutil.Cols{"doc_id": doc.ID, "doc_thread_id": thread, "doc_comment_id": thread,
+ "status": "failed", "error": "secret path /home/owner/work", "failure_reason": "timeout",
+ "runtime_id": handlerTestRuntimeID(t), "completed_at": testutil.Raw("now()"), "context": docContext})
+ dbfx.Task(t, private, testutil.Cols{"doc_id": doc.ID, "doc_thread_id": thread, "doc_comment_id": thread, "status": "running",
+ "runtime_id": handlerTestRuntimeID(t), "started_at": testutil.Raw("now()"), "context": docContext})
+
+ list := func(as string) []DocTaskRunResponse {
+ t.Helper()
+ var out struct {
+ Tasks []DocTaskRunResponse `json:"tasks"`
+ }
+ req := withURLParam(newRequest("GET", "/task-runs", nil), "id", doc.ID)
+ req.Header.Set("X-User-ID", as)
+ testutil.Call(t, testHandler.ListDocTaskRuns, req).Want(http.StatusOK).JSON(&out)
+ return out.Tasks
+ }
+ for _, run := range list(colleague) {
+ if run.Error != nil || run.CanCancel {
+ t.Fatalf("a member who cannot see the agent got its details: %+v", run)
+ }
+ if run.Status == "" || run.DocThreadID != thread {
+ t.Fatalf("a member still sees the run's state: %+v", run)
+ }
+ }
+ var sawError, canStop bool
+ for _, run := range list(testUserID) {
+ sawError = sawError || run.Error != nil
+ canStop = canStop || (run.Status == "running" && run.CanCancel)
+ }
+ if !sawError || !canStop {
+ t.Fatal("the agent's owner sees the error and can stop the running run")
+ }
+
+ // The run's transcript follows the agent's visibility too.
+ transcript := func(as string) *testutil.Response {
+ req := withURLParam(newRequestAs(as, http.MethodGet, "/api/tasks/"+failedRun+"/messages", nil), "taskId", failedRun)
+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))
+ return testutil.Call(t, testHandler.ListTaskMessagesByUser, req)
+ }
+ transcript(colleague).Want(http.StatusNotFound)
+ transcript(testUserID).Want(http.StatusOK)
+
+ // A long-running run stays listed however many runs finished after it.
+ dbfx.Exec(t, `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, doc_id, doc_thread_id, doc_comment_id, created_at, completed_at)
+ SELECT $1, $2, 'completed', 0, $3, $4, $4, now() + make_interval(secs => g), now() + make_interval(secs => g)
+ FROM generate_series(1, 201) AS g`, private, handlerTestRuntimeID(t), doc.ID, thread)
+ var running int
+ for _, run := range list(testUserID) {
+ if run.Status == "running" {
+ running++
+ }
+ }
+ if running != 1 {
+ t.Fatalf("the running run must stay listed behind 201 newer finished runs, have %d running", running)
+ }
+}
diff --git a/server/internal/handler/guest_access_test.go b/server/internal/handler/guest_access_test.go
index b1fd0c4fd3..be074a7ff6 100644
--- a/server/internal/handler/guest_access_test.go
+++ b/server/internal/handler/guest_access_test.go
@@ -15,6 +15,7 @@ import (
"github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -191,7 +192,7 @@ func TestDemotedGuestCannotReadProjectlessNotifications(t *testing.T) {
notify := func(issueID, title string, archived, read bool) string {
cols := testutil.Cols{
"workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": user,
- "type": inboxTypeDocComment, "severity": "info", "title": title, "body": "quoted doc text",
+ "type": service.InboxTypeDocComment, "severity": "info", "title": title, "body": "quoted doc text",
"archived": archived, "read": read,
}
if issueID != "" {
diff --git a/server/internal/service/builtin_skills/multica-platform/references/docs.md b/server/internal/service/builtin_skills/multica-platform/references/docs.md
index da320be892..0d84635689 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/docs.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/docs.md
@@ -61,10 +61,19 @@ Resolved threads are hidden unless you pass `--include-resolved`; each root
comment's `anchor_quote` is the text it was left on, and `--output json` has
the full comment text.
-Writing in doc discussions is reserved for people: commenting, replying,
-resolving and reopening all answer `403` to agent credentials, and the CLI has
-no command for them. Report which threads you addressed in your issue
-comment, so the reviewer can resolve them.
+You can reply in an existing thread:
+
+```bash
+multica doc comment list <doc-id> --thread <comment-id> --output json # one thread
+multica doc comment add <doc-id> --parent <comment-id> --content-file ./reply.md
+```
+
+Starting a thread, resolving, reopening and deleting are reserved for people:
+they answer `403` to agent credentials. A reply that @mentions an agent starts
+a run for it, as an issue comment does. When someone @mentions you in a
+thread, the run's prompt names the doc and the thread, and your reply goes
+there. When you addressed threads while working on an issue, say which in
+your issue comment, so the reviewer can resolve them.
## History and restore
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 9b4b5b4617..81461a9016 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -749,7 +749,8 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
"Prefer `doc edit` for a\ntargeted change",
"never retry the same body with a newer revision",
"multica doc comment list <doc-id>",
- "Writing in doc discussions is reserved for people",
+ "Starting a thread, resolving, reopening and deleting are reserved for people",
+ "multica doc comment add <doc-id> --parent <comment-id>",
"multica doc restore <doc-id> --version 3 --base-revision <revision>",
"To undo one change and keep the rest, use `doc edit` instead",
"Deleting a doc or a folder answers `403`",
diff --git a/server/internal/service/doc_comment_notify.go b/server/internal/service/doc_comment_notify.go
new file mode 100644
index 0000000000..6691a0b748
--- /dev/null
+++ b/server/internal/service/doc_comment_notify.go
@@ -0,0 +1,98 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "unicode/utf8"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/inbox"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// Inbox types for doc discussions.
+const (
+ InboxTypeDocComment = "doc_comment"
+ InboxTypeDocMentioned = "doc_mentioned"
+)
+
+// NotifyDocComment tells the members a new doc comment is for: everyone it
+// @mentions, and everyone who already wrote in the discussion. The author and
+// guests are never notified, and a member gets one item even when both apply.
+// Shared by comments posted through the API and the reply the platform posts
+// for a doc discussion run that ended without replying.
+func NotifyDocComment(ctx context.Context, q *db.Queries, bus *events.Bus, doc db.Doc, root, comment db.DocComment, actorType, actorID string) {
+ author := util.UUIDToString(comment.AuthorID)
+ mentioned := map[string]bool{}
+ for _, m := range util.ParseMentions(comment.Content) {
+ if m.Type == "member" && m.ID != author {
+ mentioned[m.ID] = true
+ }
+ }
+ participants := map[string]bool{}
+ if ids, err := q.ListDocThreadParticipants(ctx, db.ListDocThreadParticipantsParams{
+ WorkspaceID: doc.WorkspaceID, DocID: doc.ID, RootID: root.ID,
+ }); err == nil {
+ for _, id := range ids {
+ if s := util.UUIDToString(id); s != author && !mentioned[s] {
+ participants[s] = true
+ }
+ }
+ }
+ details, _ := json.Marshal(map[string]string{
+ "doc_id": util.UUIDToString(doc.ID),
+ "thread_id": util.UUIDToString(root.ID),
+ "comment_id": util.UUIDToString(comment.ID),
+ "quote": firstRunes(root.AnchorQuote, 200),
+ })
+ body := firstRunes(comment.Content, 500)
+ actorUUID, _ := util.ParseUUID(actorID)
+ deliver := func(recipient, kind string) {
+ recipientUUID, err := util.ParseUUID(recipient)
+ if err != nil {
+ return
+ }
+ // Docs are closed to guests (and to anyone outside the workspace), so
+ // a notification carrying the doc's title and text must not reach them.
+ member, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: recipientUUID, WorkspaceID: doc.WorkspaceID,
+ })
+ if err != nil || projectaccess.IsGuestRole(member.Role) {
+ return
+ }
+ if _, _, err := inbox.Deliver(ctx, q, bus, inbox.Notification{Params: db.CreateInboxItemParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: doc.WorkspaceID,
+ RecipientType: "member",
+ RecipientID: recipientUUID,
+ Type: kind,
+ Severity: "info",
+ Title: doc.Title,
+ Body: pgtype.Text{String: body, Valid: true},
+ ActorType: pgtype.Text{String: actorType, Valid: true},
+ ActorID: actorUUID,
+ Details: details,
+ }}); err != nil {
+ slog.Warn("doc comment notification failed", "doc_id", util.UUIDToString(doc.ID), "recipient_id", recipient, "error", err)
+ }
+ }
+ for id := range mentioned {
+ deliver(id, InboxTypeDocMentioned)
+ }
+ for id := range participants {
+ deliver(id, InboxTypeDocComment)
+ }
+}
+
+func firstRunes(s string, n int) string {
+ if utf8.RuneCountInString(s) <= n {
+ return s
+ }
+ return string([]rune(s)[:n])
+}
diff --git a/server/internal/service/doc_task.go b/server/internal/service/doc_task.go
new file mode 100644
index 0000000000..91e8becfb9
--- /dev/null
+++ b/server/internal/service/doc_task.go
@@ -0,0 +1,258 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "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"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/pkg/redact"
+)
+
+// DocCommentContextType marks a run started from a doc discussion (MUL-9933).
+const DocCommentContextType = "doc_comment"
+
+// DocCommentContext is the task context of a doc discussion run. The doc and
+// discussion live in their own columns; the workspace is kept here so the
+// run's events and daemon routes still resolve once the doc is deleted.
+type DocCommentContext struct {
+ Type string `json:"type"`
+ WorkspaceID string `json:"workspace_id"`
+}
+
+// ParseDocCommentContext returns the doc discussion context of task, if it is
+// a doc discussion run.
+func ParseDocCommentContext(task db.AgentTaskQueue) (DocCommentContext, bool) {
+ if !task.DocID.Valid || len(task.Context) == 0 {
+ return DocCommentContext{}, false
+ }
+ var dc DocCommentContext
+ if err := json.Unmarshal(task.Context, &dc); err != nil || dc.Type != DocCommentContextType {
+ return DocCommentContext{}, false
+ }
+ return dc, true
+}
+
+// EnqueueDocCommentTask starts agent's run for a doc discussion, triggered by
+// comment. When the agent already has a run for the discussion that has not
+// started, the comment folds into it instead (merged is true): the run reads
+// the whole discussion when it starts, so the newer comment becomes its
+// trigger and the run now acts for that comment's human. The caller has
+// checked that the comment's author may invoke agent.
+func (s *TaskService) EnqueueDocCommentTask(ctx context.Context, agent db.Agent, doc db.Doc, comment db.DocComment) (task db.AgentTaskQueue, merged bool, err error) {
+ if agent.ArchivedAt.Valid {
+ return db.AgentTaskQueue{}, false, fmt.Errorf("agent is archived")
+ }
+ if !agent.RuntimeID.Valid {
+ return db.AgentTaskQueue{}, false, fmt.Errorf("agent has no runtime")
+ }
+ threadID := comment.ID
+ if comment.ParentID.Valid {
+ threadID = comment.ParentID
+ }
+
+ attr := s.attributionFromDocComment(ctx, comment)
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ return db.AgentTaskQueue{}, false, err
+ }
+ attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
+ contextJSON, err := json.Marshal(DocCommentContext{Type: DocCommentContextType, WorkspaceID: util.UUIDToString(doc.WorkspaceID)})
+ if err != nil {
+ return db.AgentTaskQueue{}, false, fmt.Errorf("marshal doc comment context: %w", err)
+ }
+ summary := pgtype.Text{}
+ if text := truncateForSummary(comment.Content, triggerSummaryMaxLen); text != "" {
+ summary = pgtype.Text{String: text, Valid: true}
+ }
+ overlay := s.buildRuntimeMCPOverlay(ctx, attr.UserID, agent)
+
+ err = s.runInTx(ctx, func(qtx *db.Queries) error {
+ // Agent row first, as on every enqueue path; holding it also
+ // serializes two comments racing to start the same agent's run.
+ if _, err := qtx.GetAgentForClaimUpdate(ctx, agent.ID); err != nil {
+ return fmt.Errorf("lock agent: %w", err)
+ }
+ queued, err := qtx.GetQueuedDocThreadTaskForUpdate(ctx, db.GetQueuedDocThreadTaskForUpdateParams{
+ DocID: doc.ID, DocThreadID: threadID, AgentID: agent.ID,
+ })
+ if err == nil {
+ task, err = qtx.MergeDocCommentIntoQueuedTask(ctx, db.MergeDocCommentIntoQueuedTaskParams{
+ ID: queued.ID,
+ DocCommentID: comment.ID,
+ TriggerSummary: summary,
+ OriginatorUserID: attr.UserID,
+ AccountableUserID: attr.AccountableUserID,
+ OriginatorSource: attrSource,
+ DelegatedFromTaskID: attrDelegatedFrom,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
+ RuntimeMcpOverlay: overlay.Overlay,
+ RuntimeConnectedApps: overlay.ConnectedApps,
+ })
+ merged = err == nil
+ return err
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("find queued doc task: %w", err)
+ }
+ task, err = qtx.CreateDocCommentTask(ctx, db.CreateDocCommentTaskParams{
+ ID: dbid.NewV7(),
+ AgentID: agent.ID,
+ Priority: priorityToInt("high"),
+ Context: contextJSON,
+ TriggerSummary: summary,
+ DocID: doc.ID,
+ DocThreadID: threadID,
+ DocCommentID: comment.ID,
+ OriginatorUserID: attr.UserID,
+ AccountableUserID: attr.AccountableUserID,
+ RuntimeMcpOverlay: overlay.Overlay,
+ RuntimeConnectedApps: overlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ DelegatedFromTaskID: attrDelegatedFrom,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("agent or workspace is gone")
+ }
+ return err
+ })
+ if err != nil {
+ return db.AgentTaskQueue{}, false, err
+ }
+ s.RecordHumanDelegation(ctx, attr)
+ if merged {
+ s.BroadcastTaskCoalesced(ctx, task)
+ return task, true, nil
+ }
+ slog.Info("doc comment task enqueued",
+ "task_id", util.UUIDToString(task.ID),
+ "agent_id", util.UUIDToString(agent.ID),
+ "doc_id", util.UUIDToString(doc.ID),
+ "doc_thread_id", util.UUIDToString(threadID),
+ )
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
+ s.NotifyTaskEnqueued(ctx, task)
+ return task, false, nil
+}
+
+// attributionFromDocComment resolves who a doc discussion run acts for, the
+// same way an issue comment does: a member's comment is that member's direct
+// action; an agent's comment inherits the human behind the run that wrote it.
+func (s *TaskService) attributionFromDocComment(ctx context.Context, comment db.DocComment) attribution.Result {
+ facts := attribution.CommentFacts{
+ CommentID: comment.ID,
+ AuthorType: comment.AuthorType,
+ AuthorID: comment.AuthorID,
+ CreatedAt: comment.CreatedAt,
+ }
+ 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
+ }
+ }
+ attr := attribution.ClassifyComment(facts, attribution.SourceDelegation)
+ attr.EvidenceKind = attribution.EvidenceDocComment
+ return attr
+}
+
+// CancelTasksForDoc cancels every active run on a deleted doc, the doc
+// counterpart of CancelTasksForIssue.
+func (s *TaskService) CancelTasksForDoc(ctx context.Context, docID pgtype.UUID) error {
+ var cancelled []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelAgentTasksByDoc(ctx, docID)
+ if err != nil {
+ return err
+ }
+ return SettleTerminalTaskState(ctx, qtx, cancelled...)
+ }); err != nil {
+ return err
+ }
+ for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
+ }
+ for _, agentID := range distinctAgentIDs(cancelled) {
+ s.ReconcileAgentStatus(ctx, agentID)
+ }
+ s.notifyTasksFinished(cancelled)
+ return nil
+}
+
+// ensureDocReply posts a completed run's final output into its discussion
+// when the agent ended without replying there, the doc counterpart of the
+// issue fallback comment: a discussion never waits on a run that already
+// finished. The reply notifies members like any other reply.
+func (s *TaskService) ensureDocReply(ctx context.Context, task db.AgentTaskQueue, result []byte) {
+ dc, ok := ParseDocCommentContext(task)
+ if !ok {
+ return
+ }
+ wsUUID, err := util.ParseUUID(dc.WorkspaceID)
+ if err != nil {
+ return
+ }
+ replied, err := s.Queries.HasDocTaskReply(ctx, db.HasDocTaskReplyParams{
+ WorkspaceID: wsUUID, DocID: task.DocID, TaskID: task.ID, DocThreadID: task.DocThreadID,
+ })
+ if err != nil || replied {
+ return
+ }
+ var payload protocol.TaskCompletedPayload
+ if json.Unmarshal(result, &payload) != nil || payload.Output == "" {
+ return
+ }
+ body := util.DecodeEscapedAgentOutput(payload.Output)
+ if isTrivialDoneOutput(body) {
+ return
+ }
+ // The doc or the discussion may have been deleted while the run worked.
+ doc, err := s.Queries.GetDoc(ctx, db.GetDocParams{ID: task.DocID, WorkspaceID: wsUUID})
+ if err != nil {
+ return
+ }
+ root, err := s.Queries.GetDocComment(ctx, db.GetDocCommentParams{ID: task.DocThreadID, DocID: task.DocID, WorkspaceID: wsUUID})
+ if err != nil {
+ return
+ }
+ comment, err := s.Queries.CreateDocComment(ctx, db.CreateDocCommentParams{
+ ID: dbid.NewV7(),
+ WorkspaceID: wsUUID,
+ DocID: task.DocID,
+ ParentID: task.DocThreadID,
+ AuthorType: "agent",
+ AuthorID: task.AgentID,
+ Content: truncateFallbackCommentBody(redact.Text(body), maxSynthesizedFallbackCommentRunes),
+ SourceTaskID: task.ID,
+ })
+ if err != nil {
+ slog.Warn("doc comment task: fallback reply failed", "task_id", util.UUIDToString(task.ID), "error", err)
+ return
+ }
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventDocCommentChanged,
+ WorkspaceID: dc.WorkspaceID,
+ ActorType: "agent",
+ ActorID: util.UUIDToString(task.AgentID),
+ Payload: map[string]any{
+ "doc_id": util.UUIDToString(task.DocID), "comment_id": util.UUIDToString(comment.ID),
+ },
+ })
+ NotifyDocComment(ctx, s.Queries, s.Bus, doc, root, comment, "agent", util.UUIDToString(task.AgentID))
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 23a0e41abe..5742f3da42 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1038,6 +1038,8 @@ func (s *TaskService) taskMetricsContext(ctx context.Context, task db.AgentTaskQ
}
case task.AutopilotRunID.Valid:
source = "autopilot"
+ case task.DocID.Valid:
+ source = "doc_comment"
default:
if _, ok := s.parseQuickCreateContext(task); ok {
source = "quick_create"
@@ -5063,6 +5065,10 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt
}
}
+ if task.DocID.Valid {
+ s.ensureDocReply(ctx, task, result)
+ }
+
// Quick-create tasks: locate the issue the agent just created and push
// an inbox confirmation to the requester. The agent has no issue / chat
// link, so the regular completion paths above don't apply. We find the
@@ -5901,8 +5907,8 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {
// retryEligible reports whether a failed task qualifies for an automatic retry
// attempt: an infrastructure-shaped failure_reason, remaining attempt budget,
-// not an autopilot run, not a Triage run, and linked to an issue or chat
-// session. Shared by FailTask's in-transaction retry and the orphan sweeper's
+// not an autopilot run, not a Triage run, and linked to an issue, chat
+// session or doc discussion. Shared by FailTask's in-transaction retry and the orphan sweeper's
// MaybeRetryFailedTask so both agree on which failures re-run.
//
// A Triage run is excluded for the reason autopilot runs are (MUL-7189 §5.6):
@@ -5914,7 +5920,7 @@ func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
t.Attempt < retryAttemptCeiling(failureReason, t.MaxAttempts) &&
!t.AutopilotRunID.Valid &&
!IsTriageTask(t) &&
- (t.IssueID.Valid || t.ChatSessionID.Valid || isSourceContextQuickCreateTask(t))
+ (t.IssueID.Valid || t.ChatSessionID.Valid || t.DocID.Valid || isSourceContextQuickCreateTask(t))
}
func isSourceContextQuickCreateTask(task db.AgentTaskQueue) bool {
@@ -7892,6 +7898,10 @@ func taskEvent(eventType, workspaceID string, task db.AgentTaskQueue, extra ...m
payload["chat_session_id"] = chatSessionID
e.ChatSessionID = chatSessionID
}
+ // doc_id lets an open doc refresh its discussions' run status.
+ if task.DocID.Valid {
+ payload["doc_id"] = util.UUIDToString(task.DocID)
+ }
for _, fields := range extra {
for key, value := range fields {
payload[key] = value
@@ -8039,6 +8049,11 @@ func (s *TaskService) ResolveTaskScopeChecked(ctx context.Context, task db.Agent
if qc, ok := s.parseQuickCreateContext(task); ok {
return TaskScope{WorkspaceID: qc.WorkspaceID}, nil
}
+ // Doc discussion runs carry their workspace in the context too, so a run
+ // cancelled by its doc's deletion still resolves.
+ if dc, ok := ParseDocCommentContext(task); ok {
+ return TaskScope{WorkspaceID: dc.WorkspaceID}, nil
+ }
if lookupErr != nil {
return TaskScope{}, fmt.Errorf("resolve task workspace: %w", lookupErr)
}
diff --git a/server/migrations/752_doc_comment_agent_runs.down.sql b/server/migrations/752_doc_comment_agent_runs.down.sql
new file mode 100644
index 0000000000..05b5330967
--- /dev/null
+++ b/server/migrations/752_doc_comment_agent_runs.down.sql
@@ -0,0 +1,6 @@
+ALTER TABLE doc_comment DROP COLUMN IF EXISTS source_task_id;
+
+ALTER TABLE agent_task_queue
+ DROP COLUMN IF EXISTS doc_comment_id,
+ DROP COLUMN IF EXISTS doc_thread_id,
+ DROP COLUMN IF EXISTS doc_id;
diff --git a/server/migrations/752_doc_comment_agent_runs.up.sql b/server/migrations/752_doc_comment_agent_runs.up.sql
new file mode 100644
index 0000000000..161041640c
--- /dev/null
+++ b/server/migrations/752_doc_comment_agent_runs.up.sql
@@ -0,0 +1,10 @@
+-- Agents answer doc discussions (MUL-9933). A run started from a discussion
+-- records the doc, the discussion's first comment and the comment that
+-- triggered it; an agent's reply records the run that wrote it. No foreign
+-- keys: doc delete cancels the doc's runs in application code.
+ALTER TABLE agent_task_queue
+ ADD COLUMN IF NOT EXISTS doc_id UUID,
+ ADD COLUMN IF NOT EXISTS doc_thread_id UUID,
+ ADD COLUMN IF NOT EXISTS doc_comment_id UUID;
+
+ALTER TABLE doc_comment ADD COLUMN IF NOT EXISTS source_task_id UUID;
diff --git a/server/migrations/753_agent_task_queue_doc_idx.down.sql b/server/migrations/753_agent_task_queue_doc_idx.down.sql
new file mode 100644
index 0000000000..825715d3fa
--- /dev/null
+++ b/server/migrations/753_agent_task_queue_doc_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_doc;
diff --git a/server/migrations/753_agent_task_queue_doc_idx.up.sql b/server/migrations/753_agent_task_queue_doc_idx.up.sql
new file mode 100644
index 0000000000..902e17b579
--- /dev/null
+++ b/server/migrations/753_agent_task_queue_doc_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_doc ON agent_task_queue (doc_id, created_at DESC) WHERE doc_id IS NOT NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 050b29e712..a2b1f93ec6 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -32,7 +32,7 @@ WHERE acknowledged.id = (
WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'
AND attempt_count.trigger_evidence_ref_id = $2
) >= $3::int
-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot, acknowledged.workflow_step, acknowledged.usage_squad_id
+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision, acknowledged.comment_thread_id, acknowledged.cancelled_by_type, acknowledged.cancelled_by_id, acknowledged.cancelled_by_name, acknowledged.issue_snapshot, acknowledged.workflow_step, acknowledged.usage_squad_id, acknowledged.doc_id, acknowledged.doc_thread_id, acknowledged.doc_comment_id
`
type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {
@@ -110,6 +110,9 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -311,7 +314,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = 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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Automatic cancellation without an explicit persisted failure reason. Unlike
@@ -381,6 +384,9 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -442,7 +448,7 @@ SET status = 'cancelled',
END
WHERE task.id = $1
AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
type CancelAgentTaskByUserParams struct {
@@ -526,6 +532,9 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, arg CancelAgentTask
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -541,7 +550,7 @@ SET status = 'cancelled',
cancelled_by_id = NULL,
cancelled_by_name = NULL
WHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CancelAgentTaskWithReasonParams struct {
@@ -622,6 +631,9 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -631,7 +643,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = 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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -710,6 +722,9 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -726,7 +741,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = 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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Cancels active tasks belonging to a chat session. Called from
@@ -805,6 +820,9 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -821,7 +839,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = 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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -900,6 +918,9 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -918,7 +939,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
context = COALESCE(context, '{}'::jsonb) || jsonb_build_object('comment_change_cancelled_task_id', id::text)
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -996,6 +1017,9 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1013,7 +1037,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CancelPendingTasksByIssueAndAgentParams struct {
@@ -1108,6 +1132,9 @@ func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg Can
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1126,7 +1153,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
AND comment_thread_id IS NOT DISTINCT FROM comment_thread_root_id($3::uuid)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CancelPendingTasksByIssueAndAgentInThreadParams struct {
@@ -1208,6 +1235,9 @@ func (q *Queries) CancelPendingTasksByIssueAndAgentInThread(ctx context.Context,
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1228,7 +1258,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE id = $4
AND chat_session_id = $5
AND status = 'queued'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CancelQueuedAgentTaskParams struct {
@@ -1312,6 +1342,9 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1340,7 +1373,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
WHERE queued.chat_session_id = $1
AND queued.status = 'queued'
AND queued.id IS DISTINCT FROM (SELECT id FROM head)
-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot, queued.workflow_step, queued.usage_squad_id
+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision, queued.comment_thread_id, queued.cancelled_by_type, queued.cancelled_by_id, queued.cancelled_by_name, queued.issue_snapshot, queued.workflow_step, queued.usage_squad_id, queued.doc_id, queued.doc_thread_id, queued.doc_comment_id
`
// Clear only positional follow-ups. The first visible task is current even
@@ -1418,6 +1451,9 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1446,7 +1482,7 @@ WHERE r.runtime_id = ANY($1::uuid[])
AND successor.id <> r.id
AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Cancels deferred auto-retry rows that a newer active task has already
@@ -1542,6 +1578,9 @@ func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1590,13 +1629,16 @@ WHERE id = (
AND (
(atq.issue_id IS NOT NULL AND active.issue_id = atq.issue_id)
OR (atq.chat_session_id IS NOT NULL AND active.chat_session_id = atq.chat_session_id)
+ OR (atq.doc_id IS NOT NULL AND active.doc_id = atq.doc_id)
OR (
atq.issue_id IS NULL
AND atq.chat_session_id IS NULL
AND atq.autopilot_run_id IS NULL
+ AND atq.doc_id IS NULL
AND active.issue_id IS NULL
AND active.chat_session_id IS NULL
AND active.autopilot_run_id IS NULL
+ AND active.doc_id IS NULL
)
)
)
@@ -1604,7 +1646,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type ClaimAgentTaskParams struct {
@@ -1620,6 +1662,7 @@ type ClaimAgentTaskParams struct {
// already dispatched or running. This allows different agents to work on the same
// issue in parallel while preventing a single agent from running duplicate tasks.
// Chat tasks (issue_id IS NULL) use chat_session_id for serialization instead.
+// Doc discussion tasks serialize per (doc, agent), the scope of their session.
// Quick-create tasks have no issue / chat / autopilot link, so they serialize on
// "any other quick-create-shaped task" (all four FKs NULL) for the same agent —
// otherwise a user mashing the create button could fire concurrent quick-creates
@@ -1694,6 +1737,9 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1702,7 +1748,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1772,6 +1818,9 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1970,7 +2019,7 @@ SET status = 'completed', completed_at = now(), result = $2,
retired_session_id = COALESCE($8, retired_session_id),
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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CompleteAgentTaskParams struct {
@@ -2069,6 +2118,9 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -2333,7 +2385,7 @@ SELECT
$3,
COALESCE($27::uuid, gen_random_uuid())
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateAgentTaskParams struct {
@@ -2485,6 +2537,9 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -2533,7 +2588,7 @@ SELECT
(SELECT i.status FROM issue i WHERE i.id = $2),
COALESCE($24::uuid, gen_random_uuid())
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateDeferredChannelIssueTaskParams struct {
@@ -2662,6 +2717,9 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -2688,7 +2746,7 @@ WHERE p.id = $5
AND p.chat_session_id IS NULL
AND p.autopilot_run_id IS NULL
AND lock_task_owner_rows(p.agent_id, p.issue_id, COALESCE(a.runtime_id, p.runtime_id))
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateManualQuickCreateRetryTaskParams struct {
@@ -2780,6 +2838,9 @@ func (q *Queries) CreateManualQuickCreateRetryTask(ctx context.Context, arg Crea
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -2810,7 +2871,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateQuickCreateTaskParams struct {
@@ -2918,6 +2979,9 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -2925,6 +2989,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
const createRetryTask = `-- name: CreateRetryTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
+ doc_id, doc_thread_id, doc_comment_id,
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,
@@ -2936,6 +3001,7 @@ INSERT INTO agent_task_queue (
)
SELECT
p.agent_id, COALESCE(a.runtime_id, p.runtime_id), p.issue_id, p.chat_session_id, p.autopilot_run_id,
+ p.doc_id, p.doc_thread_id, p.doc_comment_id,
CASE WHEN $2::timestamptz IS NOT NULL THEN 'deferred' ELSE 'queued' END,
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
@@ -2970,7 +3036,7 @@ WHERE p.id = $1
ON CONFLICT (issue_id, agent_id, (COALESCE(comment_thread_id, '00000000-0000-0000-0000-000000000000'::uuid))) WHERE status IN ('queued', 'dispatched')
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
DO NOTHING
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateRetryTaskParams struct {
@@ -3079,6 +3145,9 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -3259,7 +3328,7 @@ WHERE t.id = v.id
WHERE retry_parent.id = t.parent_task_id
AND retry_parent.failure_reason = 'runtime_offline'
)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id, t.doc_id, t.doc_thread_id, t.doc_comment_id
`
type ExpireStaleQueuedTasksParams struct {
@@ -3346,6 +3415,9 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -3364,7 +3436,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -3442,6 +3514,9 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -3460,7 +3535,7 @@ SET status = 'failed',
retired_session_id = COALESCE($9, retired_session_id),
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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type FailAgentTaskParams struct {
@@ -3565,6 +3640,9 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -3611,7 +3689,7 @@ WHERE retry.id = victims.id
AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=
now() - make_interval(secs => $2::double precision)
)
-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot, retry.workflow_step, retry.usage_squad_id
+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision, retry.comment_thread_id, retry.cancelled_by_type, retry.cancelled_by_id, retry.cancelled_by_name, retry.issue_snapshot, retry.workflow_step, retry.usage_squad_id, retry.doc_id, retry.doc_thread_id, retry.doc_comment_id
`
type FailExpiredRuntimeReconnectRetriesParams struct {
@@ -3698,6 +3776,9 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -3752,7 +3833,7 @@ WHERE (
)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type FailStaleTasksParams struct {
@@ -3870,6 +3951,9 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -4111,7 +4195,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE id = $1
`
@@ -4180,12 +4264,15 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE id = $1
FOR UPDATE
`
@@ -4258,12 +4345,15 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -4345,6 +4435,9 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -5220,7 +5313,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -5301,6 +5394,9 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -5415,7 +5511,7 @@ func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActi
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE agent_id = $1
-- Apply visibility before LIMIT so hidden fallbacks cannot end a page early.
-- Keep this predicate in sync with handler.visibleTaskHistory.
@@ -5509,6 +5605,9 @@ func (q *Queries) ListAgentTasks(ctx context.Context, arg ListAgentTasksParams)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -5699,7 +5798,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_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
@@ -5785,6 +5884,9 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -6082,7 +6184,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -6158,6 +6260,9 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -6170,7 +6275,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_id FROM agent_task_queue atq
WHERE atq.runtime_id = $1
AND atq.status = 'queued'
AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))
@@ -6268,6 +6373,9 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -6280,7 +6388,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_id FROM agent_task_queue atq
WHERE atq.runtime_id = ANY($1::uuid[])
AND atq.status = 'queued'
AND (atq.context->>'wakeup_id' IS NULL OR EXISTS (SELECT 1 FROM issue_wakeup w WHERE w.id=(atq.context->>'wakeup_id')::uuid AND w.disabled_at IS NULL AND w.revision=(atq.context->>'wakeup_revision')::bigint))
@@ -6380,6 +6488,9 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -6392,7 +6503,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -6468,6 +6579,9 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -6488,7 +6602,7 @@ WITH RECURSIVE subtree(id) AS (
JOIN subtree parent ON child.parent_issue_id = parent.id
WHERE child.workspace_id = $3
)
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, i.title AS issue_title, i.number AS issue_number, w.issue_prefix
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_id, i.title AS issue_title, i.number AS issue_number, w.issue_prefix
FROM agent_task_queue atq
JOIN subtree ON subtree.id = atq.issue_id
JOIN issue i ON i.id = atq.issue_id
@@ -6584,6 +6698,9 @@ func (q *Queries) ListTasksByIssueSubtree(ctx context.Context, arg ListTasksByIs
&i.AgentTaskQueue.IssueSnapshot,
&i.AgentTaskQueue.WorkflowStep,
&i.AgentTaskQueue.UsageSquadID,
+ &i.AgentTaskQueue.DocID,
+ &i.AgentTaskQueue.DocThreadID,
+ &i.AgentTaskQueue.DocCommentID,
&i.IssueTitle,
&i.IssueNumber,
&i.IssuePrefix,
@@ -6694,7 +6811,7 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_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')
@@ -6702,9 +6819,9 @@ WHERE a.workspace_id = $1
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot, latest.workflow_step, latest.usage_squad_id FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision, latest.comment_thread_id, latest.cancelled_by_type, latest.cancelled_by_id, latest.cancelled_by_name, latest.issue_snapshot, latest.workflow_step, latest.usage_squad_id, latest.doc_id, latest.doc_thread_id, latest.doc_comment_id FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision, atq.comment_thread_id, atq.cancelled_by_type, atq.cancelled_by_id, atq.cancelled_by_name, atq.issue_snapshot, atq.workflow_step, atq.usage_squad_id, atq.doc_id, atq.doc_thread_id, atq.doc_comment_id
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -6810,6 +6927,9 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -7064,7 +7184,7 @@ func (q *Queries) LockAgentForTaskEnqueue(ctx context.Context, id pgtype.UUID) (
}
const lockAgentTaskStartClaim = `-- name: LockAgentTaskStartClaim :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE id = $1 AND runtime_id = $2 AND dispatched_at = $3
AND status IN ('dispatched', 'waiting_local_directory', 'running')
FOR UPDATE
@@ -7143,6 +7263,9 @@ func (q *Queries) LockAgentTaskStartClaim(ctx context.Context, arg LockAgentTask
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7153,7 +7276,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -7237,6 +7360,9 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7245,7 +7371,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -7315,6 +7441,9 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7376,7 +7505,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE OF t
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type MergeCommentIntoPendingTaskParams struct {
@@ -7520,6 +7649,9 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeComm
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7547,7 +7679,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type MergeDelegatedFailureCommentIntoPendingTaskParams struct {
@@ -7633,6 +7765,9 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7689,7 +7824,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTas
UPDATE agent_task_queue
SET status = 'queued', fire_at = NULL
WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Early promotion is idempotent at the service layer: a task already promoted
@@ -7759,6 +7894,9 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -7797,7 +7935,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type PromoteDueDeferredTasksForRuntimeParams struct {
@@ -7891,6 +8029,9 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -7936,7 +8077,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type PromoteDueDeferredTasksForRuntimesParams struct {
@@ -8018,6 +8159,9 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -8187,7 +8331,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -8272,6 +8416,9 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -8316,7 +8463,7 @@ UPDATE agent_task_queue
SET dispatched_at = now(),
prepare_lease_expires_at = now() + make_interval(secs => $1::double precision)
WHERE id IN (SELECT id FROM candidates)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -8413,6 +8560,9 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -8433,7 +8583,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -8513,6 +8663,9 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -8676,7 +8829,7 @@ WHERE task.id = $1
AND task.started_at IS NULL
AND task.dispatched_at = $3
AND lock_task_owner_rows(task.agent_id, task.issue_id, COALESCE(enqueue_agent.runtime_id, task.runtime_id))
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -8757,6 +8910,9 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index cd566aade3..33c06b9eae 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -315,7 +315,7 @@ SELECT
$10,
COALESCE($11::uuid, gen_random_uuid())
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateAutopilotTaskParams struct {
@@ -430,6 +430,9 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1001,7 +1004,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_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, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -1074,6 +1077,9 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 2055595c82..66e40d4e56 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -406,7 +406,7 @@ SELECT
COALESCE($15::uuid, gen_random_uuid()),
$16::jsonb
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateChatTaskParams struct {
@@ -519,6 +519,9 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -600,7 +603,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -674,6 +677,9 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -3068,7 +3074,7 @@ WHERE task.chat_session_id = $1
AND message.role = 'user'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -3148,6 +3154,9 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -3580,7 +3589,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, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -3655,6 +3664,9 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat_supplement.sql.go b/server/pkg/db/generated/chat_supplement.sql.go
index 5bf3f10072..5778d614fa 100644
--- a/server/pkg/db/generated/chat_supplement.sql.go
+++ b/server/pkg/db/generated/chat_supplement.sql.go
@@ -170,7 +170,7 @@ func (q *Queries) ListChatGuidanceInProviderSession(ctx context.Context, arg Lis
}
const lockRunningChatTaskForSupplement = `-- name: LockRunningChatTaskForSupplement :one
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id FROM agent_task_queue t
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id, t.doc_id, t.doc_thread_id, t.doc_comment_id FROM agent_task_queue t
JOIN task_supplement_capability cap ON cap.task_id = t.id
WHERE t.chat_session_id = $1 AND t.status = 'running'
AND t.regenerate_quick_actions_for IS NULL
@@ -246,6 +246,9 @@ func (q *Queries) LockRunningChatTaskForSupplement(ctx context.Context, chatSess
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/generated/doc.sql.go b/server/pkg/db/generated/doc.sql.go
index ae6c703393..adcebea851 100644
--- a/server/pkg/db/generated/doc.sql.go
+++ b/server/pkg/db/generated/doc.sql.go
@@ -81,12 +81,12 @@ func (q *Queries) CreateDoc(ctx context.Context, arg CreateDocParams) (Doc, erro
const createDocComment = `-- name: CreateDocComment :one
INSERT INTO doc_comment (
id, workspace_id, doc_id, parent_id, author_type, author_id, content,
- anchor_quote, anchor_prefix, anchor_suffix
+ anchor_quote, anchor_prefix, anchor_suffix, source_task_id
) VALUES (
$1, $2, $3, $4, $5, $6, $7,
- $8, $9, $10
+ $8, $9, $10, $11
)
-RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at
+RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id
`
type CreateDocCommentParams struct {
@@ -100,6 +100,7 @@ type CreateDocCommentParams struct {
AnchorQuote string `json:"anchor_quote"`
AnchorPrefix string `json:"anchor_prefix"`
AnchorSuffix string `json:"anchor_suffix"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
}
func (q *Queries) CreateDocComment(ctx context.Context, arg CreateDocCommentParams) (DocComment, error) {
@@ -114,6 +115,7 @@ func (q *Queries) CreateDocComment(ctx context.Context, arg CreateDocCommentPara
arg.AnchorQuote,
arg.AnchorPrefix,
arg.AnchorSuffix,
+ arg.SourceTaskID,
)
var i DocComment
err := row.Scan(
@@ -132,6 +134,7 @@ func (q *Queries) CreateDocComment(ctx context.Context, arg CreateDocCommentPara
&i.ResolvedByID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.SourceTaskID,
)
return i, err
}
@@ -293,7 +296,7 @@ func (q *Queries) GetDocByIDForUpdate(ctx context.Context, id pgtype.UUID) (Doc,
}
const getDocComment = `-- name: GetDocComment :one
-SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at FROM doc_comment
+SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id FROM doc_comment
WHERE id = $1 AND doc_id = $2 AND workspace_id = $3
`
@@ -322,6 +325,7 @@ func (q *Queries) GetDocComment(ctx context.Context, arg GetDocCommentParams) (D
&i.ResolvedByID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.SourceTaskID,
)
return i, err
}
@@ -550,7 +554,7 @@ func (q *Queries) InsertDocVersion(ctx context.Context, arg InsertDocVersionPara
}
const listDocComments = `-- name: ListDocComments :many
-SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at FROM doc_comment
+SELECT id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id FROM doc_comment
WHERE doc_id = $1 AND workspace_id = $2
ORDER BY created_at, id
`
@@ -585,6 +589,7 @@ func (q *Queries) ListDocComments(ctx context.Context, arg ListDocCommentsParams
&i.ResolvedByID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.SourceTaskID,
); err != nil {
return nil, err
}
@@ -667,11 +672,14 @@ func (q *Queries) ListDocThreadParticipants(ctx context.Context, arg ListDocThre
const listDocVersions = `-- name: ListDocVersions :many
SELECT
- doc_id, workspace_id, number, title, author_type, author_id, message, action,
- action_ref, task_id, issue_id, contributors, created_at, updated_at
-FROM doc_version
-WHERE doc_id = $1
-ORDER BY number DESC
+ v.doc_id, v.workspace_id, v.number, v.title, v.author_type, v.author_id, v.message, v.action,
+ v.action_ref, v.task_id, v.issue_id, v.contributors, v.created_at, v.updated_at,
+ c.id AS doc_thread_id, COALESCE(c.anchor_quote, '')::text AS doc_thread_quote
+FROM doc_version v
+LEFT JOIN agent_task_queue t ON t.id = v.task_id
+LEFT JOIN doc_comment c ON c.id = t.doc_thread_id AND c.doc_id = v.doc_id AND c.parent_id IS NULL
+WHERE v.doc_id = $1
+ORDER BY v.number DESC
LIMIT $2
`
@@ -681,22 +689,26 @@ type ListDocVersionsParams struct {
}
type ListDocVersionsRow struct {
- DocID pgtype.UUID `json:"doc_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Number int32 `json:"number"`
- Title string `json:"title"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Message string `json:"message"`
- Action string `json:"action"`
- ActionRef pgtype.Int4 `json:"action_ref"`
- TaskID pgtype.UUID `json:"task_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Contributors []byte `json:"contributors"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ DocID pgtype.UUID `json:"doc_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Number int32 `json:"number"`
+ Title string `json:"title"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Message string `json:"message"`
+ Action string `json:"action"`
+ ActionRef pgtype.Int4 `json:"action_ref"`
+ TaskID pgtype.UUID `json:"task_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Contributors []byte `json:"contributors"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+ DocThreadQuote string `json:"doc_thread_quote"`
}
+// An edit an agent made while answering a discussion names that discussion
+// (through the run that made it), so history can link back to it.
func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams) ([]ListDocVersionsRow, error) {
rows, err := q.db.Query(ctx, listDocVersions, arg.DocID, arg.Limit)
if err != nil {
@@ -721,6 +733,8 @@ func (q *Queries) ListDocVersions(ctx context.Context, arg ListDocVersionsParams
&i.Contributors,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.DocThreadID,
+ &i.DocThreadQuote,
); err != nil {
return nil, err
}
@@ -999,7 +1013,7 @@ UPDATE doc_comment SET
resolved_by_id = $3,
updated_at = now()
WHERE id = $4 AND doc_id = $5 AND workspace_id = $6 AND parent_id IS NULL
-RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at
+RETURNING id, workspace_id, doc_id, parent_id, author_type, author_id, content, anchor_quote, anchor_prefix, anchor_suffix, resolved_at, resolved_by_type, resolved_by_id, created_at, updated_at, source_task_id
`
type SetDocCommentResolutionParams struct {
@@ -1038,6 +1052,7 @@ func (q *Queries) SetDocCommentResolution(ctx context.Context, arg SetDocComment
&i.ResolvedByID,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.SourceTaskID,
)
return i, err
}
diff --git a/server/pkg/db/generated/doc_task.sql.go b/server/pkg/db/generated/doc_task.sql.go
new file mode 100644
index 0000000000..82cd5ad598
--- /dev/null
+++ b/server/pkg/db/generated/doc_task.sql.go
@@ -0,0 +1,698 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: doc_task.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const cancelAgentTasksByDoc = `-- name: CancelAgentTasksByDoc :many
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
+WHERE doc_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
+`
+
+// Doc deletion cleanup: cancels every active run on the doc and returns the
+// rows so the caller can settle, broadcast and reconcile agent status.
+func (q *Queries) CancelAgentTasksByDoc(ctx context.Context, docID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, cancelAgentTasksByDoc, docID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ &i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const createDocCommentTask = `-- name: CreateDocCommentTask :one
+
+WITH enqueue_agent AS MATERIALIZED (
+ SELECT a.id, a.runtime_id
+ FROM agent a
+ WHERE a.id = $2
+ AND lock_task_owner_rows(a.id, NULL, a.runtime_id)
+ FOR KEY SHARE OF a
+)
+INSERT INTO agent_task_queue (
+ id, agent_id, runtime_id, issue_id, status, priority, context, trigger_summary,
+ doc_id, doc_thread_id, doc_comment_id,
+ originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ originator_source, delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+)
+SELECT
+ $1, $2, enqueue_agent.runtime_id, NULL, 'queued',
+ $3, $4, $5,
+ $6, $7, $8,
+ $9, $10,
+ $11, $12,
+ $13, $14,
+ $15, $16
+FROM enqueue_agent
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
+`
+
+type CreateDocCommentTaskParams struct {
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ Priority int32 `json:"priority"`
+ Context []byte `json:"context"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ DocID pgtype.UUID `json:"doc_id"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+ DocCommentID pgtype.UUID `json:"doc_comment_id"`
+ 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"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+}
+
+// Agent runs started from doc discussions (MUL-9933). A run records the doc,
+// the discussion's first comment (doc_thread_id) and the comment that
+// triggered it (doc_comment_id); the doc-scoped task context JSON carries the
+// workspace so events still resolve after the doc is gone.
+// Fenced against workspace teardown like every other enqueue: the caller has
+// already locked the agent row; lock_task_owner_rows locks the workspace and
+// runtime rows inside this statement and returns false once they are gone.
+func (q *Queries) CreateDocCommentTask(ctx context.Context, arg CreateDocCommentTaskParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, createDocCommentTask,
+ arg.ID,
+ arg.AgentID,
+ arg.Priority,
+ arg.Context,
+ arg.TriggerSummary,
+ arg.DocID,
+ arg.DocThreadID,
+ arg.DocCommentID,
+ arg.OriginatorUserID,
+ arg.AccountableUserID,
+ arg.RuntimeMcpOverlay,
+ arg.RuntimeConnectedApps,
+ arg.OriginatorSource,
+ arg.DelegatedFromTaskID,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
+ )
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ &i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
+ )
+ return i, err
+}
+
+const getDocThreadContinuationAgent = `-- name: GetDocThreadContinuationAgent :one
+SELECT agent_id FROM (
+ SELECT t.agent_id, t.created_at
+ FROM agent_task_queue t
+ WHERE t.doc_id = $1 AND t.doc_thread_id = $2
+ UNION ALL
+ SELECT c.author_id AS agent_id, c.created_at
+ FROM doc_comment c
+ WHERE c.workspace_id = $3 AND c.doc_id = $1
+ AND (c.id = $2 OR c.parent_id = $2)
+ AND c.author_type = 'agent'
+) participation
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+type GetDocThreadContinuationAgentParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// The agent that most recently took part in a discussion: it ran for the
+// discussion or wrote in it. A member's reply without a mention goes to it.
+func (q *Queries) GetDocThreadContinuationAgent(ctx context.Context, arg GetDocThreadContinuationAgentParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, getDocThreadContinuationAgent, arg.DocID, arg.DocThreadID, arg.WorkspaceID)
+ var agent_id pgtype.UUID
+ err := row.Scan(&agent_id)
+ return agent_id, err
+}
+
+const getLastDocTaskSession = `-- name: GetLastDocTaskSession :one
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.agent_id = $1 AND r.doc_id = $2
+ AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.doc_id = $2
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
+), latest_per_session AS (
+ SELECT DISTINCT ON (t.session_id)
+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,
+ COALESCE(t.error, '') AS error,
+ t.started_at,
+ COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.doc_id = $2
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed', 'cancelled')
+ ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC
+)
+SELECT session_id, work_dir, runtime_id, status, started_at FROM latest_per_session
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
+ AND (
+ status IN ('completed', 'cancelled')
+ OR (
+ status = 'failed'
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized', 'opencode_clock_skew')
+ AND NOT (error ILIKE '%400%' AND error ILIKE '%invalid_request_error%')
+ AND NOT (error ILIKE '%image dimensions exceed max allowed size%' AND error ILIKE '%image.source.base64.data%')
+ AND NOT (error ILIKE '%could not resolve authentication method%')
+ AND NOT (error ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
+ AND error ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
+ AND NOT (error ILIKE '%invalid conversation history%')
+ )
+ )
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR terminal_at > (SELECT at FROM resume_overflow_at)
+ )
+ORDER BY terminal_at DESC
+LIMIT 1
+`
+
+type GetLastDocTaskSessionParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+}
+
+type GetLastDocTaskSessionRow struct {
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Status string `json:"status"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+}
+
+// Resume context for an agent on a doc: one session and workdir per (doc,
+// agent), the doc analogue of GetLastTaskSession. Keep the per-session
+// reduction, retired-session exclusion and failure guards aligned with it.
+func (q *Queries) GetLastDocTaskSession(ctx context.Context, arg GetLastDocTaskSessionParams) (GetLastDocTaskSessionRow, error) {
+ row := q.db.QueryRow(ctx, getLastDocTaskSession, arg.AgentID, arg.DocID)
+ var i GetLastDocTaskSessionRow
+ err := row.Scan(
+ &i.SessionID,
+ &i.WorkDir,
+ &i.RuntimeID,
+ &i.Status,
+ &i.StartedAt,
+ )
+ return i, err
+}
+
+const getQueuedDocThreadTaskForUpdate = `-- name: GetQueuedDocThreadTaskForUpdate :one
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue
+WHERE doc_id = $1 AND doc_thread_id = $2 AND agent_id = $3
+ AND status = 'queued'
+ORDER BY created_at DESC
+LIMIT 1
+FOR UPDATE
+`
+
+type GetQueuedDocThreadTaskForUpdateParams struct {
+ DocID pgtype.UUID `json:"doc_id"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// The agent's run for this discussion that has not been picked up yet. A new
+// comment folds into it instead of queuing a second run.
+func (q *Queries) GetQueuedDocThreadTaskForUpdate(ctx context.Context, arg GetQueuedDocThreadTaskForUpdateParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, getQueuedDocThreadTaskForUpdate, arg.DocID, arg.DocThreadID, arg.AgentID)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ &i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
+ )
+ return i, err
+}
+
+const hasDocTaskReply = `-- name: HasDocTaskReply :one
+SELECT EXISTS (
+ SELECT 1 FROM doc_comment
+ WHERE workspace_id = $1 AND doc_id = $2 AND source_task_id = $3
+ AND (id = $4 OR parent_id = $4)
+)::bool
+`
+
+type HasDocTaskReplyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+}
+
+// Whether a run already replied in its own discussion; a comment it left in
+// another discussion on the doc does not answer this one.
+func (q *Queries) HasDocTaskReply(ctx context.Context, arg HasDocTaskReplyParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasDocTaskReply,
+ arg.WorkspaceID,
+ arg.DocID,
+ arg.TaskID,
+ arg.DocThreadID,
+ )
+ var column_1 bool
+ err := row.Scan(&column_1)
+ return column_1, err
+}
+
+const listDocTasks = `-- name: ListDocTasks :many
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue t
+WHERE t.doc_id = $1
+ AND (
+ t.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ OR t.id IN (
+ SELECT f.id FROM agent_task_queue f
+ WHERE f.doc_id = $1
+ AND f.status NOT IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ ORDER BY f.created_at DESC
+ LIMIT 200
+ )
+ )
+ORDER BY t.created_at DESC
+`
+
+// Runs on a doc for the discussions' run status, newest first: every run not
+// yet finished, however old, plus the 200 most recent finished ones.
+func (q *Queries) ListDocTasks(ctx context.Context, docID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, listDocTasks, docID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ &i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const mergeDocCommentIntoQueuedTask = `-- name: MergeDocCommentIntoQueuedTask :one
+UPDATE agent_task_queue
+SET doc_comment_id = $1,
+ trigger_summary = $2,
+ originator_user_id = $3::uuid,
+ accountable_user_id = $4::uuid,
+ originator_source = $5,
+ delegated_from_task_id = $6::uuid,
+ trigger_evidence_kind = $7,
+ trigger_evidence_ref_id = $8::uuid,
+ runtime_mcp_overlay = $9,
+ runtime_connected_apps = $10
+WHERE id = $11 AND status = 'queued'
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
+`
+
+type MergeDocCommentIntoQueuedTaskParams struct {
+ DocCommentID pgtype.UUID `json:"doc_comment_id"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ 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"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// The newer comment becomes the run's trigger, and the run moves to that
+// comment's human with its whole attribution and connected apps, as
+// MergeCommentIntoPendingTask does for issues: a run answering B must not run
+// with A's apps or show A as accountable.
+func (q *Queries) MergeDocCommentIntoQueuedTask(ctx context.Context, arg MergeDocCommentIntoQueuedTaskParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, mergeDocCommentIntoQueuedTask,
+ arg.DocCommentID,
+ arg.TriggerSummary,
+ arg.OriginatorUserID,
+ arg.AccountableUserID,
+ arg.OriginatorSource,
+ arg.DelegatedFromTaskID,
+ arg.TriggerEvidenceKind,
+ arg.TriggerEvidenceRefID,
+ arg.RuntimeMcpOverlay,
+ arg.RuntimeConnectedApps,
+ arg.ID,
+ )
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ &i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index c36a995d1f..d14e5a7596 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -195,6 +195,9 @@ type AgentTaskQueue struct {
WorkflowStep pgtype.Text `json:"workflow_step"`
// Squad UUID for usage attribution and unified execution avatar grouping. Separate from squad_id (which carries leader/worker routing authority). NULL for standalone non-squad runs.
UsageSquadID pgtype.UUID `json:"usage_squad_id"`
+ DocID pgtype.UUID `json:"doc_id"`
+ DocThreadID pgtype.UUID `json:"doc_thread_id"`
+ DocCommentID pgtype.UUID `json:"doc_comment_id"`
}
type AgentToLabel struct {
@@ -928,6 +931,7 @@ type DocComment struct {
ResolvedByID pgtype.UUID `json:"resolved_by_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
}
type DocFolder struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index aafe18c7bf..8faff635fb 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -17,7 +17,7 @@ SET status = 'cancelled', completed_at = now(),
cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -118,6 +118,9 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -143,7 +146,7 @@ WHERE task.agent_id = agent.id
AND agent.owner_id IS DISTINCT FROM $3
AND NOT COALESCE(agent.owner_id = ANY($4::uuid[]), false)
AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
type CancelNonOwnerTasksByRuntimeParams struct {
@@ -234,6 +237,9 @@ func (q *Queries) CancelNonOwnerTasksByRuntime(ctx context.Context, arg CancelNo
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -355,7 +361,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',
FROM victims
WHERE task.id = victims.id
AND task.status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
type FailTasksForOfflineRuntimesParams struct {
@@ -442,6 +448,9 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -952,7 +961,7 @@ func (q *Queries) ListDaemonCustomNames(ctx context.Context, arg ListDaemonCusto
}
const listNonOwnerActiveTasksByRuntime = `-- name: ListNonOwnerActiveTasksByRuntime :many
-SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
FROM agent_task_queue AS task
JOIN agent ON agent.id = task.agent_id
WHERE task.runtime_id = $1
@@ -1041,6 +1050,9 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntime(ctx context.Context, arg List
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -1053,7 +1065,7 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntime(ctx context.Context, arg List
}
const listNonOwnerActiveTasksByRuntimeForUpdate = `-- name: ListNonOwnerActiveTasksByRuntimeForUpdate :many
-SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
FROM agent_task_queue AS task
JOIN agent ON agent.id = task.agent_id
WHERE task.runtime_id = $1
@@ -1143,6 +1155,9 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntimeForUpdate(ctx context.Context,
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.go
index 9bc1ed89d5..f370024301 100644
--- a/server/pkg/db/generated/supplement.sql.go
+++ b/server/pkg/db/generated/supplement.sql.go
@@ -880,7 +880,7 @@ WHERE t.id = candidate.id
-- Reference the data-modifying CTE explicitly: capability persistence and
-- the returned running row are one indivisible statement.
AND (SELECT count(*) FROM capability) >= 0
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision, t.comment_thread_id, t.cancelled_by_type, t.cancelled_by_id, t.cancelled_by_name, t.issue_snapshot, t.workflow_step, t.usage_squad_id, t.doc_id, t.doc_thread_id, t.doc_comment_id
`
type StartAgentTaskWithSupplementParams struct {
@@ -957,6 +957,9 @@ func (q *Queries) StartAgentTaskWithSupplement(ctx context.Context, arg StartAge
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/generated/task_cleanup.sql.go b/server/pkg/db/generated/task_cleanup.sql.go
index f5ce156e28..7e22f39f8e 100644
--- a/server/pkg/db/generated/task_cleanup.sql.go
+++ b/server/pkg/db/generated/task_cleanup.sql.go
@@ -31,7 +31,7 @@ SET status = 'failed',
completed_at = now(),
chat_finalize_deferred_at = NULL
WHERE id = $2 AND status = 'cancelled'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type FailCancelledTaskProcessCleanupParams struct {
@@ -107,6 +107,9 @@ func (q *Queries) FailCancelledTaskProcessCleanup(ctx context.Context, arg FailC
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -122,7 +125,7 @@ WHERE task.id = ANY($1::uuid[])
AND (task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'
OR EXISTS (SELECT 1 FROM agent_runtime runtime
WHERE runtime.id = task.runtime_id AND runtime.provider = 'museapp'))
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step, task.usage_squad_id, task.doc_id, task.doc_thread_id, task.doc_comment_id
`
// Run inside the bulk terminal-write transaction, before its rows reach the
@@ -200,6 +203,9 @@ func (q *Queries) MarkMuseAppRecoveryCleanupUnconfirmed(ctx context.Context, tas
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/wakeup.sql.go b/server/pkg/db/generated/wakeup.sql.go
index 69cbfa401a..a358317139 100644
--- a/server/pkg/db/generated/wakeup.sql.go
+++ b/server/pkg/db/generated/wakeup.sql.go
@@ -37,7 +37,7 @@ func (q *Queries) AdvanceIssueWakeup(ctx context.Context, arg AdvanceIssueWakeup
const cancelUnstartedIssueWakeupTasks = `-- name: CancelUnstartedIssueWakeupTasks :many
UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Issue closed; wakeup disabled'
-WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+WHERE issue_id= $1 AND context->>'wakeup_id' IS NOT NULL AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -111,6 +111,9 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID p
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -124,7 +127,7 @@ func (q *Queries) CancelUnstartedIssueWakeupTasks(ctx context.Context, issueID p
const cancelUnstartedWakeupTasks = `-- name: CancelUnstartedWakeupTasks :many
UPDATE agent_task_queue SET status='cancelled',completed_at=now(),error='Wakeup disabled or updated'
-WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','deferred') AND started_at IS NULL RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID string) ([]AgentTaskQueue, error) {
@@ -198,6 +201,9 @@ func (q *Queries) CancelUnstartedWakeupTasks(ctx context.Context, wakeupID strin
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
); err != nil {
return nil, err
}
@@ -420,7 +426,7 @@ SELECT
),
COALESCE($24::uuid, gen_random_uuid())
FROM enqueue_agent
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type CreateWakeupTaskParams struct {
@@ -560,6 +566,9 @@ func (q *Queries) CreateWakeupTask(ctx context.Context, arg CreateWakeupTaskPara
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -629,7 +638,7 @@ func (q *Queries) DiscardWakeupReceipts(ctx context.Context, id pgtype.UUID) err
}
const findPendingWakeupTask = `-- name: FindPendingWakeupTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue WHERE context->>'wakeup_id'= $1::text AND status IN ('queued','dispatched') ORDER BY created_at LIMIT 1 FOR UPDATE
`
func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (AgentTaskQueue, error) {
@@ -697,6 +706,9 @@ func (q *Queries) FindPendingWakeupTask(ctx context.Context, wakeupID string) (A
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1569,7 +1581,7 @@ func (q *Queries) LockWakeupIssue(ctx context.Context, id pgtype.UUID) (Issue, e
}
const lockWakeupSourceTask = `-- name: LockWakeupSourceTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id FROM agent_task_queue WHERE id= $1 AND issue_id= $2 FOR UPDATE NOWAIT
`
type LockWakeupSourceTaskParams struct {
@@ -1642,6 +1654,9 @@ func (q *Queries) LockWakeupSourceTask(ctx context.Context, arg LockWakeupSource
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1791,7 +1806,7 @@ func (q *Queries) ReleaseWakeupReceipts(ctx context.Context, ids []pgtype.UUID)
}
const replaceWakeupEvidence = `-- name: ReplaceWakeupEvidence :one
-UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+UPDATE agent_task_queue SET handoff_note=$1, context=COALESCE(context,'{}'::jsonb) || jsonb_build_object('wakeup_evidence', $2::jsonb) WHERE id= $3 AND status='queued' RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type ReplaceWakeupEvidenceParams struct {
@@ -1865,6 +1880,9 @@ func (q *Queries) ReplaceWakeupEvidence(ctx context.Context, arg ReplaceWakeupEv
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
@@ -1887,7 +1905,7 @@ func (q *Queries) ReserveWakeupReceipts(ctx context.Context, arg ReserveWakeupRe
const setClaimedTaskContext = `-- name: SetClaimedTaskContext :one
UPDATE agent_task_queue SET context= $1::jsonb
-WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id
+WHERE id= $2 AND status='dispatched' AND dispatched_at= $3 RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step, usage_squad_id, doc_id, doc_thread_id, doc_comment_id
`
type SetClaimedTaskContextParams struct {
@@ -1962,6 +1980,9 @@ func (q *Queries) SetClaimedTaskContext(ctx context.Context, arg SetClaimedTaskC
&i.IssueSnapshot,
&i.WorkflowStep,
&i.UsageSquadID,
+ &i.DocID,
+ &i.DocThreadID,
+ &i.DocCommentID,
)
return i, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index f9a99aea78..c126475210 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -560,6 +560,7 @@ WHERE id = $1 AND issue_id IS NULL
-- ceiling; it does not re-enable tasks whose retry budget was disabled.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
+ doc_id, doc_thread_id, doc_comment_id,
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,
@@ -571,6 +572,7 @@ INSERT INTO agent_task_queue (
)
SELECT
p.agent_id, COALESCE(a.runtime_id, p.runtime_id), p.issue_id, p.chat_session_id, p.autopilot_run_id,
+ p.doc_id, p.doc_thread_id, p.doc_comment_id,
CASE WHEN sqlc.narg(fire_at)::timestamptz IS NOT NULL THEN 'deferred' ELSE 'queued' END,
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
@@ -824,6 +826,7 @@ WHERE atq.id = $1 AND a.workspace_id = $2;
-- already dispatched or running. This allows different agents to work on the same
-- issue in parallel while preventing a single agent from running duplicate tasks.
-- Chat tasks (issue_id IS NULL) use chat_session_id for serialization instead.
+-- Doc discussion tasks serialize per (doc, agent), the scope of their session.
-- Quick-create tasks have no issue / chat / autopilot link, so they serialize on
-- "any other quick-create-shaped task" (all four FKs NULL) for the same agent —
-- otherwise a user mashing the create button could fire concurrent quick-creates
@@ -864,13 +867,16 @@ WHERE id = (
AND (
(atq.issue_id IS NOT NULL AND active.issue_id = atq.issue_id)
OR (atq.chat_session_id IS NOT NULL AND active.chat_session_id = atq.chat_session_id)
+ OR (atq.doc_id IS NOT NULL AND active.doc_id = atq.doc_id)
OR (
atq.issue_id IS NULL
AND atq.chat_session_id IS NULL
AND atq.autopilot_run_id IS NULL
+ AND atq.doc_id IS NULL
AND active.issue_id IS NULL
AND active.chat_session_id IS NULL
AND active.autopilot_run_id IS NULL
+ AND active.doc_id IS NULL
)
)
)
diff --git a/server/pkg/db/queries/doc.sql b/server/pkg/db/queries/doc.sql
index 10096a24af..18e0bdf478 100644
--- a/server/pkg/db/queries/doc.sql
+++ b/server/pkg/db/queries/doc.sql
@@ -93,12 +93,17 @@ SELECT * FROM doc_version
WHERE doc_id = $1 AND number = $2;
-- name: ListDocVersions :many
+-- An edit an agent made while answering a discussion names that discussion
+-- (through the run that made it), so history can link back to it.
SELECT
- doc_id, workspace_id, number, title, author_type, author_id, message, action,
- action_ref, task_id, issue_id, contributors, created_at, updated_at
-FROM doc_version
-WHERE doc_id = $1
-ORDER BY number DESC
+ v.doc_id, v.workspace_id, v.number, v.title, v.author_type, v.author_id, v.message, v.action,
+ v.action_ref, v.task_id, v.issue_id, v.contributors, v.created_at, v.updated_at,
+ c.id AS doc_thread_id, COALESCE(c.anchor_quote, '')::text AS doc_thread_quote
+FROM doc_version v
+LEFT JOIN agent_task_queue t ON t.id = v.task_id
+LEFT JOIN doc_comment c ON c.id = t.doc_thread_id AND c.doc_id = v.doc_id AND c.parent_id IS NULL
+WHERE v.doc_id = $1
+ORDER BY v.number DESC
LIMIT $2;
-- name: MergeDocEditIntoVersion :execrows
@@ -149,10 +154,10 @@ WHERE id = @id AND doc_id = @doc_id AND workspace_id = @workspace_id;
-- name: CreateDocComment :one
INSERT INTO doc_comment (
id, workspace_id, doc_id, parent_id, author_type, author_id, content,
- anchor_quote, anchor_prefix, anchor_suffix
+ anchor_quote, anchor_prefix, anchor_suffix, source_task_id
) VALUES (
@id, @workspace_id, @doc_id, sqlc.narg('parent_id'), @author_type, @author_id, @content,
- @anchor_quote, @anchor_prefix, @anchor_suffix
+ @anchor_quote, @anchor_prefix, @anchor_suffix, sqlc.narg('source_task_id')
)
RETURNING *;
diff --git a/server/pkg/db/queries/doc_task.sql b/server/pkg/db/queries/doc_task.sql
new file mode 100644
index 0000000000..afda870c21
--- /dev/null
+++ b/server/pkg/db/queries/doc_task.sql
@@ -0,0 +1,165 @@
+-- Agent runs started from doc discussions (MUL-9933). A run records the doc,
+-- the discussion's first comment (doc_thread_id) and the comment that
+-- triggered it (doc_comment_id); the doc-scoped task context JSON carries the
+-- workspace so events still resolve after the doc is gone.
+
+-- name: CreateDocCommentTask :one
+-- Fenced against workspace teardown like every other enqueue: the caller has
+-- already locked the agent row; lock_task_owner_rows locks the workspace and
+-- runtime rows inside this statement and returns false once they are gone.
+WITH enqueue_agent AS MATERIALIZED (
+ SELECT a.id, a.runtime_id
+ FROM agent a
+ WHERE a.id = sqlc.arg(agent_id)
+ AND lock_task_owner_rows(a.id, NULL, a.runtime_id)
+ FOR KEY SHARE OF a
+)
+INSERT INTO agent_task_queue (
+ id, agent_id, runtime_id, issue_id, status, priority, context, trigger_summary,
+ doc_id, doc_thread_id, doc_comment_id,
+ originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ originator_source, delegated_from_task_id, trigger_evidence_kind, trigger_evidence_ref_id
+)
+SELECT
+ sqlc.arg(id), sqlc.arg(agent_id), enqueue_agent.runtime_id, NULL, 'queued',
+ sqlc.arg(priority), sqlc.arg(context), sqlc.narg(trigger_summary),
+ sqlc.arg(doc_id), sqlc.arg(doc_thread_id), sqlc.arg(doc_comment_id),
+ sqlc.narg(originator_user_id), sqlc.narg(accountable_user_id),
+ sqlc.narg(runtime_mcp_overlay), sqlc.narg(runtime_connected_apps),
+ sqlc.narg(originator_source), sqlc.narg(delegated_from_task_id),
+ sqlc.narg(trigger_evidence_kind), sqlc.narg(trigger_evidence_ref_id)
+FROM enqueue_agent
+RETURNING *;
+
+-- name: GetQueuedDocThreadTaskForUpdate :one
+-- The agent's run for this discussion that has not been picked up yet. A new
+-- comment folds into it instead of queuing a second run.
+SELECT * FROM agent_task_queue
+WHERE doc_id = @doc_id AND doc_thread_id = @doc_thread_id AND agent_id = @agent_id
+ AND status = 'queued'
+ORDER BY created_at DESC
+LIMIT 1
+FOR UPDATE;
+
+-- name: MergeDocCommentIntoQueuedTask :one
+-- The newer comment becomes the run's trigger, and the run moves to that
+-- comment's human with its whole attribution and connected apps, as
+-- MergeCommentIntoPendingTask does for issues: a run answering B must not run
+-- with A's apps or show A as accountable.
+UPDATE agent_task_queue
+SET doc_comment_id = @doc_comment_id,
+ trigger_summary = sqlc.narg(trigger_summary),
+ originator_user_id = sqlc.narg(originator_user_id)::uuid,
+ accountable_user_id = sqlc.narg(accountable_user_id)::uuid,
+ originator_source = sqlc.narg(originator_source),
+ delegated_from_task_id = sqlc.narg(delegated_from_task_id)::uuid,
+ trigger_evidence_kind = sqlc.narg(trigger_evidence_kind),
+ trigger_evidence_ref_id = sqlc.narg(trigger_evidence_ref_id)::uuid,
+ runtime_mcp_overlay = sqlc.narg(runtime_mcp_overlay),
+ runtime_connected_apps = sqlc.narg(runtime_connected_apps)
+WHERE id = @id AND status = 'queued'
+RETURNING *;
+
+-- name: GetDocThreadContinuationAgent :one
+-- The agent that most recently took part in a discussion: it ran for the
+-- discussion or wrote in it. A member's reply without a mention goes to it.
+SELECT agent_id FROM (
+ SELECT t.agent_id, t.created_at
+ FROM agent_task_queue t
+ WHERE t.doc_id = @doc_id AND t.doc_thread_id = @doc_thread_id
+ UNION ALL
+ SELECT c.author_id AS agent_id, c.created_at
+ FROM doc_comment c
+ WHERE c.workspace_id = @workspace_id AND c.doc_id = @doc_id
+ AND (c.id = @doc_thread_id OR c.parent_id = @doc_thread_id)
+ AND c.author_type = 'agent'
+) participation
+ORDER BY created_at DESC
+LIMIT 1;
+
+-- name: ListDocTasks :many
+-- Runs on a doc for the discussions' run status, newest first: every run not
+-- yet finished, however old, plus the 200 most recent finished ones.
+SELECT * FROM agent_task_queue t
+WHERE t.doc_id = $1
+ AND (
+ t.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ OR t.id IN (
+ SELECT f.id FROM agent_task_queue f
+ WHERE f.doc_id = $1
+ AND f.status NOT IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ ORDER BY f.created_at DESC
+ LIMIT 200
+ )
+ )
+ORDER BY t.created_at DESC;
+
+-- name: CancelAgentTasksByDoc :many
+-- Doc deletion cleanup: cancels every active run on the doc and returns the
+-- rows so the caller can settle, broadcast and reconcile agent status.
+UPDATE agent_task_queue
+SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL,
+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL
+WHERE doc_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+RETURNING *;
+
+-- name: GetLastDocTaskSession :one
+-- Resume context for an agent on a doc: one session and workdir per (doc,
+-- agent), the doc analogue of GetLastTaskSession. Keep the per-session
+-- reduction, retired-session exclusion and failure guards aligned with it.
+WITH retired_sessions AS (
+ SELECT DISTINCT r.retired_session_id AS session_id
+ FROM agent_task_queue r
+ WHERE r.agent_id = $1 AND r.doc_id = $2
+ AND r.retired_session_id IS NOT NULL
+), resume_overflow_at AS (
+ SELECT MAX(COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at)) AS at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.doc_id = $2
+ AND t.status = 'failed'
+ AND (
+ COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
+ OR (COALESCE(t.error, '') ILIKE '%thread/resume failed%' AND COALESCE(t.error, '') ILIKE '%token too long%')
+ )
+), latest_per_session AS (
+ SELECT DISTINCT ON (t.session_id)
+ t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason,
+ COALESCE(t.error, '') AS error,
+ t.started_at,
+ COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) AS terminal_at
+ FROM agent_task_queue t
+ WHERE t.agent_id = $1 AND t.doc_id = $2
+ AND t.session_id IS NOT NULL
+ AND t.status IN ('completed', 'failed', 'cancelled')
+ ORDER BY t.session_id, COALESCE(t.completed_at, t.started_at, t.dispatched_at, t.created_at) DESC
+)
+SELECT session_id, work_dir, runtime_id, status, started_at FROM latest_per_session
+WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
+ AND (
+ status IN ('completed', 'cancelled')
+ OR (
+ status = 'failed'
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow', 'codex_resume_oversized', 'opencode_clock_skew')
+ AND NOT (error ILIKE '%400%' AND error ILIKE '%invalid_request_error%')
+ AND NOT (error ILIKE '%image dimensions exceed max allowed size%' AND error ILIKE '%image.source.base64.data%')
+ AND NOT (error ILIKE '%could not resolve authentication method%')
+ AND NOT (error ~* 'must not be empty|must be non-?empty|must have non-?empty|non-?empty content|cannot be empty|should not be empty'
+ AND error ~* 'role[^a-z0-9]{0,2}assistant|assistant message|message at position|messages\.[0-9]|messages\[[0-9]')
+ AND NOT (error ILIKE '%invalid conversation history%')
+ )
+ )
+ AND (
+ (SELECT at FROM resume_overflow_at) IS NULL
+ OR terminal_at > (SELECT at FROM resume_overflow_at)
+ )
+ORDER BY terminal_at DESC
+LIMIT 1;
+
+-- name: HasDocTaskReply :one
+-- Whether a run already replied in its own discussion; a comment it left in
+-- another discussion on the doc does not answer this one.
+SELECT EXISTS (
+ SELECT 1 FROM doc_comment
+ WHERE workspace_id = @workspace_id AND doc_id = @doc_id AND source_task_id = @task_id
+ AND (id = @doc_thread_id OR parent_id = @doc_thread_id)
+)::bool;
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 99776da3fe..7085276e44 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -98,6 +98,11 @@ const (
// daemon puts on the agent's PATH has `issue comment add --steer`. The
// server tells a squad leader about steering only then.
DaemonCapabilityCLICommentSteerV1 = "cli-comment-steer-v1"
+ // DaemonCapabilityDocCommentV1 advertises that the daemon runs doc
+ // discussion tasks (MUL-9933): it renders their prompt and brief, and its
+ // CLI has `doc comment add`. An older daemon would treat such a task as an
+ // issue run with no issue, so the claim fails it before launch instead.
+ DaemonCapabilityDocCommentV1 = "doc-comment-v1"
TaskSupplementFailureTurnNotStarted = "turn_not_started"
TaskSupplementFailureProviderRejected = "provider_rejected"