Skip to content

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

Go
28.8 KB
Raw Blame
// 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, transcript_purged_at, transcript_purged_by
`

// 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,
			&i.TranscriptPurgedAt,
			&i.TranscriptPurgedBy,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const cancelAgentTasksByDocThread = `-- name: CancelAgentTasksByDocThread :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 doc_thread_id = $2
  AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, 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, transcript_purged_at, transcript_purged_by
`

type CancelAgentTasksByDocThreadParams struct {
	DocID       pgtype.UUID `json:"doc_id"`
	DocThreadID pgtype.UUID `json:"doc_thread_id"`
}

// Discussion deletion cleanup, the counterpart of CancelAgentTasksByDoc.
func (q *Queries) CancelAgentTasksByDocThread(ctx context.Context, arg CancelAgentTasksByDocThreadParams) ([]AgentTaskQueue, error) {
	rows, err := q.db.Query(ctx, cancelAgentTasksByDocThread, arg.DocID, arg.DocThreadID)
	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,
			&i.TranscriptPurgedAt,
			&i.TranscriptPurgedBy,
		); 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, transcript_purged_at, transcript_purged_by
`

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,
		&i.TranscriptPurgedAt,
		&i.TranscriptPurgedBy,
	)
	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, transcript_purged_at, transcript_purged_by 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,
		&i.TranscriptPurgedAt,
		&i.TranscriptPurgedBy,
	)
	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, transcript_purged_at, transcript_purged_by 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,
			&i.TranscriptPurgedAt,
			&i.TranscriptPurgedBy,
		); 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, transcript_purged_at, transcript_purged_by
`

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,
		&i.TranscriptPurgedAt,
		&i.TranscriptPurgedBy,
	)
	return i, err
}