// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: queries.sql

package sqlitegen

import (
	"context"
	"database/sql"
	"strings"
)

const acquireProjectDeleteWriteLock = `-- name: AcquireProjectDeleteWriteLock :execrows
UPDATE projects
SET updated_at_unix_ms = updated_at_unix_ms
WHERE id = ?1
`

func (q *Queries) AcquireProjectDeleteWriteLock(ctx context.Context, projectID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, acquireProjectDeleteWriteLock, projectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const acquireWorkspaceRegistrationLock = `-- name: AcquireWorkspaceRegistrationLock :execrows
UPDATE projects
SET updated_at_unix_ms = updated_at_unix_ms
WHERE id = ''
`

func (q *Queries) AcquireWorkspaceRegistrationLock(ctx context.Context) (int64, error) {
	result, err := q.db.ExecContext(ctx, acquireWorkspaceRegistrationLock)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const acquireWorkspaceUnlinkWriteLock = `-- name: AcquireWorkspaceUnlinkWriteLock :execrows
UPDATE workspaces
SET updated_at_unix_ms = updated_at_unix_ms
WHERE project_id = ?1
  AND id = ?2
`

type AcquireWorkspaceUnlinkWriteLockParams struct {
	ProjectID   string
	WorkspaceID string
}

func (q *Queries) AcquireWorkspaceUnlinkWriteLock(ctx context.Context, arg AcquireWorkspaceUnlinkWriteLockParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, acquireWorkspaceUnlinkWriteLock, arg.ProjectID, arg.WorkspaceID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const allocateProjectTaskSequence = `-- name: AllocateProjectTaskSequence :one
UPDATE projects
SET
    next_task_seq = next_task_seq + 1,
    updated_at_unix_ms = ?1
WHERE id = ?2
RETURNING project_key, next_task_seq
`

type AllocateProjectTaskSequenceParams struct {
	UpdatedAtUnixMs int64
	ProjectID       string
}

type AllocateProjectTaskSequenceRow struct {
	ProjectKey  string
	NextTaskSeq int64
}

func (q *Queries) AllocateProjectTaskSequence(ctx context.Context, arg AllocateProjectTaskSequenceParams) (AllocateProjectTaskSequenceRow, error) {
	row := q.db.QueryRowContext(ctx, allocateProjectTaskSequence, arg.UpdatedAtUnixMs, arg.ProjectID)
	var i AllocateProjectTaskSequenceRow
	err := row.Scan(&i.ProjectKey, &i.NextTaskSeq)
	return i, err
}

const applyPendingTransitionEdgeToJoin = `-- name: ApplyPendingTransitionEdgeToJoin :execrows
UPDATE task_transition_edges
SET state = 'applied'
WHERE id = ?1
  AND state = 'pending'
`

func (q *Queries) ApplyPendingTransitionEdgeToJoin(ctx context.Context, edgeID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, applyPendingTransitionEdgeToJoin, edgeID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const applyPendingTransitionEdgeToPlacement = `-- name: ApplyPendingTransitionEdgeToPlacement :execrows
UPDATE task_transition_edges
SET state = 'applied',
    target_placement_id = ?1
WHERE id = ?2
  AND state = 'pending'
`

type ApplyPendingTransitionEdgeToPlacementParams struct {
	TargetPlacementID sql.NullString
	EdgeID            string
}

func (q *Queries) ApplyPendingTransitionEdgeToPlacement(ctx context.Context, arg ApplyPendingTransitionEdgeToPlacementParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, applyPendingTransitionEdgeToPlacement, arg.TargetPlacementID, arg.EdgeID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const approvePendingTransition = `-- name: ApprovePendingTransition :execrows
UPDATE task_transitions
SET state = 'approved', applied_at_unix_ms = ?1
WHERE id = ?2
  AND state = 'pending_approval'
`

type ApprovePendingTransitionParams struct {
	AppliedAtUnixMs int64
	TransitionID    string
}

func (q *Queries) ApprovePendingTransition(ctx context.Context, arg ApprovePendingTransitionParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, approvePendingTransition, arg.AppliedAtUnixMs, arg.TransitionID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const attachRunSession = `-- name: AttachRunSession :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    session_id = ?2
WHERE id = ?3
  AND run_generation = ?4
  AND started_at_unix_ms > 0
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND (session_id IS NULL OR session_id = ?2)
`

type AttachRunSessionParams struct {
	UpdatedAtUnixMs int64
	SessionID       sql.NullString
	RunID           string
	RunGeneration   int64
}

func (q *Queries) AttachRunSession(ctx context.Context, arg AttachRunSessionParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, attachRunSession,
		arg.UpdatedAtUnixMs,
		arg.SessionID,
		arg.RunID,
		arg.RunGeneration,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const cancelTask = `-- name: CancelTask :execrows
UPDATE tasks
SET
    canceled_at_unix_ms = ?1,
    cancellation_reason = ?2,
    updated_at_unix_ms = ?3
WHERE id = ?4
`

type CancelTaskParams struct {
	CanceledAtUnixMs   int64
	CancellationReason string
	UpdatedAtUnixMs    int64
	ID                 string
}

func (q *Queries) CancelTask(ctx context.Context, arg CancelTaskParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, cancelTask,
		arg.CanceledAtUnixMs,
		arg.CancellationReason,
		arg.UpdatedAtUnixMs,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const claimWorkflowRun = `-- name: ClaimWorkflowRun :one
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    started_at_unix_ms = ?2,
    run_generation = run_generation + 1
WHERE task_runs.id = ?3
  AND run_generation = ?4
  AND automation_requested_at_unix_ms > 0
  AND started_at_unix_ms = 0
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND waiting_ask_id = ''
  AND EXISTS (
      SELECT 1
      FROM tasks t
      JOIN task_node_placements p ON p.id = task_runs.placement_id
      JOIN workflow_nodes n ON n.id = p.node_id
      WHERE t.id = p.task_id
        AND t.canceled_at_unix_ms = 0
        AND p.state = 'active'
        AND n.kind IN ('agent', 'script')
  )
RETURNING
    id,
    (
        SELECT p.task_id
        FROM task_node_placements p
        WHERE p.id = task_runs.placement_id
    ) AS task_id,
    placement_id,
    (
        SELECT p.node_id
        FROM task_node_placements p
        WHERE p.id = task_runs.placement_id
    ) AS node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
`

type ClaimWorkflowRunParams struct {
	UpdatedAtUnixMs    int64
	StartedAtUnixMs    int64
	ID                 string
	ExpectedGeneration int64
}

type ClaimWorkflowRunRow struct {
	ID                          string
	TaskID                      string
	PlacementID                 string
	NodeID                      sql.NullString
	SessionID                   sql.NullString
	RunGeneration               int64
	WorkflowRevisionSeen        int64
	AutomationRequestedAtUnixMs int64
	CreatedAtUnixMs             int64
	UpdatedAtUnixMs             int64
	StartedAtUnixMs             int64
	CompletedAtUnixMs           int64
	InterruptedAtUnixMs         int64
	InterruptionReason          string
	InterruptionDetailJson      string
	WaitingAskID                string
	EffectiveCompletionMode     string
	InvalidCompletionCount      int64
	RunStartSnapshotJson        string
	MetadataJson                string
}

func (q *Queries) ClaimWorkflowRun(ctx context.Context, arg ClaimWorkflowRunParams) (ClaimWorkflowRunRow, error) {
	row := q.db.QueryRowContext(ctx, claimWorkflowRun,
		arg.UpdatedAtUnixMs,
		arg.StartedAtUnixMs,
		arg.ID,
		arg.ExpectedGeneration,
	)
	var i ClaimWorkflowRunRow
	err := row.Scan(
		&i.ID,
		&i.TaskID,
		&i.PlacementID,
		&i.NodeID,
		&i.SessionID,
		&i.RunGeneration,
		&i.WorkflowRevisionSeen,
		&i.AutomationRequestedAtUnixMs,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
		&i.StartedAtUnixMs,
		&i.CompletedAtUnixMs,
		&i.InterruptedAtUnixMs,
		&i.InterruptionReason,
		&i.InterruptionDetailJson,
		&i.WaitingAskID,
		&i.EffectiveCompletionMode,
		&i.InvalidCompletionCount,
		&i.RunStartSnapshotJson,
		&i.MetadataJson,
	)
	return i, err
}

const clearDeletedWorkflowDefaultProjectLinks = `-- name: ClearDeletedWorkflowDefaultProjectLinks :execrows
UPDATE projects
SET
    default_project_workflow_link_id = '',
    updated_at_unix_ms = ?1
WHERE default_project_workflow_link_id IN (
    SELECT id
    FROM project_workflow_links
    WHERE workflow_id = ?2
)
`

type ClearDeletedWorkflowDefaultProjectLinksParams struct {
	UpdatedAtUnixMs int64
	WorkflowID      string
}

func (q *Queries) ClearDeletedWorkflowDefaultProjectLinks(ctx context.Context, arg ClearDeletedWorkflowDefaultProjectLinksParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, clearDeletedWorkflowDefaultProjectLinks, arg.UpdatedAtUnixMs, arg.WorkflowID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const clearProjectDefaultWorkflowLinks = `-- name: ClearProjectDefaultWorkflowLinks :exec
UPDATE projects
SET
    default_project_workflow_link_id = '',
    updated_at_unix_ms = ?1
WHERE id = ?2
`

type ClearProjectDefaultWorkflowLinksParams struct {
	UpdatedAtUnixMs int64
	ProjectID       string
}

func (q *Queries) ClearProjectDefaultWorkflowLinks(ctx context.Context, arg ClearProjectDefaultWorkflowLinksParams) error {
	_, err := q.db.ExecContext(ctx, clearProjectDefaultWorkflowLinks, arg.UpdatedAtUnixMs, arg.ProjectID)
	return err
}

const clearRunWaitingAsk = `-- name: ClearRunWaitingAsk :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    waiting_ask_id = ''
WHERE id = ?2
  AND run_generation = ?3
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND waiting_ask_id = ?4
`

type ClearRunWaitingAskParams struct {
	UpdatedAtUnixMs int64
	RunID           string
	RunGeneration   int64
	AskID           string
}

func (q *Queries) ClearRunWaitingAsk(ctx context.Context, arg ClearRunWaitingAskParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, clearRunWaitingAsk,
		arg.UpdatedAtUnixMs,
		arg.RunID,
		arg.RunGeneration,
		arg.AskID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const completeActiveManualMoveSourcePlacement = `-- name: CompleteActiveManualMoveSourcePlacement :execrows
UPDATE task_node_placements
SET state = 'completed',
    updated_at_unix_ms = ?1
WHERE task_node_placements.id = ?2
  AND state = 'active'
`

type CompleteActiveManualMoveSourcePlacementParams struct {
	UpdatedAtUnixMs int64
	PlacementID     string
}

func (q *Queries) CompleteActiveManualMoveSourcePlacement(ctx context.Context, arg CompleteActiveManualMoveSourcePlacementParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, completeActiveManualMoveSourcePlacement, arg.UpdatedAtUnixMs, arg.PlacementID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const completeRunUpdateRun = `-- name: CompleteRunUpdateRun :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    completed_at_unix_ms = ?2,
    waiting_ask_id = ''
WHERE id = ?3
  AND run_generation = ?4
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
`

type CompleteRunUpdateRunParams struct {
	UpdatedAtUnixMs   int64
	CompletedAtUnixMs int64
	RunID             string
	RunGeneration     int64
}

func (q *Queries) CompleteRunUpdateRun(ctx context.Context, arg CompleteRunUpdateRunParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, completeRunUpdateRun,
		arg.UpdatedAtUnixMs,
		arg.CompletedAtUnixMs,
		arg.RunID,
		arg.RunGeneration,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const countActiveProjectWorkflowLinks = `-- name: CountActiveProjectWorkflowLinks :one
SELECT CAST(COUNT(*) AS INTEGER) AS active_link_count
FROM project_workflow_links
WHERE project_id = ?1
`

func (q *Queries) CountActiveProjectWorkflowLinks(ctx context.Context, projectID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countActiveProjectWorkflowLinks, projectID)
	var active_link_count int64
	err := row.Scan(&active_link_count)
	return active_link_count, err
}

const countActiveTaskRunsByWorkspace = `-- name: CountActiveTaskRunsByWorkspace :one
SELECT CAST(COUNT(DISTINCT r.id) AS INTEGER) AS run_count
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
LEFT JOIN sessions s ON s.id = r.session_id
WHERE r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND (
      t.source_workspace_id = ?1
      OR s.workspace_id = ?1
  )
`

func (q *Queries) CountActiveTaskRunsByWorkspace(ctx context.Context, workspaceID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countActiveTaskRunsByWorkspace, workspaceID)
	var run_count int64
	err := row.Scan(&run_count)
	return run_count, err
}

const countAllTaskEdgeReferences = `-- name: CountAllTaskEdgeReferences :one
SELECT CAST(COUNT(*) AS INTEGER) AS ref_count
FROM (
    SELECT te.id
    FROM task_transition_edges te
    WHERE te.workflow_edge_id = ?1
    UNION ALL
    SELECT p.id
    FROM task_node_placements p
    WHERE p.parallel_branch_edge_id = ?1
)
`

func (q *Queries) CountAllTaskEdgeReferences(ctx context.Context, edgeID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countAllTaskEdgeReferences, edgeID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countCurrentTaskNodeAnchorReferences = `-- name: CountCurrentTaskNodeAnchorReferences :one
SELECT CAST(COUNT(*) AS INTEGER) AS ref_count
FROM (
    SELECT p.id
    FROM task_node_placements p
    JOIN task_records t ON t.id = p.task_id
    JOIN workflow_nodes n ON n.id = p.node_id
    WHERE p.node_id = ?1
      AND (
          p.state IN ('active', 'waiting_approval')
          OR (p.state = 'completed' AND n.kind = 'terminal')
      )
      AND t.canceled_at_unix_ms = 0
    UNION ALL
    SELECT tt.id
    FROM task_transition_records tt
    JOIN task_records t ON t.id = tt.task_id
    WHERE tt.source_node_id = ?1
      AND tt.state = 'pending_approval'
      AND t.canceled_at_unix_ms = 0
    UNION ALL
    SELECT te.id
    FROM task_transition_edges te
    JOIN task_transition_records tt ON tt.id = te.task_transition_id
    JOIN task_records t ON t.id = tt.task_id
    WHERE te.target_node_id = ?1
      AND tt.state = 'pending_approval'
      AND te.state = 'pending'
      AND t.canceled_at_unix_ms = 0
)
`

func (q *Queries) CountCurrentTaskNodeAnchorReferences(ctx context.Context, nodeID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countCurrentTaskNodeAnchorReferences, nodeID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countManagedOwnedWorktreesByWorkspace = `-- name: CountManagedOwnedWorktreesByWorkspace :one
SELECT CAST(COUNT(*) AS INTEGER) AS worktree_count
FROM worktrees
WHERE workspace_id = ?1
  AND managed <> 0
  AND created_branch <> 0
`

func (q *Queries) CountManagedOwnedWorktreesByWorkspace(ctx context.Context, workspaceID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countManagedOwnedWorktreesByWorkspace, workspaceID)
	var worktree_count int64
	err := row.Scan(&worktree_count)
	return worktree_count, err
}

const countNonTerminalTasksByManagedWorktree = `-- name: CountNonTerminalTasksByManagedWorktree :one
SELECT CAST(COUNT(DISTINCT t.id) AS INTEGER) AS ref_count
FROM tasks t
JOIN task_node_placements p
    ON p.task_id = t.id
    AND p.state IN ('active', 'waiting_approval')
JOIN workflow_nodes n ON n.id = p.node_id
WHERE t.managed_worktree_id = ?1
  AND t.canceled_at_unix_ms = 0
  AND n.kind != 'terminal'
`

func (q *Queries) CountNonTerminalTasksByManagedWorktree(ctx context.Context, managedWorktreeID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countNonTerminalTasksByManagedWorktree, managedWorktreeID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countNonTerminalTasksByProjectWorkflowLink = `-- name: CountNonTerminalTasksByProjectWorkflowLink :one
SELECT CAST(COUNT(DISTINCT t.id) AS INTEGER) AS task_count
FROM tasks t
JOIN task_node_placements p ON p.task_id = t.id AND p.state IN ('active', 'waiting_approval')
JOIN workflow_nodes n ON n.id = p.node_id
WHERE t.project_workflow_link_id = ?1
  AND t.canceled_at_unix_ms = 0
  AND n.kind != 'terminal'
`

func (q *Queries) CountNonTerminalTasksByProjectWorkflowLink(ctx context.Context, projectWorkflowLinkID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countNonTerminalTasksByProjectWorkflowLink, projectWorkflowLinkID)
	var task_count int64
	err := row.Scan(&task_count)
	return task_count, err
}

const countNonTerminalTasksBySourceWorkspace = `-- name: CountNonTerminalTasksBySourceWorkspace :one
SELECT CAST(COUNT(DISTINCT t.id) AS INTEGER) AS task_count
FROM tasks t
WHERE t.source_workspace_id = ?1
  AND t.canceled_at_unix_ms = 0
  AND (
      EXISTS (
          SELECT 1
          FROM task_node_placements p
          JOIN workflow_nodes n ON n.id = p.node_id
          WHERE p.task_id = t.id
            AND p.state IN ('active', 'waiting_approval')
            AND n.kind != 'terminal'
      )
      OR EXISTS (
          SELECT 1
          FROM task_transitions tt
          WHERE tt.task_id = t.id
            AND tt.state = 'pending_approval'
      )
  )
`

func (q *Queries) CountNonTerminalTasksBySourceWorkspace(ctx context.Context, workspaceID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countNonTerminalTasksBySourceWorkspace, workspaceID)
	var task_count int64
	err := row.Scan(&task_count)
	return task_count, err
}

const countNonTerminalTasksByWorkflow = `-- name: CountNonTerminalTasksByWorkflow :one
SELECT CAST(COUNT(DISTINCT t.id) AS INTEGER) AS task_count
FROM task_records t
JOIN task_node_placements p ON p.task_id = t.id AND p.state IN ('active', 'waiting_approval')
JOIN workflow_nodes n ON n.id = p.node_id
WHERE t.workflow_id = ?1
  AND t.canceled_at_unix_ms = 0
  AND n.kind != 'terminal'
`

func (q *Queries) CountNonTerminalTasksByWorkflow(ctx context.Context, workflowID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countNonTerminalTasksByWorkflow, workflowID)
	var task_count int64
	err := row.Scan(&task_count)
	return task_count, err
}

const countOtherNonTerminalTasksByManagedWorktree = `-- name: CountOtherNonTerminalTasksByManagedWorktree :one
SELECT CAST(COUNT(DISTINCT t.id) AS INTEGER) AS ref_count
FROM tasks t
JOIN task_node_placements p
    ON p.task_id = t.id
    AND p.state IN ('active', 'waiting_approval')
JOIN workflow_nodes n ON n.id = p.node_id
WHERE t.managed_worktree_id = ?1
  AND t.id != ?2
  AND t.canceled_at_unix_ms = 0
  AND n.kind != 'terminal'
`

type CountOtherNonTerminalTasksByManagedWorktreeParams struct {
	ManagedWorktreeID sql.NullString
	TaskID            string
}

func (q *Queries) CountOtherNonTerminalTasksByManagedWorktree(ctx context.Context, arg CountOtherNonTerminalTasksByManagedWorktreeParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, countOtherNonTerminalTasksByManagedWorktree, arg.ManagedWorktreeID, arg.TaskID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countProjectWorkflowLinksByIDAndProject = `-- name: CountProjectWorkflowLinksByIDAndProject :one
SELECT CAST(COUNT(*) AS INTEGER) AS link_count
FROM project_workflow_links
WHERE id = ?1
  AND project_id = ?2
`

type CountProjectWorkflowLinksByIDAndProjectParams struct {
	ProjectWorkflowLinkID string
	ProjectID             string
}

func (q *Queries) CountProjectWorkflowLinksByIDAndProject(ctx context.Context, arg CountProjectWorkflowLinksByIDAndProjectParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, countProjectWorkflowLinksByIDAndProject, arg.ProjectWorkflowLinkID, arg.ProjectID)
	var link_count int64
	err := row.Scan(&link_count)
	return link_count, err
}

const countProjectWorkspaces = `-- name: CountProjectWorkspaces :one
SELECT CAST(COUNT(*) AS INTEGER) AS workspace_count
FROM workspaces
WHERE project_id = ?1
`

func (q *Queries) CountProjectWorkspaces(ctx context.Context, projectID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countProjectWorkspaces, projectID)
	var workspace_count int64
	err := row.Scan(&workspace_count)
	return workspace_count, err
}

const countTaskComments = `-- name: CountTaskComments :one
SELECT CAST(COUNT(*) AS INTEGER)
FROM task_comments
WHERE task_id = ?1
`

func (q *Queries) CountTaskComments(ctx context.Context, taskID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTaskComments, taskID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const countTaskEdgeReferences = `-- name: CountTaskEdgeReferences :one
SELECT CAST(COUNT(*) AS INTEGER) AS ref_count
FROM (
    -- Only live unresolved references block edge deletion. Completed historical
    -- transition edges intentionally rely on ON DELETE SET NULL.
    SELECT te.id
    FROM task_transition_edges te
    JOIN task_transition_records tt ON tt.id = te.task_transition_id
    JOIN task_records t ON t.id = tt.task_id
    WHERE te.workflow_edge_id = ?1
      AND t.canceled_at_unix_ms = 0
      AND tt.state = 'pending_approval'
      AND te.state = 'pending'
    UNION ALL
    SELECT p.id
    FROM task_node_placements p
    JOIN task_records t ON t.id = p.task_id
    JOIN workflow_nodes n ON n.id = p.node_id
    WHERE p.parallel_branch_edge_id = ?1
      AND p.state IN ('active', 'waiting_approval')
      AND t.canceled_at_unix_ms = 0
      AND n.kind != 'terminal'
)
`

func (q *Queries) CountTaskEdgeReferences(ctx context.Context, edgeID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTaskEdgeReferences, edgeID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countTaskNodeReferences = `-- name: CountTaskNodeReferences :one
SELECT CAST(COUNT(*) AS INTEGER) AS ref_count
FROM (
    SELECT p.id FROM task_node_placements p WHERE p.node_id = ?1
    UNION ALL
    SELECT tr.id FROM task_transition_records tr WHERE tr.source_node_id = ?1
    UNION ALL
    SELECT te.id FROM task_transition_edges te WHERE te.target_node_id = ?1
)
`

func (q *Queries) CountTaskNodeReferences(ctx context.Context, nodeID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTaskNodeReferences, nodeID)
	var ref_count int64
	err := row.Scan(&ref_count)
	return ref_count, err
}

const countTaskRunsByTask = `-- name: CountTaskRunsByTask :one
SELECT CAST(COUNT(*) AS INTEGER) AS run_count
FROM task_run_records
WHERE task_id = ?1
`

func (q *Queries) CountTaskRunsByTask(ctx context.Context, taskID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTaskRunsByTask, taskID)
	var run_count int64
	err := row.Scan(&run_count)
	return run_count, err
}

const countTasksByProjectWorkflowLink = `-- name: CountTasksByProjectWorkflowLink :one
SELECT CAST(COUNT(*) AS INTEGER) AS task_count
FROM tasks
WHERE project_workflow_link_id = ?1
`

func (q *Queries) CountTasksByProjectWorkflowLink(ctx context.Context, projectWorkflowLinkID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTasksByProjectWorkflowLink, projectWorkflowLinkID)
	var task_count int64
	err := row.Scan(&task_count)
	return task_count, err
}

const countTasksMissingSourceWorkspaceSnapshot = `-- name: CountTasksMissingSourceWorkspaceSnapshot :one
SELECT CAST(COUNT(*) AS INTEGER) AS task_count
FROM tasks
WHERE source_workspace_id = ?1
  AND (
      NOT json_valid(metadata_json)
      OR NULLIF(json_extract(metadata_json, '$.source_workspace_snapshot.root_path'), '') IS NULL
      OR NULLIF(json_extract(metadata_json, '$.source_workspace_snapshot.display_name'), '') IS NULL
  )
`

func (q *Queries) CountTasksMissingSourceWorkspaceSnapshot(ctx context.Context, workspaceID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countTasksMissingSourceWorkspaceSnapshot, workspaceID)
	var task_count int64
	err := row.Scan(&task_count)
	return task_count, err
}

const countUnresolvedTaskRunsAtWorkflowNode = `-- name: CountUnresolvedTaskRunsAtWorkflowNode :one
SELECT CAST(COUNT(DISTINCT r.id) AS INTEGER) AS run_count
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE t.workflow_id = ?1
  AND r.node_id = ?2
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND (
      (
          r.started_at_unix_ms > 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
      )
      OR (
          r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms > 0
      )
      OR (
          r.automation_requested_at_unix_ms > 0
          AND r.started_at_unix_ms = 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND r.waiting_ask_id = ''
      )
  )
`

type CountUnresolvedTaskRunsAtWorkflowNodeParams struct {
	WorkflowID string
	NodeID     sql.NullString
}

func (q *Queries) CountUnresolvedTaskRunsAtWorkflowNode(ctx context.Context, arg CountUnresolvedTaskRunsAtWorkflowNodeParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, countUnresolvedTaskRunsAtWorkflowNode, arg.WorkflowID, arg.NodeID)
	var run_count int64
	err := row.Scan(&run_count)
	return run_count, err
}

const countWorkflowNodesByGroup = `-- name: CountWorkflowNodesByGroup :one
SELECT CAST(COUNT(*) AS INTEGER) AS node_count
FROM workflow_nodes
WHERE group_id = ?1
`

func (q *Queries) CountWorkflowNodesByGroup(ctx context.Context, groupID sql.NullString) (int64, error) {
	row := q.db.QueryRowContext(ctx, countWorkflowNodesByGroup, groupID)
	var node_count int64
	err := row.Scan(&node_count)
	return node_count, err
}

const deleteProject = `-- name: DeleteProject :execrows
DELETE FROM projects
WHERE id = ?1
`

func (q *Queries) DeleteProject(ctx context.Context, projectID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteProject, projectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteProjectTasks = `-- name: DeleteProjectTasks :exec
DELETE FROM tasks
WHERE id IN (
    SELECT id FROM task_records WHERE project_id = ?1
)
`

func (q *Queries) DeleteProjectTasks(ctx context.Context, projectID string) error {
	_, err := q.db.ExecContext(ctx, deleteProjectTasks, projectID)
	return err
}

const deleteProjectWorkflowLink = `-- name: DeleteProjectWorkflowLink :execrows
DELETE FROM project_workflow_links
WHERE id = ?1
`

func (q *Queries) DeleteProjectWorkflowLink(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteProjectWorkflowLink, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteProjectWorkflowLinkUnlessDefaultNeedsReplacement = `-- name: DeleteProjectWorkflowLinkUnlessDefaultNeedsReplacement :execrows
DELETE FROM project_workflow_links
WHERE project_workflow_links.id = ?1
  AND NOT (
      EXISTS (
          SELECT 1
          FROM projects p
          WHERE p.id = project_workflow_links.project_id
            AND p.default_project_workflow_link_id = project_workflow_links.id
      )
      AND (
          SELECT COUNT(*)
          FROM project_workflow_links active
          WHERE active.project_id = project_workflow_links.project_id
      ) > 1
  )
`

func (q *Queries) DeleteProjectWorkflowLinkUnlessDefaultNeedsReplacement(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteProjectWorkflowLinkUnlessDefaultNeedsReplacement, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteProjectWorkflowLinksByWorkflowID = `-- name: DeleteProjectWorkflowLinksByWorkflowID :execrows
DELETE FROM project_workflow_links
WHERE workflow_id = ?1
`

func (q *Queries) DeleteProjectWorkflowLinksByWorkflowID(ctx context.Context, workflowID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteProjectWorkflowLinksByWorkflowID, workflowID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteSessionRecordByID = `-- name: DeleteSessionRecordByID :execrows
DELETE FROM sessions
WHERE id = ?1
`

func (q *Queries) DeleteSessionRecordByID(ctx context.Context, sessionID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteSessionRecordByID, sessionID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteTask = `-- name: DeleteTask :execrows
DELETE FROM tasks
WHERE id = ?1
`

func (q *Queries) DeleteTask(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteTask, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteTaskComment = `-- name: DeleteTaskComment :execrows
DELETE FROM task_comments
WHERE id = ?1
`

func (q *Queries) DeleteTaskComment(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteTaskComment, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteTaskCommentsByTask = `-- name: DeleteTaskCommentsByTask :execrows
DELETE FROM task_comments
WHERE task_id = ?1
`

func (q *Queries) DeleteTaskCommentsByTask(ctx context.Context, taskID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteTaskCommentsByTask, taskID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteTaskNodePlacementsByTask = `-- name: DeleteTaskNodePlacementsByTask :execrows
DELETE FROM task_node_placements
WHERE task_id = ?1
`

func (q *Queries) DeleteTaskNodePlacementsByTask(ctx context.Context, taskID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteTaskNodePlacementsByTask, taskID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteTaskTransitionsByTask = `-- name: DeleteTaskTransitionsByTask :execrows
DELETE FROM task_transitions
WHERE task_id = ?1
`

func (q *Queries) DeleteTaskTransitionsByTask(ctx context.Context, taskID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteTaskTransitionsByTask, taskID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowByID = `-- name: DeleteWorkflowByID :execrows
DELETE FROM workflows
WHERE id = ?1
`

func (q *Queries) DeleteWorkflowByID(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowByID, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowEdge = `-- name: DeleteWorkflowEdge :execrows
DELETE FROM workflow_edges
WHERE id = ?1
`

func (q *Queries) DeleteWorkflowEdge(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowEdge, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowNode = `-- name: DeleteWorkflowNode :execrows
DELETE FROM workflow_nodes
WHERE id = ?1
`

func (q *Queries) DeleteWorkflowNode(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowNode, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowNodeGroup = `-- name: DeleteWorkflowNodeGroup :execrows
DELETE FROM workflow_node_groups
WHERE id = ?1
  AND workflow_id = ?2
`

type DeleteWorkflowNodeGroupParams struct {
	ID         string
	WorkflowID string
}

func (q *Queries) DeleteWorkflowNodeGroup(ctx context.Context, arg DeleteWorkflowNodeGroupParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowNodeGroup, arg.ID, arg.WorkflowID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowTasksByWorkflowID = `-- name: DeleteWorkflowTasksByWorkflowID :execrows
DELETE FROM tasks
WHERE id IN (
    SELECT task_records.id
    FROM task_records
    WHERE workflow_id = ?1
)
`

func (q *Queries) DeleteWorkflowTasksByWorkflowID(ctx context.Context, workflowID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowTasksByWorkflowID, workflowID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkflowTransitionGroupByID = `-- name: DeleteWorkflowTransitionGroupByID :execrows
DELETE FROM workflow_transition_groups
WHERE id = ?1
`

func (q *Queries) DeleteWorkflowTransitionGroupByID(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkflowTransitionGroupByID, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorkspaceBindingByID = `-- name: DeleteWorkspaceBindingByID :execrows
DELETE FROM workspaces
WHERE project_id = ?1
  AND id = ?2
`

type DeleteWorkspaceBindingByIDParams struct {
	ProjectID   string
	WorkspaceID string
}

func (q *Queries) DeleteWorkspaceBindingByID(ctx context.Context, arg DeleteWorkspaceBindingByIDParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorkspaceBindingByID, arg.ProjectID, arg.WorkspaceID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const deleteWorktreeByID = `-- name: DeleteWorktreeByID :execrows
DELETE FROM worktrees
WHERE id = ?1
`

func (q *Queries) DeleteWorktreeByID(ctx context.Context, id string) (int64, error) {
	result, err := q.db.ExecContext(ctx, deleteWorktreeByID, id)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const getActiveProjectWorkflowLinkByWorkflow = `-- name: GetActiveProjectWorkflowLinkByWorkflow :one
SELECT
    id,
    project_id,
    workflow_id,
    is_default,
    created_at_unix_ms,
    updated_at_unix_ms
FROM project_workflow_link_records
WHERE project_id = ?1
  AND workflow_id = ?2
LIMIT 1
`

type GetActiveProjectWorkflowLinkByWorkflowParams struct {
	ProjectID  string
	WorkflowID string
}

func (q *Queries) GetActiveProjectWorkflowLinkByWorkflow(ctx context.Context, arg GetActiveProjectWorkflowLinkByWorkflowParams) (ProjectWorkflowLinkRecord, error) {
	row := q.db.QueryRowContext(ctx, getActiveProjectWorkflowLinkByWorkflow, arg.ProjectID, arg.WorkflowID)
	var i ProjectWorkflowLinkRecord
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.WorkflowID,
		&i.IsDefault,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getActiveStartPlacementForTask = `-- name: GetActiveStartPlacementForTask :one
SELECT
    p.id,
    p.task_id,
    p.node_id,
    p.state,
    p.created_by_transition_id,
    p.parallel_batch_transition_id,
    p.parallel_branch_edge_id,
    p.created_at_unix_ms,
    p.updated_at_unix_ms
FROM task_node_placement_records p
JOIN workflow_nodes n ON n.id = p.node_id
WHERE p.task_id = ?1
  AND p.state = 'active'
  AND n.kind = 'start'
LIMIT 1
`

func (q *Queries) GetActiveStartPlacementForTask(ctx context.Context, taskID string) (TaskNodePlacementRecord, error) {
	row := q.db.QueryRowContext(ctx, getActiveStartPlacementForTask, taskID)
	var i TaskNodePlacementRecord
	err := row.Scan(
		&i.ID,
		&i.TaskID,
		&i.NodeID,
		&i.State,
		&i.CreatedByTransitionID,
		&i.ParallelBatchTransitionID,
		&i.ParallelBranchEdgeID,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getContextSourceBatchScope = `-- name: GetContextSourceBatchScope :one
SELECT parallel_batch_transition_id
FROM task_node_placements
WHERE task_node_placements.id = ?1
LIMIT 1
`

func (q *Queries) GetContextSourceBatchScope(ctx context.Context, placementID string) (sql.NullString, error) {
	row := q.db.QueryRowContext(ctx, getContextSourceBatchScope, placementID)
	var parallel_batch_transition_id sql.NullString
	err := row.Scan(&parallel_batch_transition_id)
	return parallel_batch_transition_id, err
}

const getDefaultProjectWorkflowLink = `-- name: GetDefaultProjectWorkflowLink :one
SELECT
    id,
    project_id,
    workflow_id,
    is_default,
    created_at_unix_ms,
    updated_at_unix_ms
FROM project_workflow_link_records
WHERE project_id = ?1
  AND is_default = 1
LIMIT 1
`

func (q *Queries) GetDefaultProjectWorkflowLink(ctx context.Context, projectID string) (ProjectWorkflowLinkRecord, error) {
	row := q.db.QueryRowContext(ctx, getDefaultProjectWorkflowLink, projectID)
	var i ProjectWorkflowLinkRecord
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.WorkflowID,
		&i.IsDefault,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getExistingJoinPlacement = `-- name: GetExistingJoinPlacement :one
SELECT id
FROM task_node_placements
WHERE task_id = ?1
  AND node_id = ?2
  AND parallel_batch_transition_id = ?3
LIMIT 1
`

type GetExistingJoinPlacementParams struct {
	TaskID  string
	NodeID  sql.NullString
	BatchID sql.NullString
}

func (q *Queries) GetExistingJoinPlacement(ctx context.Context, arg GetExistingJoinPlacementParams) (string, error) {
	row := q.db.QueryRowContext(ctx, getExistingJoinPlacement, arg.TaskID, arg.NodeID, arg.BatchID)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getLatestCompletedContextSourceRun = `-- name: GetLatestCompletedContextSourceRun :one
SELECT r.id
FROM task_runs r
JOIN task_node_placements p ON p.id = r.placement_id
WHERE p.task_id = ?1
  AND p.node_id = ?2
  AND r.completed_at_unix_ms > 0
  AND r.completed_at_unix_ms <= ?3
ORDER BY r.completed_at_unix_ms DESC, r.rowid DESC
LIMIT 1
`

type GetLatestCompletedContextSourceRunParams struct {
	TaskID       string
	NodeID       sql.NullString
	BeforeUnixMs int64
}

func (q *Queries) GetLatestCompletedContextSourceRun(ctx context.Context, arg GetLatestCompletedContextSourceRunParams) (string, error) {
	row := q.db.QueryRowContext(ctx, getLatestCompletedContextSourceRun, arg.TaskID, arg.NodeID, arg.BeforeUnixMs)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getLatestCompletedContextSourceRunInBatch = `-- name: GetLatestCompletedContextSourceRunInBatch :one
SELECT r.id
FROM task_runs r
JOIN task_node_placements p ON p.id = r.placement_id
WHERE p.task_id = ?1
  AND p.node_id = ?2
  AND p.parallel_batch_transition_id = ?3
  AND r.completed_at_unix_ms > 0
  AND r.completed_at_unix_ms <= ?4
ORDER BY r.completed_at_unix_ms DESC, r.rowid DESC
LIMIT 1
`

type GetLatestCompletedContextSourceRunInBatchParams struct {
	TaskID       string
	NodeID       sql.NullString
	BatchID      sql.NullString
	BeforeUnixMs int64
}

func (q *Queries) GetLatestCompletedContextSourceRunInBatch(ctx context.Context, arg GetLatestCompletedContextSourceRunInBatchParams) (string, error) {
	row := q.db.QueryRowContext(ctx, getLatestCompletedContextSourceRunInBatch,
		arg.TaskID,
		arg.NodeID,
		arg.BatchID,
		arg.BeforeUnixMs,
	)
	var id string
	err := row.Scan(&id)
	return id, err
}

const getLatestRunForPlacement = `-- name: GetLatestRunForPlacement :one
SELECT id, session_id
FROM task_runs
WHERE placement_id = ?1
ORDER BY created_at_unix_ms DESC, rowid DESC
LIMIT 1
`

type GetLatestRunForPlacementRow struct {
	ID        string
	SessionID sql.NullString
}

func (q *Queries) GetLatestRunForPlacement(ctx context.Context, placementID string) (GetLatestRunForPlacementRow, error) {
	row := q.db.QueryRowContext(ctx, getLatestRunForPlacement, placementID)
	var i GetLatestRunForPlacementRow
	err := row.Scan(&i.ID, &i.SessionID)
	return i, err
}

const getLatestTransitionOutputValues = `-- name: GetLatestTransitionOutputValues :one
SELECT tr.output_values_json
FROM task_transitions tr
WHERE tr.task_id = ?1
  AND tr.transition_id = ?2
  AND tr.applied_at_unix_ms > 0
  AND tr.applied_at_unix_ms <= ?3
  AND tr.state != 'rejected'
ORDER BY tr.applied_at_unix_ms DESC, tr.created_at_unix_ms DESC, tr.rowid DESC
LIMIT 1
`

type GetLatestTransitionOutputValuesParams struct {
	TaskID       string
	TransitionID string
	BeforeUnixMs int64
}

func (q *Queries) GetLatestTransitionOutputValues(ctx context.Context, arg GetLatestTransitionOutputValuesParams) (string, error) {
	row := q.db.QueryRowContext(ctx, getLatestTransitionOutputValues, arg.TaskID, arg.TransitionID, arg.BeforeUnixMs)
	var output_values_json string
	err := row.Scan(&output_values_json)
	return output_values_json, err
}

const getLatestTransitionOutputValuesInBatch = `-- name: GetLatestTransitionOutputValuesInBatch :one
SELECT tr.output_values_json
FROM task_transitions tr
JOIN task_node_placements p ON p.id = tr.source_placement_id
WHERE tr.task_id = ?1
  AND tr.transition_id = ?2
  AND p.parallel_batch_transition_id = ?3
  AND tr.applied_at_unix_ms > 0
  AND tr.applied_at_unix_ms <= ?4
  AND tr.state != 'rejected'
ORDER BY tr.applied_at_unix_ms DESC, tr.created_at_unix_ms DESC, tr.rowid DESC
LIMIT 1
`

type GetLatestTransitionOutputValuesInBatchParams struct {
	TaskID       string
	TransitionID string
	BatchID      sql.NullString
	BeforeUnixMs int64
}

func (q *Queries) GetLatestTransitionOutputValuesInBatch(ctx context.Context, arg GetLatestTransitionOutputValuesInBatchParams) (string, error) {
	row := q.db.QueryRowContext(ctx, getLatestTransitionOutputValuesInBatch,
		arg.TaskID,
		arg.TransitionID,
		arg.BatchID,
		arg.BeforeUnixMs,
	)
	var output_values_json string
	err := row.Scan(&output_values_json)
	return output_values_json, err
}

const getManualMovePreviousTransition = `-- name: GetManualMovePreviousTransition :one
SELECT
    tr.transition_group_id,
    tr.transition_id,
    tr.transition_display_name,
    tr.output_values_json,
    tr.source_run_id,
    te.workflow_edge_id,
    te.edge_key,
    te.context_mode,
    te.requires_approval,
    te.input_bindings_json,
    te.output_requirements_json,
    te.metadata_json
FROM task_transition_records tr
JOIN task_transitions storage ON storage.id = tr.id
JOIN task_transition_edges te ON te.task_transition_id = tr.id
JOIN task_node_placements source_placement ON source_placement.id = tr.source_placement_id
WHERE te.target_placement_id = ?1
  AND source_placement.node_id = ?2
ORDER BY tr.created_at_unix_ms DESC, storage.rowid DESC
LIMIT 1
`

type GetManualMovePreviousTransitionParams struct {
	SourcePlacementID sql.NullString
	TargetNodeID      sql.NullString
}

type GetManualMovePreviousTransitionRow struct {
	TransitionGroupID      sql.NullString
	TransitionID           string
	TransitionDisplayName  string
	OutputValuesJson       string
	SourceRunID            sql.NullString
	WorkflowEdgeID         sql.NullString
	EdgeKey                string
	ContextMode            string
	RequiresApproval       int64
	InputBindingsJson      string
	OutputRequirementsJson string
	MetadataJson           string
}

func (q *Queries) GetManualMovePreviousTransition(ctx context.Context, arg GetManualMovePreviousTransitionParams) (GetManualMovePreviousTransitionRow, error) {
	row := q.db.QueryRowContext(ctx, getManualMovePreviousTransition, arg.SourcePlacementID, arg.TargetNodeID)
	var i GetManualMovePreviousTransitionRow
	err := row.Scan(
		&i.TransitionGroupID,
		&i.TransitionID,
		&i.TransitionDisplayName,
		&i.OutputValuesJson,
		&i.SourceRunID,
		&i.WorkflowEdgeID,
		&i.EdgeKey,
		&i.ContextMode,
		&i.RequiresApproval,
		&i.InputBindingsJson,
		&i.OutputRequirementsJson,
		&i.MetadataJson,
	)
	return i, err
}

const getProjectDeleteBlockerCounts = `-- name: GetProjectDeleteBlockerCounts :one
SELECT
    CAST((
        SELECT COUNT(DISTINCT id)
        FROM (
            SELECT t.id
            FROM task_records t
            JOIN task_node_placements p ON p.task_id = t.id AND p.state IN ('active', 'waiting_approval')
            JOIN workflow_nodes n ON n.id = p.node_id
            WHERE t.project_id = ?1
              AND t.canceled_at_unix_ms = 0
              -- Backlog/start-node tasks are drafts, not active project work.
              AND n.kind NOT IN ('start', 'terminal')
            UNION
            SELECT t.id
            FROM task_records t
            JOIN task_transitions tt ON tt.task_id = t.id AND tt.state = 'pending_approval'
            WHERE t.project_id = ?1
              AND t.canceled_at_unix_ms = 0
        )
    ) AS INTEGER) AS non_terminal_tasks,
    CAST((
        SELECT COUNT(DISTINCT r.id)
        FROM task_run_records r
        JOIN task_records t ON t.id = r.task_id
        JOIN task_node_placements p ON p.id = r.placement_id
        JOIN workflow_nodes n ON n.id = r.node_id
        WHERE t.project_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND r.started_at_unix_ms > 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND p.state = 'active'
          AND n.kind IN ('agent', 'script')
    ) AS INTEGER) AS active_runs,
    CAST((
        SELECT COUNT(DISTINCT r.id)
        FROM task_run_records r
        JOIN task_records t ON t.id = r.task_id
        JOIN task_node_placements p ON p.id = r.placement_id
        JOIN workflow_nodes n ON n.id = r.node_id
        WHERE t.project_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND r.automation_requested_at_unix_ms > 0
          AND r.started_at_unix_ms = 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND r.waiting_ask_id = ''
          AND p.state = 'active'
          AND n.kind IN ('agent', 'script')
    ) AS INTEGER) AS runnable_runs
`

type GetProjectDeleteBlockerCountsRow struct {
	NonTerminalTasks int64
	ActiveRuns       int64
	RunnableRuns     int64
}

func (q *Queries) GetProjectDeleteBlockerCounts(ctx context.Context, deleteProjectID string) (GetProjectDeleteBlockerCountsRow, error) {
	row := q.db.QueryRowContext(ctx, getProjectDeleteBlockerCounts, deleteProjectID)
	var i GetProjectDeleteBlockerCountsRow
	err := row.Scan(&i.NonTerminalTasks, &i.ActiveRuns, &i.RunnableRuns)
	return i, err
}

const getProjectDisplayName = `-- name: GetProjectDisplayName :one
SELECT display_name
FROM projects
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetProjectDisplayName(ctx context.Context, projectID string) (string, error) {
	row := q.db.QueryRowContext(ctx, getProjectDisplayName, projectID)
	var display_name string
	err := row.Scan(&display_name)
	return display_name, err
}

const getProjectKeyState = `-- name: GetProjectKeyState :one
SELECT
    p.id,
    p.display_name,
    p.project_key,
    p.next_task_seq,
    CAST(COALESCE(COUNT(t.id), 0) AS INTEGER) AS task_count
FROM projects p
LEFT JOIN task_records t ON t.project_id = p.id
WHERE p.id = ?1
GROUP BY p.id, p.display_name, p.project_key, p.next_task_seq
LIMIT 1
`

type GetProjectKeyStateRow struct {
	ID          string
	DisplayName string
	ProjectKey  string
	NextTaskSeq int64
	TaskCount   int64
}

func (q *Queries) GetProjectKeyState(ctx context.Context, projectID string) (GetProjectKeyStateRow, error) {
	row := q.db.QueryRowContext(ctx, getProjectKeyState, projectID)
	var i GetProjectKeyStateRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.ProjectKey,
		&i.NextTaskSeq,
		&i.TaskCount,
	)
	return i, err
}

const getProjectPrimaryWorkspaceID = `-- name: GetProjectPrimaryWorkspaceID :one
SELECT primary_workspace_id
FROM projects
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetProjectPrimaryWorkspaceID(ctx context.Context, projectID string) (string, error) {
	row := q.db.QueryRowContext(ctx, getProjectPrimaryWorkspaceID, projectID)
	var primary_workspace_id string
	err := row.Scan(&primary_workspace_id)
	return primary_workspace_id, err
}

const getProjectSummary = `-- name: GetProjectSummary :one
SELECT
    p.id,
    p.display_name,
    p.project_key,
    COALESCE(w.canonical_root_path, '') AS root_path,
    CAST(COALESCE(COUNT(s.id), 0) AS INTEGER) AS session_count,
    COALESCE(MAX(s.updated_at_unix_ms), p.updated_at_unix_ms) AS latest_activity_unix_ms
FROM projects p
LEFT JOIN workspaces w ON w.id = p.primary_workspace_id AND w.project_id = p.id
LEFT JOIN sessions s ON s.project_id = p.id AND s.launch_visible <> 0
WHERE p.id = ?1
GROUP BY p.id, p.display_name, p.project_key, w.canonical_root_path, p.updated_at_unix_ms
LIMIT 1
`

type GetProjectSummaryRow struct {
	ID                   string
	DisplayName          string
	ProjectKey           string
	RootPath             string
	SessionCount         int64
	LatestActivityUnixMs int64
}

func (q *Queries) GetProjectSummary(ctx context.Context, projectID string) (GetProjectSummaryRow, error) {
	row := q.db.QueryRowContext(ctx, getProjectSummary, projectID)
	var i GetProjectSummaryRow
	err := row.Scan(
		&i.ID,
		&i.DisplayName,
		&i.ProjectKey,
		&i.RootPath,
		&i.SessionCount,
		&i.LatestActivityUnixMs,
	)
	return i, err
}

const getProjectWorkflowLink = `-- name: GetProjectWorkflowLink :one
SELECT
    id,
    project_id,
    workflow_id,
    is_default,
    created_at_unix_ms,
    updated_at_unix_ms
FROM project_workflow_link_records
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetProjectWorkflowLink(ctx context.Context, id string) (ProjectWorkflowLinkRecord, error) {
	row := q.db.QueryRowContext(ctx, getProjectWorkflowLink, id)
	var i ProjectWorkflowLinkRecord
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.WorkflowID,
		&i.IsDefault,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getProjectWorkflowUnlinkState = `-- name: GetProjectWorkflowUnlinkState :one
SELECT
    COALESCE(p.default_project_workflow_link_id, '') AS default_project_workflow_link_id,
    (SELECT CAST(COUNT(*) AS INTEGER) FROM project_workflow_links active WHERE active.project_id = p.id) AS active_link_count
FROM projects p
WHERE p.id = ?1
`

type GetProjectWorkflowUnlinkStateRow struct {
	DefaultProjectWorkflowLinkID string
	ActiveLinkCount              int64
}

func (q *Queries) GetProjectWorkflowUnlinkState(ctx context.Context, projectID string) (GetProjectWorkflowUnlinkStateRow, error) {
	row := q.db.QueryRowContext(ctx, getProjectWorkflowUnlinkState, projectID)
	var i GetProjectWorkflowUnlinkStateRow
	err := row.Scan(&i.DefaultProjectWorkflowLinkID, &i.ActiveLinkCount)
	return i, err
}

const getRunInputValues = `-- name: GetRunInputValues :one
SELECT
    tr.commentary,
    tr.output_values_json,
    te.input_bindings_json
FROM task_node_placements p
JOIN task_transition_edges te ON te.target_placement_id = p.id
JOIN task_transitions tr ON tr.id = te.task_transition_id
WHERE p.id = ?1
ORDER BY te.rowid ASC
LIMIT 1
`

type GetRunInputValuesRow struct {
	Commentary        string
	OutputValuesJson  string
	InputBindingsJson string
}

func (q *Queries) GetRunInputValues(ctx context.Context, placementID string) (GetRunInputValuesRow, error) {
	row := q.db.QueryRowContext(ctx, getRunInputValues, placementID)
	var i GetRunInputValuesRow
	err := row.Scan(&i.Commentary, &i.OutputValuesJson, &i.InputBindingsJson)
	return i, err
}

const getRunTransitionContext = `-- name: GetRunTransitionContext :one
SELECT
    te.context_mode,
    tr.source_run_id,
    tr.source_node_display_name,
    te.target_node_display_name
FROM task_node_placements p
JOIN task_transition_edges te ON te.target_placement_id = p.id
JOIN task_transitions tr ON tr.id = te.task_transition_id
WHERE p.id = ?1
ORDER BY te.rowid ASC
LIMIT 1
`

type GetRunTransitionContextRow struct {
	ContextMode           string
	SourceRunID           sql.NullString
	SourceNodeDisplayName string
	TargetNodeDisplayName string
}

func (q *Queries) GetRunTransitionContext(ctx context.Context, placementID string) (GetRunTransitionContextRow, error) {
	row := q.db.QueryRowContext(ctx, getRunTransitionContext, placementID)
	var i GetRunTransitionContextRow
	err := row.Scan(
		&i.ContextMode,
		&i.SourceRunID,
		&i.SourceNodeDisplayName,
		&i.TargetNodeDisplayName,
	)
	return i, err
}

const getRunWaitingAskEventIdentity = `-- name: GetRunWaitingAskEventIdentity :one
SELECT t.project_id, t.workflow_id, t.id AS task_id
FROM task_runs r
JOIN task_node_placements p ON p.id = r.placement_id
JOIN task_records t ON t.id = p.task_id
WHERE r.id = ?1
`

type GetRunWaitingAskEventIdentityRow struct {
	ProjectID  string
	WorkflowID string
	TaskID     string
}

func (q *Queries) GetRunWaitingAskEventIdentity(ctx context.Context, runID string) (GetRunWaitingAskEventIdentityRow, error) {
	row := q.db.QueryRowContext(ctx, getRunWaitingAskEventIdentity, runID)
	var i GetRunWaitingAskEventIdentityRow
	err := row.Scan(&i.ProjectID, &i.WorkflowID, &i.TaskID)
	return i, err
}

const getSessionExecutionTargetByID = `-- name: GetSessionExecutionTargetByID :one
SELECT
    s.id AS session_id,
    s.project_id,
    COALESCE(s.workspace_id, '') AS workspace_id,
    CAST(COALESCE(json_extract(s.metadata_json, '$.workspace_container'), '') AS TEXT) AS workspace_snapshot_name,
    COALESCE(w.canonical_root_path, json_extract(s.metadata_json, '$.workspace_root'), '') AS workspace_root,
    s.worktree_id,
    wt.canonical_root_path AS worktree_root,
    s.cwd_relpath
FROM sessions s
LEFT JOIN workspaces w ON w.id = s.workspace_id
LEFT JOIN worktrees wt ON wt.id = s.worktree_id
WHERE s.id = ?1
LIMIT 1
`

type GetSessionExecutionTargetByIDRow struct {
	SessionID             string
	ProjectID             string
	WorkspaceID           string
	WorkspaceSnapshotName string
	WorkspaceRoot         string
	WorktreeID            sql.NullString
	WorktreeRoot          sql.NullString
	CwdRelpath            string
}

func (q *Queries) GetSessionExecutionTargetByID(ctx context.Context, sessionID string) (GetSessionExecutionTargetByIDRow, error) {
	row := q.db.QueryRowContext(ctx, getSessionExecutionTargetByID, sessionID)
	var i GetSessionExecutionTargetByIDRow
	err := row.Scan(
		&i.SessionID,
		&i.ProjectID,
		&i.WorkspaceID,
		&i.WorkspaceSnapshotName,
		&i.WorkspaceRoot,
		&i.WorktreeID,
		&i.WorktreeRoot,
		&i.CwdRelpath,
	)
	return i, err
}

const getSessionPromptHistoryEntryBySourceID = `-- name: GetSessionPromptHistoryEntryBySourceID :one
SELECT
    sequence,
    session_id,
    source_id,
    text,
    created_at_unix_ms
FROM session_prompt_history_entries
WHERE session_id = ?1
  AND source_id = ?2
LIMIT 1
`

type GetSessionPromptHistoryEntryBySourceIDParams struct {
	SessionID string
	SourceID  string
}

func (q *Queries) GetSessionPromptHistoryEntryBySourceID(ctx context.Context, arg GetSessionPromptHistoryEntryBySourceIDParams) (SessionPromptHistoryEntry, error) {
	row := q.db.QueryRowContext(ctx, getSessionPromptHistoryEntryBySourceID, arg.SessionID, arg.SourceID)
	var i SessionPromptHistoryEntry
	err := row.Scan(
		&i.Sequence,
		&i.SessionID,
		&i.SourceID,
		&i.Text,
		&i.CreatedAtUnixMs,
	)
	return i, err
}

const getSessionRecordByID = `-- name: GetSessionRecordByID :one
SELECT
    s.id,
    s.artifact_relpath,
    s.name,
    s.first_prompt_preview,
    s.input_draft,
    s.parent_session_id,
    s.created_at_unix_ms,
    s.updated_at_unix_ms,
    s.last_sequence,
    s.model_request_count,
    s.continuation_json,
    s.locked_json,
    s.usage_state_json,
    s.metadata_json,
    COALESCE(w.canonical_root_path, json_extract(s.metadata_json, '$.workspace_root'), '') AS workspace_root
FROM sessions s
LEFT JOIN workspaces w ON w.id = s.workspace_id
WHERE s.id = ?1
LIMIT 1
`

type GetSessionRecordByIDRow struct {
	ID                 string
	ArtifactRelpath    string
	Name               string
	FirstPromptPreview string
	InputDraft         string
	ParentSessionID    string
	CreatedAtUnixMs    int64
	UpdatedAtUnixMs    int64
	LastSequence       int64
	ModelRequestCount  int64
	ContinuationJson   string
	LockedJson         string
	UsageStateJson     string
	MetadataJson       string
	WorkspaceRoot      string
}

func (q *Queries) GetSessionRecordByID(ctx context.Context, sessionID string) (GetSessionRecordByIDRow, error) {
	row := q.db.QueryRowContext(ctx, getSessionRecordByID, sessionID)
	var i GetSessionRecordByIDRow
	err := row.Scan(
		&i.ID,
		&i.ArtifactRelpath,
		&i.Name,
		&i.FirstPromptPreview,
		&i.InputDraft,
		&i.ParentSessionID,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
		&i.LastSequence,
		&i.ModelRequestCount,
		&i.ContinuationJson,
		&i.LockedJson,
		&i.UsageStateJson,
		&i.MetadataJson,
		&i.WorkspaceRoot,
	)
	return i, err
}

const getTask = `-- name: GetTask :one
SELECT
    id,
    project_id,
    project_workflow_link_id,
    workflow_id,
    workflow_revision_seen,
    task_seq,
    short_id,
    title,
    body,
    source_url,
    source_workspace_id,
    managed_worktree_id,
    canceled_at_unix_ms,
    cancellation_reason,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
FROM task_records
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetTask(ctx context.Context, id string) (TaskRecord, error) {
	row := q.db.QueryRowContext(ctx, getTask, id)
	var i TaskRecord
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.ProjectWorkflowLinkID,
		&i.WorkflowID,
		&i.WorkflowRevisionSeen,
		&i.TaskSeq,
		&i.ShortID,
		&i.Title,
		&i.Body,
		&i.SourceUrl,
		&i.SourceWorkspaceID,
		&i.ManagedWorktreeID,
		&i.CanceledAtUnixMs,
		&i.CancellationReason,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
		&i.MetadataJson,
	)
	return i, err
}

const getTaskByProjectShortID = `-- name: GetTaskByProjectShortID :one
SELECT
    id,
    project_id,
    project_workflow_link_id,
    workflow_id,
    workflow_revision_seen,
    task_seq,
    short_id,
    title,
    body,
    source_url,
    source_workspace_id,
    managed_worktree_id,
    canceled_at_unix_ms,
    cancellation_reason,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
FROM task_records
WHERE project_id = ?1
  AND short_id = ?2
LIMIT 1
`

type GetTaskByProjectShortIDParams struct {
	ProjectID string
	ShortID   string
}

func (q *Queries) GetTaskByProjectShortID(ctx context.Context, arg GetTaskByProjectShortIDParams) (TaskRecord, error) {
	row := q.db.QueryRowContext(ctx, getTaskByProjectShortID, arg.ProjectID, arg.ShortID)
	var i TaskRecord
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.ProjectWorkflowLinkID,
		&i.WorkflowID,
		&i.WorkflowRevisionSeen,
		&i.TaskSeq,
		&i.ShortID,
		&i.Title,
		&i.Body,
		&i.SourceUrl,
		&i.SourceWorkspaceID,
		&i.ManagedWorktreeID,
		&i.CanceledAtUnixMs,
		&i.CancellationReason,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
		&i.MetadataJson,
	)
	return i, err
}

const getTaskIdentityForComment = `-- name: GetTaskIdentityForComment :one
SELECT t.id AS task_id, t.project_id, t.workflow_id
FROM task_comments c
JOIN task_records t ON t.id = c.task_id
WHERE c.id = ?1
LIMIT 1
`

type GetTaskIdentityForCommentRow struct {
	TaskID     string
	ProjectID  string
	WorkflowID string
}

func (q *Queries) GetTaskIdentityForComment(ctx context.Context, commentID string) (GetTaskIdentityForCommentRow, error) {
	row := q.db.QueryRowContext(ctx, getTaskIdentityForComment, commentID)
	var i GetTaskIdentityForCommentRow
	err := row.Scan(&i.TaskID, &i.ProjectID, &i.WorkflowID)
	return i, err
}

const getTaskIdentityForTransition = `-- name: GetTaskIdentityForTransition :one
SELECT t.id, t.project_id, t.workflow_id
FROM task_transitions tt
JOIN task_records t ON t.id = tt.task_id
WHERE tt.id = ?1
LIMIT 1
`

type GetTaskIdentityForTransitionRow struct {
	ID         string
	ProjectID  string
	WorkflowID string
}

func (q *Queries) GetTaskIdentityForTransition(ctx context.Context, transitionID string) (GetTaskIdentityForTransitionRow, error) {
	row := q.db.QueryRowContext(ctx, getTaskIdentityForTransition, transitionID)
	var i GetTaskIdentityForTransitionRow
	err := row.Scan(&i.ID, &i.ProjectID, &i.WorkflowID)
	return i, err
}

const getTaskProjectWorkflowIDs = `-- name: GetTaskProjectWorkflowIDs :one
SELECT project_id, workflow_id
FROM task_records
WHERE id = ?1
LIMIT 1
`

type GetTaskProjectWorkflowIDsRow struct {
	ProjectID  string
	WorkflowID string
}

func (q *Queries) GetTaskProjectWorkflowIDs(ctx context.Context, taskID string) (GetTaskProjectWorkflowIDsRow, error) {
	row := q.db.QueryRowContext(ctx, getTaskProjectWorkflowIDs, taskID)
	var i GetTaskProjectWorkflowIDsRow
	err := row.Scan(&i.ProjectID, &i.WorkflowID)
	return i, err
}

const getTaskRun = `-- name: GetTaskRun :one
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetTaskRun(ctx context.Context, id string) (TaskRunRecord, error) {
	row := q.db.QueryRowContext(ctx, getTaskRun, id)
	var i TaskRunRecord
	err := row.Scan(
		&i.ID,
		&i.TaskID,
		&i.PlacementID,
		&i.NodeID,
		&i.SessionID,
		&i.RunGeneration,
		&i.WorkflowRevisionSeen,
		&i.AutomationRequestedAtUnixMs,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
		&i.StartedAtUnixMs,
		&i.CompletedAtUnixMs,
		&i.InterruptedAtUnixMs,
		&i.InterruptionReason,
		&i.InterruptionDetailJson,
		&i.WaitingAskID,
		&i.EffectiveCompletionMode,
		&i.InvalidCompletionCount,
		&i.RunStartSnapshotJson,
		&i.MetadataJson,
	)
	return i, err
}

const getTaskTransitionState = `-- name: GetTaskTransitionState :one
SELECT state
FROM task_transitions
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetTaskTransitionState(ctx context.Context, transitionID string) (string, error) {
	row := q.db.QueryRowContext(ctx, getTaskTransitionState, transitionID)
	var state string
	err := row.Scan(&state)
	return state, err
}

const getTransitionApprovalState = `-- name: GetTransitionApprovalState :one
SELECT task_id, source_run_id, state, workflow_revision_seen, created_at_unix_ms
FROM task_transition_records
WHERE id = ?1
LIMIT 1
`

type GetTransitionApprovalStateRow struct {
	TaskID               string
	SourceRunID          sql.NullString
	State                string
	WorkflowRevisionSeen int64
	CreatedAtUnixMs      int64
}

func (q *Queries) GetTransitionApprovalState(ctx context.Context, transitionID string) (GetTransitionApprovalStateRow, error) {
	row := q.db.QueryRowContext(ctx, getTransitionApprovalState, transitionID)
	var i GetTransitionApprovalStateRow
	err := row.Scan(
		&i.TaskID,
		&i.SourceRunID,
		&i.State,
		&i.WorkflowRevisionSeen,
		&i.CreatedAtUnixMs,
	)
	return i, err
}

const getWorkflow = `-- name: GetWorkflow :one
SELECT
    id,
    name,
    description,
    version,
    created_at_unix_ms,
    updated_at_unix_ms
FROM workflows
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetWorkflow(ctx context.Context, id string) (Workflow, error) {
	row := q.db.QueryRowContext(ctx, getWorkflow, id)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.Name,
		&i.Description,
		&i.Version,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getWorkflowDeleteImpact = `-- name: GetWorkflowDeleteImpact :one
SELECT
    w.id AS workflow_id,
    w.version,
    CAST(COUNT(DISTINCT pwl.project_id) AS INTEGER) AS project_count,
    CAST(COUNT(DISTINCT pwl.id) AS INTEGER) AS link_count,
    CAST(COUNT(DISTINCT CASE
        WHEN p.default_project_workflow_link_id = pwl.id
          AND EXISTS (
              SELECT 1
              FROM project_workflow_links other
              WHERE other.project_id = pwl.project_id
                AND other.workflow_id != w.id
          )
        THEN pwl.project_id
    END) AS INTEGER) AS default_replacement_project_count,
    CAST(COUNT(DISTINCT t.id) AS INTEGER) AS task_count,
    CAST(COUNT(DISTINCT CASE
        WHEN r.started_at_unix_ms > 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND placement.state = 'active'
          AND n.kind IN ('agent', 'script')
        THEN r.id
    END) AS INTEGER) AS active_run_count,
    CAST(COUNT(DISTINCT CASE
        WHEN r.automation_requested_at_unix_ms > 0
          AND r.started_at_unix_ms = 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND r.waiting_ask_id = ''
          AND t.canceled_at_unix_ms = 0
          AND placement.state = 'active'
          AND n.kind IN ('agent', 'script')
        THEN r.id
    END) AS INTEGER) AS runnable_run_count,
    CAST(COUNT(DISTINCT CASE
        WHEN (
            r.started_at_unix_ms > 0
            AND r.completed_at_unix_ms = 0
            AND r.interrupted_at_unix_ms = 0
            AND placement.state = 'active'
            AND n.kind IN ('agent', 'script')
        )
        OR (
            r.automation_requested_at_unix_ms > 0
            AND r.started_at_unix_ms = 0
            AND r.completed_at_unix_ms = 0
            AND r.interrupted_at_unix_ms = 0
            AND r.waiting_ask_id = ''
            AND t.canceled_at_unix_ms = 0
            AND placement.state = 'active'
            AND n.kind IN ('agent', 'script')
        )
        THEN t.id
    END) AS INTEGER) AS blocked_task_count
FROM workflows w
LEFT JOIN project_workflow_links pwl ON pwl.workflow_id = w.id
LEFT JOIN projects p ON p.id = pwl.project_id
LEFT JOIN task_records t ON t.project_workflow_link_id = pwl.id
LEFT JOIN task_run_records r ON r.task_id = t.id
LEFT JOIN task_node_placements placement ON placement.id = r.placement_id
LEFT JOIN workflow_nodes n ON n.id = r.node_id
WHERE w.id = ?1
GROUP BY w.id, w.version
`

type GetWorkflowDeleteImpactRow struct {
	WorkflowID                     string
	Version                        int64
	ProjectCount                   int64
	LinkCount                      int64
	DefaultReplacementProjectCount int64
	TaskCount                      int64
	ActiveRunCount                 int64
	RunnableRunCount               int64
	BlockedTaskCount               int64
}

func (q *Queries) GetWorkflowDeleteImpact(ctx context.Context, workflowID string) (GetWorkflowDeleteImpactRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowDeleteImpact, workflowID)
	var i GetWorkflowDeleteImpactRow
	err := row.Scan(
		&i.WorkflowID,
		&i.Version,
		&i.ProjectCount,
		&i.LinkCount,
		&i.DefaultReplacementProjectCount,
		&i.TaskCount,
		&i.ActiveRunCount,
		&i.RunnableRunCount,
		&i.BlockedTaskCount,
	)
	return i, err
}

const getWorkflowEdge = `-- name: GetWorkflowEdge :one
SELECT
    e.id,
    source.workflow_id AS workflow_id,
    e.transition_group_id,
    e.edge_key,
    e.target_node_id,
    e.requires_approval,
    e.context_mode,
    e.context_source_kind,
    e.context_source_node_key,
    e.prompt_template,
    e.parameters_json,
    e.input_bindings_json,
    e.output_requirements_json,
    e.sort_order
FROM workflow_edges e
JOIN workflow_transition_groups tg ON tg.id = e.transition_group_id
JOIN workflow_nodes source ON source.id = tg.source_node_id
WHERE e.id = ?1
LIMIT 1
`

type GetWorkflowEdgeRow struct {
	ID                     string
	WorkflowID             string
	TransitionGroupID      string
	EdgeKey                string
	TargetNodeID           string
	RequiresApproval       int64
	ContextMode            string
	ContextSourceKind      string
	ContextSourceNodeKey   string
	PromptTemplate         string
	ParametersJson         string
	InputBindingsJson      string
	OutputRequirementsJson string
	SortOrder              int64
}

func (q *Queries) GetWorkflowEdge(ctx context.Context, id string) (GetWorkflowEdgeRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowEdge, id)
	var i GetWorkflowEdgeRow
	err := row.Scan(
		&i.ID,
		&i.WorkflowID,
		&i.TransitionGroupID,
		&i.EdgeKey,
		&i.TargetNodeID,
		&i.RequiresApproval,
		&i.ContextMode,
		&i.ContextSourceKind,
		&i.ContextSourceNodeKey,
		&i.PromptTemplate,
		&i.ParametersJson,
		&i.InputBindingsJson,
		&i.OutputRequirementsJson,
		&i.SortOrder,
	)
	return i, err
}

const getWorkflowGraphActiveWorkPolicyImpact = `-- name: GetWorkflowGraphActiveWorkPolicyImpact :one
SELECT
    (
        SELECT CAST(COUNT(DISTINCT p.id) AS INTEGER)
        FROM task_records t
        JOIN task_node_placements p ON p.task_id = t.id AND p.state IN ('active', 'waiting_approval')
        JOIN workflow_nodes n ON n.id = p.node_id
        WHERE t.workflow_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND n.kind NOT IN ('start', 'terminal')
          AND NOT EXISTS (
              SELECT 1
              FROM task_run_records interrupted
              WHERE interrupted.placement_id = p.id
                AND interrupted.completed_at_unix_ms = 0
                AND interrupted.interrupted_at_unix_ms > 0
          )
    ) AS active_node_placement_count,
    (
        SELECT CAST(COUNT(DISTINCT tt.id) AS INTEGER)
        FROM task_transition_records tt
        JOIN task_records t ON t.id = tt.task_id
        WHERE t.workflow_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND tt.state = 'pending_approval'
    ) AS pending_approval_count,
    (
        SELECT CAST(COUNT(DISTINCT r.id) AS INTEGER)
        FROM task_run_records r
        JOIN task_records t ON t.id = r.task_id
        JOIN task_node_placements p ON p.id = r.placement_id
        JOIN workflow_nodes n ON n.id = r.node_id
        WHERE t.workflow_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND r.started_at_unix_ms > 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND p.state = 'active'
          AND n.kind IN ('agent', 'script')
    ) AS active_run_count,
    (
        SELECT CAST(COUNT(DISTINCT r.id) AS INTEGER)
        FROM task_run_records r
        JOIN task_records t ON t.id = r.task_id
        JOIN task_node_placements p ON p.id = r.placement_id
        JOIN workflow_nodes n ON n.id = r.node_id
        WHERE t.workflow_id = ?1
          AND t.canceled_at_unix_ms = 0
          AND r.automation_requested_at_unix_ms > 0
          AND r.started_at_unix_ms = 0
          AND r.completed_at_unix_ms = 0
          AND r.interrupted_at_unix_ms = 0
          AND r.waiting_ask_id = ''
          AND p.state = 'active'
          AND n.kind IN ('agent', 'script')
    ) AS runnable_run_count
`

type GetWorkflowGraphActiveWorkPolicyImpactRow struct {
	ActiveNodePlacementCount int64
	PendingApprovalCount     int64
	ActiveRunCount           int64
	RunnableRunCount         int64
}

func (q *Queries) GetWorkflowGraphActiveWorkPolicyImpact(ctx context.Context, workflowID string) (GetWorkflowGraphActiveWorkPolicyImpactRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowGraphActiveWorkPolicyImpact, workflowID)
	var i GetWorkflowGraphActiveWorkPolicyImpactRow
	err := row.Scan(
		&i.ActiveNodePlacementCount,
		&i.PendingApprovalCount,
		&i.ActiveRunCount,
		&i.RunnableRunCount,
	)
	return i, err
}

const getWorkflowNode = `-- name: GetWorkflowNode :one
SELECT
    id,
    workflow_id,
    node_key,
    kind,
    display_name,
    subagent_role,
    prompt_template,
    completion_mode,
    script_path,
    input_fields_json,
    join_input_providers_json,
    output_fields_json,
    group_id,
    sort_order
FROM workflow_nodes
WHERE id = ?1
LIMIT 1
`

type GetWorkflowNodeRow struct {
	ID                     string
	WorkflowID             string
	NodeKey                string
	Kind                   string
	DisplayName            string
	SubagentRole           string
	PromptTemplate         string
	CompletionMode         string
	ScriptPath             sql.NullString
	InputFieldsJson        string
	JoinInputProvidersJson string
	OutputFieldsJson       string
	GroupID                sql.NullString
	SortOrder              int64
}

func (q *Queries) GetWorkflowNode(ctx context.Context, id string) (GetWorkflowNodeRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowNode, id)
	var i GetWorkflowNodeRow
	err := row.Scan(
		&i.ID,
		&i.WorkflowID,
		&i.NodeKey,
		&i.Kind,
		&i.DisplayName,
		&i.SubagentRole,
		&i.PromptTemplate,
		&i.CompletionMode,
		&i.ScriptPath,
		&i.InputFieldsJson,
		&i.JoinInputProvidersJson,
		&i.OutputFieldsJson,
		&i.GroupID,
		&i.SortOrder,
	)
	return i, err
}

const getWorkflowNodeGroupByID = `-- name: GetWorkflowNodeGroupByID :one
SELECT
    id,
    workflow_id,
    group_key,
    display_name,
    sort_order
FROM workflow_node_groups
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetWorkflowNodeGroupByID(ctx context.Context, id string) (WorkflowNodeGroup, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowNodeGroupByID, id)
	var i WorkflowNodeGroup
	err := row.Scan(
		&i.ID,
		&i.WorkflowID,
		&i.GroupKey,
		&i.DisplayName,
		&i.SortOrder,
	)
	return i, err
}

const getWorkflowNodeGroupByKey = `-- name: GetWorkflowNodeGroupByKey :one
SELECT
    id,
    workflow_id,
    group_key,
    display_name,
    sort_order
FROM workflow_node_groups
WHERE workflow_id = ?1
  AND group_key = ?2
LIMIT 1
`

type GetWorkflowNodeGroupByKeyParams struct {
	WorkflowID string
	GroupKey   string
}

func (q *Queries) GetWorkflowNodeGroupByKey(ctx context.Context, arg GetWorkflowNodeGroupByKeyParams) (WorkflowNodeGroup, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowNodeGroupByKey, arg.WorkflowID, arg.GroupKey)
	var i WorkflowNodeGroup
	err := row.Scan(
		&i.ID,
		&i.WorkflowID,
		&i.GroupKey,
		&i.DisplayName,
		&i.SortOrder,
	)
	return i, err
}

const getWorkflowTransitionGroupWorkflowID = `-- name: GetWorkflowTransitionGroupWorkflowID :one
SELECT source.workflow_id
FROM workflow_transition_groups tg
JOIN workflow_nodes source ON source.id = tg.source_node_id
WHERE tg.id = ?1
LIMIT 1
`

func (q *Queries) GetWorkflowTransitionGroupWorkflowID(ctx context.Context, id string) (string, error) {
	row := q.db.QueryRowContext(ctx, getWorkflowTransitionGroupWorkflowID, id)
	var workflow_id string
	err := row.Scan(&workflow_id)
	return workflow_id, err
}

const getWorkspaceBindingByID = `-- name: GetWorkspaceBindingByID :one
SELECT
    p.id AS project_id,
    p.display_name AS project_display_name,
    p.project_key,
    w.id AS workspace_id,
    w.canonical_root_path AS workspace_root
FROM workspaces w
JOIN projects p ON p.id = w.project_id
WHERE w.id = ?1
LIMIT 1
`

type GetWorkspaceBindingByIDRow struct {
	ProjectID          string
	ProjectDisplayName string
	ProjectKey         string
	WorkspaceID        string
	WorkspaceRoot      string
}

func (q *Queries) GetWorkspaceBindingByID(ctx context.Context, workspaceID string) (GetWorkspaceBindingByIDRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkspaceBindingByID, workspaceID)
	var i GetWorkspaceBindingByIDRow
	err := row.Scan(
		&i.ProjectID,
		&i.ProjectDisplayName,
		&i.ProjectKey,
		&i.WorkspaceID,
		&i.WorkspaceRoot,
	)
	return i, err
}

const getWorkspaceBindingByProjectAndCanonicalRoot = `-- name: GetWorkspaceBindingByProjectAndCanonicalRoot :one
SELECT
    p.id AS project_id,
    p.display_name AS project_display_name,
    p.project_key,
    w.id AS workspace_id,
    w.canonical_root_path AS workspace_root
FROM workspaces w
JOIN projects p ON p.id = w.project_id
WHERE w.project_id = ?1
  AND w.canonical_root_path = ?2
LIMIT 1
`

type GetWorkspaceBindingByProjectAndCanonicalRootParams struct {
	ProjectID         string
	CanonicalRootPath string
}

type GetWorkspaceBindingByProjectAndCanonicalRootRow struct {
	ProjectID          string
	ProjectDisplayName string
	ProjectKey         string
	WorkspaceID        string
	WorkspaceRoot      string
}

func (q *Queries) GetWorkspaceBindingByProjectAndCanonicalRoot(ctx context.Context, arg GetWorkspaceBindingByProjectAndCanonicalRootParams) (GetWorkspaceBindingByProjectAndCanonicalRootRow, error) {
	row := q.db.QueryRowContext(ctx, getWorkspaceBindingByProjectAndCanonicalRoot, arg.ProjectID, arg.CanonicalRootPath)
	var i GetWorkspaceBindingByProjectAndCanonicalRootRow
	err := row.Scan(
		&i.ProjectID,
		&i.ProjectDisplayName,
		&i.ProjectKey,
		&i.WorkspaceID,
		&i.WorkspaceRoot,
	)
	return i, err
}

const getWorkspaceByID = `-- name: GetWorkspaceByID :one
SELECT
    id,
    project_id,
    canonical_root_path,
    git_metadata_json,
    created_at_unix_ms,
    updated_at_unix_ms
FROM workspaces
WHERE id = ?1
LIMIT 1
`

func (q *Queries) GetWorkspaceByID(ctx context.Context, id string) (Workspace, error) {
	row := q.db.QueryRowContext(ctx, getWorkspaceByID, id)
	var i Workspace
	err := row.Scan(
		&i.ID,
		&i.ProjectID,
		&i.CanonicalRootPath,
		&i.GitMetadataJson,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getWorktreeByCanonicalRoot = `-- name: GetWorktreeByCanonicalRoot :one
SELECT
    wt.id,
    wt.workspace_id,
    wt.canonical_root_path,
    CASE WHEN wt.canonical_root_path = w.canonical_root_path THEN 1 ELSE 0 END AS is_main,
    wt.managed,
    wt.created_branch,
    wt.origin_session_id,
    wt.git_metadata_json,
    wt.created_at_unix_ms,
    wt.updated_at_unix_ms
FROM worktrees wt
JOIN workspaces w ON w.id = wt.workspace_id
WHERE wt.canonical_root_path = ?1
LIMIT 1
`

type GetWorktreeByCanonicalRootRow struct {
	ID                string
	WorkspaceID       string
	CanonicalRootPath string
	IsMain            int64
	Managed           int64
	CreatedBranch     int64
	OriginSessionID   string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) GetWorktreeByCanonicalRoot(ctx context.Context, canonicalRootPath string) (GetWorktreeByCanonicalRootRow, error) {
	row := q.db.QueryRowContext(ctx, getWorktreeByCanonicalRoot, canonicalRootPath)
	var i GetWorktreeByCanonicalRootRow
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.CanonicalRootPath,
		&i.IsMain,
		&i.Managed,
		&i.CreatedBranch,
		&i.OriginSessionID,
		&i.GitMetadataJson,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const getWorktreeByID = `-- name: GetWorktreeByID :one
SELECT
    wt.id,
    wt.workspace_id,
    wt.canonical_root_path,
    CASE WHEN wt.canonical_root_path = w.canonical_root_path THEN 1 ELSE 0 END AS is_main,
    wt.managed,
    wt.created_branch,
    wt.origin_session_id,
    wt.git_metadata_json,
    wt.created_at_unix_ms,
    wt.updated_at_unix_ms
FROM worktrees wt
JOIN workspaces w ON w.id = wt.workspace_id
WHERE wt.id = ?1
LIMIT 1
`

type GetWorktreeByIDRow struct {
	ID                string
	WorkspaceID       string
	CanonicalRootPath string
	IsMain            int64
	Managed           int64
	CreatedBranch     int64
	OriginSessionID   string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) GetWorktreeByID(ctx context.Context, id string) (GetWorktreeByIDRow, error) {
	row := q.db.QueryRowContext(ctx, getWorktreeByID, id)
	var i GetWorktreeByIDRow
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.CanonicalRootPath,
		&i.IsMain,
		&i.Managed,
		&i.CreatedBranch,
		&i.OriginSessionID,
		&i.GitMetadataJson,
		&i.CreatedAtUnixMs,
		&i.UpdatedAtUnixMs,
	)
	return i, err
}

const incrementWorkflowVersion = `-- name: IncrementWorkflowVersion :one
UPDATE workflows
SET
    version = version + 1,
    updated_at_unix_ms = ?1
WHERE id = ?2
RETURNING version
`

type IncrementWorkflowVersionParams struct {
	UpdatedAtUnixMs int64
	ID              string
}

func (q *Queries) IncrementWorkflowVersion(ctx context.Context, arg IncrementWorkflowVersionParams) (int64, error) {
	row := q.db.QueryRowContext(ctx, incrementWorkflowVersion, arg.UpdatedAtUnixMs, arg.ID)
	var version int64
	err := row.Scan(&version)
	return version, err
}

const insertProjectWorkflowLink = `-- name: InsertProjectWorkflowLink :exec
INSERT INTO project_workflow_links (
    id,
    project_id,
    workflow_id,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5
)
`

type InsertProjectWorkflowLinkParams struct {
	ID              string
	ProjectID       string
	WorkflowID      string
	CreatedAtUnixMs int64
	UpdatedAtUnixMs int64
}

func (q *Queries) InsertProjectWorkflowLink(ctx context.Context, arg InsertProjectWorkflowLinkParams) error {
	_, err := q.db.ExecContext(ctx, insertProjectWorkflowLink,
		arg.ID,
		arg.ProjectID,
		arg.WorkflowID,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const insertSessionPromptHistoryEntry = `-- name: InsertSessionPromptHistoryEntry :execrows
INSERT INTO session_prompt_history_entries (
    session_id,
    source_id,
    text,
    created_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4
)
ON CONFLICT DO NOTHING
`

type InsertSessionPromptHistoryEntryParams struct {
	SessionID       string
	SourceID        string
	Text            string
	CreatedAtUnixMs int64
}

func (q *Queries) InsertSessionPromptHistoryEntry(ctx context.Context, arg InsertSessionPromptHistoryEntryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, insertSessionPromptHistoryEntry,
		arg.SessionID,
		arg.SourceID,
		arg.Text,
		arg.CreatedAtUnixMs,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const insertTask = `-- name: InsertTask :exec
INSERT INTO tasks (
    id,
    project_workflow_link_id,
    workflow_revision_seen,
    task_seq,
    short_id,
    title,
    body,
    source_url,
    source_workspace_id,
    managed_worktree_id,
    canceled_at_unix_ms,
    cancellation_reason,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    0,
    '',
    ?11,
    ?12,
    ?13
)
`

type InsertTaskParams struct {
	ID                    string
	ProjectWorkflowLinkID string
	WorkflowRevisionSeen  int64
	TaskSeq               int64
	ShortID               string
	Title                 string
	Body                  string
	SourceUrl             string
	SourceWorkspaceID     sql.NullString
	ManagedWorktreeID     sql.NullString
	CreatedAtUnixMs       int64
	UpdatedAtUnixMs       int64
	MetadataJson          string
}

func (q *Queries) InsertTask(ctx context.Context, arg InsertTaskParams) error {
	_, err := q.db.ExecContext(ctx, insertTask,
		arg.ID,
		arg.ProjectWorkflowLinkID,
		arg.WorkflowRevisionSeen,
		arg.TaskSeq,
		arg.ShortID,
		arg.Title,
		arg.Body,
		arg.SourceUrl,
		arg.SourceWorkspaceID,
		arg.ManagedWorktreeID,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
		arg.MetadataJson,
	)
	return err
}

const insertTaskComment = `-- name: InsertTaskComment :exec
INSERT INTO task_comments (
    id,
    task_id,
    body,
    author_kind,
    author_id,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7
)
`

type InsertTaskCommentParams struct {
	ID              string
	TaskID          string
	Body            string
	AuthorKind      string
	AuthorID        string
	CreatedAtUnixMs int64
	UpdatedAtUnixMs int64
}

func (q *Queries) InsertTaskComment(ctx context.Context, arg InsertTaskCommentParams) error {
	_, err := q.db.ExecContext(ctx, insertTaskComment,
		arg.ID,
		arg.TaskID,
		arg.Body,
		arg.AuthorKind,
		arg.AuthorID,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const insertTaskNodePlacement = `-- name: InsertTaskNodePlacement :exec
INSERT INTO task_node_placements (
    id,
    task_id,
    node_id,
    state,
    parallel_batch_transition_id,
    parallel_branch_edge_id,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8
)
`

type InsertTaskNodePlacementParams struct {
	ID                        string
	TaskID                    string
	NodeID                    sql.NullString
	State                     string
	ParallelBatchTransitionID sql.NullString
	ParallelBranchEdgeID      sql.NullString
	CreatedAtUnixMs           int64
	UpdatedAtUnixMs           int64
}

func (q *Queries) InsertTaskNodePlacement(ctx context.Context, arg InsertTaskNodePlacementParams) error {
	_, err := q.db.ExecContext(ctx, insertTaskNodePlacement,
		arg.ID,
		arg.TaskID,
		arg.NodeID,
		arg.State,
		arg.ParallelBatchTransitionID,
		arg.ParallelBranchEdgeID,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const insertTaskRun = `-- name: InsertTaskRun :exec
INSERT INTO task_runs (
    id,
    placement_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14,
    ?15,
    ?16,
    ?17
)
`

type InsertTaskRunParams struct {
	ID                          string
	PlacementID                 string
	SessionID                   sql.NullString
	RunGeneration               int64
	WorkflowRevisionSeen        int64
	AutomationRequestedAtUnixMs int64
	CreatedAtUnixMs             int64
	UpdatedAtUnixMs             int64
	StartedAtUnixMs             int64
	CompletedAtUnixMs           int64
	InterruptedAtUnixMs         int64
	InterruptionReason          string
	InterruptionDetailJson      string
	WaitingAskID                string
	InvalidCompletionCount      int64
	RunStartSnapshotJson        string
	MetadataJson                string
}

func (q *Queries) InsertTaskRun(ctx context.Context, arg InsertTaskRunParams) error {
	_, err := q.db.ExecContext(ctx, insertTaskRun,
		arg.ID,
		arg.PlacementID,
		arg.SessionID,
		arg.RunGeneration,
		arg.WorkflowRevisionSeen,
		arg.AutomationRequestedAtUnixMs,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
		arg.StartedAtUnixMs,
		arg.CompletedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
		arg.WaitingAskID,
		arg.InvalidCompletionCount,
		arg.RunStartSnapshotJson,
		arg.MetadataJson,
	)
	return err
}

const insertTaskTransition = `-- name: InsertTaskTransition :exec
INSERT INTO task_transitions (
    id,
    task_id,
    source_run_id,
    source_placement_id,
    source_node_key,
    source_node_display_name,
    transition_id,
    transition_display_name,
    workflow_revision_seen,
    actor,
    state,
    commentary,
    output_values_json,
    created_at_unix_ms,
    applied_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14,
    ?15
)
`

type InsertTaskTransitionParams struct {
	ID                    string
	TaskID                string
	SourceRunID           sql.NullString
	SourcePlacementID     sql.NullString
	SourceNodeKey         string
	SourceNodeDisplayName string
	TransitionID          string
	TransitionDisplayName string
	WorkflowRevisionSeen  int64
	Actor                 string
	State                 string
	Commentary            string
	OutputValuesJson      string
	CreatedAtUnixMs       int64
	AppliedAtUnixMs       int64
}

func (q *Queries) InsertTaskTransition(ctx context.Context, arg InsertTaskTransitionParams) error {
	_, err := q.db.ExecContext(ctx, insertTaskTransition,
		arg.ID,
		arg.TaskID,
		arg.SourceRunID,
		arg.SourcePlacementID,
		arg.SourceNodeKey,
		arg.SourceNodeDisplayName,
		arg.TransitionID,
		arg.TransitionDisplayName,
		arg.WorkflowRevisionSeen,
		arg.Actor,
		arg.State,
		arg.Commentary,
		arg.OutputValuesJson,
		arg.CreatedAtUnixMs,
		arg.AppliedAtUnixMs,
	)
	return err
}

const insertTaskTransitionEdge = `-- name: InsertTaskTransitionEdge :exec
INSERT INTO task_transition_edges (
    id,
    task_transition_id,
    workflow_edge_id,
    edge_key,
    target_node_id,
    target_node_key,
    target_node_display_name,
    target_node_kind,
    target_placement_id,
    state,
    context_mode,
    requires_approval,
    input_bindings_json,
    output_requirements_json,
    metadata_json
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14,
    ?15
)
`

type InsertTaskTransitionEdgeParams struct {
	ID                     string
	TaskTransitionID       string
	WorkflowEdgeID         sql.NullString
	EdgeKey                string
	TargetNodeID           sql.NullString
	TargetNodeKey          string
	TargetNodeDisplayName  string
	TargetNodeKind         string
	TargetPlacementID      sql.NullString
	State                  string
	ContextMode            string
	RequiresApproval       int64
	InputBindingsJson      string
	OutputRequirementsJson string
	MetadataJson           string
}

func (q *Queries) InsertTaskTransitionEdge(ctx context.Context, arg InsertTaskTransitionEdgeParams) error {
	_, err := q.db.ExecContext(ctx, insertTaskTransitionEdge,
		arg.ID,
		arg.TaskTransitionID,
		arg.WorkflowEdgeID,
		arg.EdgeKey,
		arg.TargetNodeID,
		arg.TargetNodeKey,
		arg.TargetNodeDisplayName,
		arg.TargetNodeKind,
		arg.TargetPlacementID,
		arg.State,
		arg.ContextMode,
		arg.RequiresApproval,
		arg.InputBindingsJson,
		arg.OutputRequirementsJson,
		arg.MetadataJson,
	)
	return err
}

const insertWorkflow = `-- name: InsertWorkflow :exec
INSERT INTO workflows (
    id,
    name,
    description,
    version,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6
)
`

type InsertWorkflowParams struct {
	ID              string
	Name            string
	Description     string
	Version         int64
	CreatedAtUnixMs int64
	UpdatedAtUnixMs int64
}

func (q *Queries) InsertWorkflow(ctx context.Context, arg InsertWorkflowParams) error {
	_, err := q.db.ExecContext(ctx, insertWorkflow,
		arg.ID,
		arg.Name,
		arg.Description,
		arg.Version,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const insertWorkflowEdge = `-- name: InsertWorkflowEdge :exec
INSERT INTO workflow_edges (
    id,
    transition_group_id,
    edge_key,
    target_node_id,
    requires_approval,
    context_mode,
    context_source_kind,
    context_source_node_key,
    prompt_template,
    parameters_json,
    input_bindings_json,
    output_requirements_json,
    sort_order
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13
)
`

type InsertWorkflowEdgeParams struct {
	ID                     string
	TransitionGroupID      string
	EdgeKey                string
	TargetNodeID           string
	RequiresApproval       int64
	ContextMode            string
	ContextSourceKind      string
	ContextSourceNodeKey   string
	PromptTemplate         string
	ParametersJson         string
	InputBindingsJson      string
	OutputRequirementsJson string
	SortOrder              int64
}

func (q *Queries) InsertWorkflowEdge(ctx context.Context, arg InsertWorkflowEdgeParams) error {
	_, err := q.db.ExecContext(ctx, insertWorkflowEdge,
		arg.ID,
		arg.TransitionGroupID,
		arg.EdgeKey,
		arg.TargetNodeID,
		arg.RequiresApproval,
		arg.ContextMode,
		arg.ContextSourceKind,
		arg.ContextSourceNodeKey,
		arg.PromptTemplate,
		arg.ParametersJson,
		arg.InputBindingsJson,
		arg.OutputRequirementsJson,
		arg.SortOrder,
	)
	return err
}

const insertWorkflowNode = `-- name: InsertWorkflowNode :exec
INSERT INTO workflow_nodes (
    id,
    workflow_id,
    node_key,
    kind,
    display_name,
    subagent_role,
    prompt_template,
    completion_mode,
    script_path,
    input_fields_json,
    join_input_providers_json,
    output_fields_json,
    group_id,
    sort_order
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14
)
`

type InsertWorkflowNodeParams struct {
	ID                     string
	WorkflowID             string
	NodeKey                string
	Kind                   string
	DisplayName            string
	SubagentRole           string
	PromptTemplate         string
	CompletionMode         string
	ScriptPath             sql.NullString
	InputFieldsJson        string
	JoinInputProvidersJson string
	OutputFieldsJson       string
	GroupID                sql.NullString
	SortOrder              int64
}

func (q *Queries) InsertWorkflowNode(ctx context.Context, arg InsertWorkflowNodeParams) error {
	_, err := q.db.ExecContext(ctx, insertWorkflowNode,
		arg.ID,
		arg.WorkflowID,
		arg.NodeKey,
		arg.Kind,
		arg.DisplayName,
		arg.SubagentRole,
		arg.PromptTemplate,
		arg.CompletionMode,
		arg.ScriptPath,
		arg.InputFieldsJson,
		arg.JoinInputProvidersJson,
		arg.OutputFieldsJson,
		arg.GroupID,
		arg.SortOrder,
	)
	return err
}

const insertWorkflowNodeGroup = `-- name: InsertWorkflowNodeGroup :exec
INSERT INTO workflow_node_groups (
    id,
    workflow_id,
    group_key,
    display_name,
    sort_order
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5
)
`

type InsertWorkflowNodeGroupParams struct {
	ID          string
	WorkflowID  string
	GroupKey    string
	DisplayName string
	SortOrder   int64
}

func (q *Queries) InsertWorkflowNodeGroup(ctx context.Context, arg InsertWorkflowNodeGroupParams) error {
	_, err := q.db.ExecContext(ctx, insertWorkflowNodeGroup,
		arg.ID,
		arg.WorkflowID,
		arg.GroupKey,
		arg.DisplayName,
		arg.SortOrder,
	)
	return err
}

const insertWorkflowTransitionGroup = `-- name: InsertWorkflowTransitionGroup :exec
INSERT INTO workflow_transition_groups (
    id,
    source_node_id,
    transition_id,
    display_name,
    description,
    sort_order
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6
)
`

type InsertWorkflowTransitionGroupParams struct {
	ID           string
	SourceNodeID string
	TransitionID string
	DisplayName  string
	Description  string
	SortOrder    int64
}

func (q *Queries) InsertWorkflowTransitionGroup(ctx context.Context, arg InsertWorkflowTransitionGroupParams) error {
	_, err := q.db.ExecContext(ctx, insertWorkflowTransitionGroup,
		arg.ID,
		arg.SourceNodeID,
		arg.TransitionID,
		arg.DisplayName,
		arg.Description,
		arg.SortOrder,
	)
	return err
}

const insertWorkspaceBinding = `-- name: InsertWorkspaceBinding :execrows
INSERT INTO workspaces (
    id,
    project_id,
    canonical_root_path,
    git_metadata_json,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6
)
ON CONFLICT(project_id, canonical_root_path) DO NOTHING
`

type InsertWorkspaceBindingParams struct {
	ID                string
	ProjectID         string
	CanonicalRootPath string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) InsertWorkspaceBinding(ctx context.Context, arg InsertWorkspaceBindingParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, insertWorkspaceBinding,
		arg.ID,
		arg.ProjectID,
		arg.CanonicalRootPath,
		arg.GitMetadataJson,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const interruptActiveTaskRuns = `-- name: InterruptActiveTaskRuns :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    interrupted_at_unix_ms = ?2,
    interruption_reason = ?3,
    interruption_detail_json = ?4,
    waiting_ask_id = ''
WHERE EXISTS (
      SELECT 1
      FROM task_node_placements p
      WHERE p.id = task_runs.placement_id
        AND p.task_id = ?5
  )
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
`

type InterruptActiveTaskRunsParams struct {
	UpdatedAtUnixMs        int64
	InterruptedAtUnixMs    int64
	InterruptionReason     string
	InterruptionDetailJson string
	TaskID                 string
}

func (q *Queries) InterruptActiveTaskRuns(ctx context.Context, arg InterruptActiveTaskRunsParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, interruptActiveTaskRuns,
		arg.UpdatedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
		arg.TaskID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const interruptRunGeneration = `-- name: InterruptRunGeneration :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    interrupted_at_unix_ms = ?2,
    interruption_reason = ?3,
    interruption_detail_json = ?4,
    waiting_ask_id = ''
WHERE id = ?5
  AND run_generation = ?6
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
`

type InterruptRunGenerationParams struct {
	UpdatedAtUnixMs        int64
	InterruptedAtUnixMs    int64
	InterruptionReason     string
	InterruptionDetailJson string
	RunID                  string
	RunGeneration          int64
}

func (q *Queries) InterruptRunGeneration(ctx context.Context, arg InterruptRunGenerationParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, interruptRunGeneration,
		arg.UpdatedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
		arg.RunID,
		arg.RunGeneration,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const interruptStartedWorkflowRunsForRecovery = `-- name: InterruptStartedWorkflowRunsForRecovery :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    interrupted_at_unix_ms = ?2,
    interruption_reason = ?3,
    interruption_detail_json = ?4
WHERE started_at_unix_ms > 0
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND waiting_ask_id = ''
`

type InterruptStartedWorkflowRunsForRecoveryParams struct {
	UpdatedAtUnixMs        int64
	InterruptedAtUnixMs    int64
	InterruptionReason     string
	InterruptionDetailJson string
}

func (q *Queries) InterruptStartedWorkflowRunsForRecovery(ctx context.Context, arg InterruptStartedWorkflowRunsForRecoveryParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, interruptStartedWorkflowRunsForRecovery,
		arg.UpdatedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const interruptWorkflowRun = `-- name: InterruptWorkflowRun :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    interrupted_at_unix_ms = ?2,
    interruption_reason = ?3,
    interruption_detail_json = ?4,
    waiting_ask_id = ''
WHERE id = ?5
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
`

type InterruptWorkflowRunParams struct {
	UpdatedAtUnixMs        int64
	InterruptedAtUnixMs    int64
	InterruptionReason     string
	InterruptionDetailJson string
	ID                     string
}

func (q *Queries) InterruptWorkflowRun(ctx context.Context, arg InterruptWorkflowRunParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, interruptWorkflowRun,
		arg.UpdatedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const listActiveManualMoveSources = `-- name: ListActiveManualMoveSources :many
SELECT task_node_placements.id, node_id, parallel_batch_transition_id
FROM task_node_placements
LEFT JOIN workflow_nodes n ON n.id = task_node_placements.node_id
WHERE task_node_placements.task_id = ?1
  AND (
      task_node_placements.state = 'active'
      OR (task_node_placements.state = 'completed' AND n.kind = 'terminal')
  )
ORDER BY task_node_placements.created_at_unix_ms DESC, task_node_placements.rowid DESC
`

type ListActiveManualMoveSourcesRow struct {
	ID                        string
	NodeID                    sql.NullString
	ParallelBatchTransitionID sql.NullString
}

func (q *Queries) ListActiveManualMoveSources(ctx context.Context, taskID string) ([]ListActiveManualMoveSourcesRow, error) {
	rows, err := q.db.QueryContext(ctx, listActiveManualMoveSources, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListActiveManualMoveSourcesRow
	for rows.Next() {
		var i ListActiveManualMoveSourcesRow
		if err := rows.Scan(&i.ID, &i.NodeID, &i.ParallelBatchTransitionID); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listBoardColumnTaskCounts = `-- name: ListBoardColumnTaskCounts :many
WITH effective_board_placements AS (
    SELECT
        t.id AS task_id,
        p.node_id AS node_id
    FROM task_node_placements p
    JOIN task_records t ON t.id = p.task_id
    JOIN workflow_nodes n ON n.id = p.node_id
    WHERE (
          (p.state IN ('active', 'waiting_approval') AND n.kind != 'terminal')
          OR (p.state = 'completed' AND n.kind = 'terminal')
      )
      AND t.project_id = ?1
      AND t.workflow_id = ?2
      AND (
          t.canceled_at_unix_ms = 0
          OR n.kind = 'terminal'
          OR trim(?3) = ''
      )
    UNION
    SELECT
        t.id AS task_id,
        ?3 AS node_id
    FROM task_records t
    WHERE t.project_id = ?1
      AND t.workflow_id = ?2
      AND t.canceled_at_unix_ms != 0
      AND trim(?3) != ''
      AND NOT EXISTS (
          SELECT 1
          FROM task_node_placements p
          JOIN workflow_nodes n ON n.id = p.node_id
          WHERE p.task_id = t.id
            AND p.state = 'completed'
            AND n.kind = 'terminal'
      )
    UNION
    SELECT
        t.id AS task_id,
        tt.source_node_id AS node_id
    FROM task_transition_records tt
    JOIN task_records t ON t.id = tt.task_id
    WHERE tt.state = 'pending_approval'
      AND t.project_id = ?1
      AND t.workflow_id = ?2
      AND (
          t.canceled_at_unix_ms = 0
          OR trim(?3) = ''
      )
      AND trim(tt.source_node_id) != ''
)
SELECT
    node_id,
    CAST(COUNT(DISTINCT task_id) AS INTEGER) AS task_count
FROM effective_board_placements
GROUP BY node_id
ORDER BY node_id ASC
`

type ListBoardColumnTaskCountsParams struct {
	ProjectID              string
	WorkflowID             string
	CanceledTerminalNodeID string
}

type ListBoardColumnTaskCountsRow struct {
	NodeID    sql.NullString
	TaskCount int64
}

func (q *Queries) ListBoardColumnTaskCounts(ctx context.Context, arg ListBoardColumnTaskCountsParams) ([]ListBoardColumnTaskCountsRow, error) {
	rows, err := q.db.QueryContext(ctx, listBoardColumnTaskCounts, arg.ProjectID, arg.WorkflowID, arg.CanceledTerminalNodeID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListBoardColumnTaskCountsRow
	for rows.Next() {
		var i ListBoardColumnTaskCountsRow
		if err := rows.Scan(&i.NodeID, &i.TaskCount); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listBoardDonePreviewTasks = `-- name: ListBoardDonePreviewTasks :many
SELECT
    t.id,
    t.project_id,
    t.project_workflow_link_id,
    t.workflow_id,
    t.workflow_revision_seen,
    t.task_seq,
    t.short_id,
    t.title,
    t.body,
    t.source_url,
    t.source_workspace_id,
    t.managed_worktree_id,
    t.canceled_at_unix_ms,
    t.cancellation_reason,
    t.created_at_unix_ms,
    t.updated_at_unix_ms,
    t.metadata_json
FROM task_records t
WHERE t.project_id = ?1
  AND t.workflow_id = ?2
  AND (
      EXISTS (
          SELECT 1
          FROM task_node_placements p
          JOIN workflow_nodes n ON n.id = p.node_id
          WHERE p.task_id = t.id
            AND p.state = 'completed'
            AND n.kind = 'terminal'
      )
      OR (
          t.canceled_at_unix_ms != 0
          AND trim(?3) != ''
      )
  )
ORDER BY t.updated_at_unix_ms DESC, t.id DESC
LIMIT ?4
`

type ListBoardDonePreviewTasksParams struct {
	ProjectID              string
	WorkflowID             string
	CanceledTerminalNodeID string
	LimitRows              int64
}

func (q *Queries) ListBoardDonePreviewTasks(ctx context.Context, arg ListBoardDonePreviewTasksParams) ([]TaskRecord, error) {
	rows, err := q.db.QueryContext(ctx, listBoardDonePreviewTasks,
		arg.ProjectID,
		arg.WorkflowID,
		arg.CanceledTerminalNodeID,
		arg.LimitRows,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRecord
	for rows.Next() {
		var i TaskRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listBoardNodeTasks = `-- name: ListBoardNodeTasks :many
WITH board_node_task_ids AS (
    SELECT
        t.id
    FROM task_node_placements p
    JOIN task_records t ON t.id = p.task_id
    JOIN workflow_nodes n ON n.id = p.node_id
    WHERE p.node_id = ?5
      AND (
        (p.state IN ('active', 'waiting_approval') AND n.kind != 'terminal')
        OR (p.state = 'completed' AND n.kind = 'terminal')
      )
      AND t.project_id = ?6
      AND t.workflow_id = ?7
      AND (
        t.canceled_at_unix_ms = 0
        OR n.kind = 'terminal'
      )
    UNION
    SELECT
        t.id
    FROM task_transition_records tt
    JOIN task_records t ON t.id = tt.task_id
    WHERE tt.source_node_id = ?5
      AND tt.state = 'pending_approval'
      AND t.project_id = ?6
      AND t.workflow_id = ?7
      AND t.canceled_at_unix_ms = 0
    UNION
    SELECT
        t.id
    FROM task_records t
    WHERE t.project_id = ?6
      AND t.workflow_id = ?7
      AND t.canceled_at_unix_ms != 0
      AND ?5 = ?8
      AND EXISTS (
        SELECT 1
        FROM workflow_nodes n
        WHERE n.id = ?5
          AND n.kind = 'terminal'
      )
      AND NOT EXISTS (
        SELECT 1
        FROM task_node_placements p
        JOIN workflow_nodes n ON n.id = p.node_id
        WHERE p.task_id = t.id
          AND p.state = 'completed'
          AND n.kind = 'terminal'
      )
)
SELECT
    t.id,
    t.project_id,
    t.project_workflow_link_id,
    t.workflow_id,
    t.workflow_revision_seen,
    t.task_seq,
    t.short_id,
    t.title,
    t.body,
    t.source_url,
    t.source_workspace_id,
    t.managed_worktree_id,
    t.canceled_at_unix_ms,
    t.cancellation_reason,
    t.created_at_unix_ms,
    t.updated_at_unix_ms,
    t.metadata_json
FROM task_records t
WHERE t.id IN (SELECT id FROM board_node_task_ids)
  AND (
    CAST(?1 AS INTEGER) = 0
    OR t.updated_at_unix_ms < ?2
    OR (
        t.updated_at_unix_ms = ?2
        AND t.id < ?3
    )
  )
ORDER BY t.updated_at_unix_ms DESC, t.id DESC
LIMIT ?4
`

type ListBoardNodeTasksParams struct {
	CursorSet              int64
	CursorUpdatedAtUnixMs  int64
	CursorTaskID           string
	LimitRows              int64
	NodeID                 sql.NullString
	ProjectID              string
	WorkflowID             string
	CanceledTerminalNodeID interface{}
}

func (q *Queries) ListBoardNodeTasks(ctx context.Context, arg ListBoardNodeTasksParams) ([]TaskRecord, error) {
	rows, err := q.db.QueryContext(ctx, listBoardNodeTasks,
		arg.CursorSet,
		arg.CursorUpdatedAtUnixMs,
		arg.CursorTaskID,
		arg.LimitRows,
		arg.NodeID,
		arg.ProjectID,
		arg.WorkflowID,
		arg.CanceledTerminalNodeID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRecord
	for rows.Next() {
		var i TaskRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listBoardOpenTasks = `-- name: ListBoardOpenTasks :many
WITH board_open_task_ids AS (
    SELECT
        t.id
    FROM task_node_placements p
    JOIN task_records t ON t.id = p.task_id
    JOIN workflow_nodes n ON n.id = p.node_id
    WHERE p.state IN ('active', 'waiting_approval')
      AND n.kind != 'terminal'
      AND t.project_id = ?5
      AND t.workflow_id = ?6
      AND (
          t.canceled_at_unix_ms = 0
          OR trim(?7) = ''
      )
    UNION
    SELECT
        t.id
    FROM task_transition_records tt
    JOIN task_records t ON t.id = tt.task_id
    JOIN workflow_nodes n ON n.id = tt.source_node_id
    WHERE tt.state = 'pending_approval'
      AND n.kind != 'terminal'
      AND t.project_id = ?5
      AND t.workflow_id = ?6
      AND (
          t.canceled_at_unix_ms = 0
          OR trim(?7) = ''
      )
)
SELECT
    t.id,
    t.project_id,
    t.project_workflow_link_id,
    t.workflow_id,
    t.workflow_revision_seen,
    t.task_seq,
    t.short_id,
    t.title,
    t.body,
    t.source_url,
    t.source_workspace_id,
    t.managed_worktree_id,
    t.canceled_at_unix_ms,
    t.cancellation_reason,
    t.created_at_unix_ms,
    t.updated_at_unix_ms,
    t.metadata_json
FROM task_records t
WHERE t.id IN (SELECT id FROM board_open_task_ids)
  AND NOT EXISTS (
      SELECT 1
      FROM task_node_placements terminal_placement
      JOIN workflow_nodes terminal_node ON terminal_node.id = terminal_placement.node_id
      WHERE terminal_placement.task_id = t.id
        AND terminal_placement.state = 'completed'
        AND terminal_node.kind = 'terminal'
  )
  AND (
    CAST(?1 AS INTEGER) = 0
    OR t.updated_at_unix_ms < ?2
    OR (
        t.updated_at_unix_ms = ?2
        AND t.id < ?3
    )
  )
ORDER BY t.updated_at_unix_ms DESC, t.id DESC
LIMIT ?4
`

type ListBoardOpenTasksParams struct {
	CursorSet              int64
	CursorUpdatedAtUnixMs  int64
	CursorTaskID           string
	LimitRows              int64
	ProjectID              string
	WorkflowID             string
	CanceledTerminalNodeID string
}

func (q *Queries) ListBoardOpenTasks(ctx context.Context, arg ListBoardOpenTasksParams) ([]TaskRecord, error) {
	rows, err := q.db.QueryContext(ctx, listBoardOpenTasks,
		arg.CursorSet,
		arg.CursorUpdatedAtUnixMs,
		arg.CursorTaskID,
		arg.LimitRows,
		arg.ProjectID,
		arg.WorkflowID,
		arg.CanceledTerminalNodeID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRecord
	for rows.Next() {
		var i TaskRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listInterruptTaskRunCandidates = `-- name: ListInterruptTaskRunCandidates :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.task_id = ?1
  AND (?2 = '' OR r.session_id = ?2)
  AND r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

type ListInterruptTaskRunCandidatesParams struct {
	TaskID    string
	SessionID interface{}
}

func (q *Queries) ListInterruptTaskRunCandidates(ctx context.Context, arg ListInterruptTaskRunCandidatesParams) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, listInterruptTaskRunCandidates, arg.TaskID, arg.SessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listJoinArrivals = `-- name: ListJoinArrivals :many
SELECT
    p.id,
    p.parallel_branch_edge_id,
    te.workflow_edge_id,
    tr.source_node_key,
    tr.output_values_json
FROM task_node_placements p
JOIN task_transitions tr ON tr.source_placement_id = p.id
JOIN task_transition_edges te ON te.task_transition_id = tr.id
WHERE p.parallel_batch_transition_id = ?1
  AND p.state = 'completed'
  AND te.target_node_id = ?2
  AND te.state = 'applied'
ORDER BY p.parallel_branch_edge_id ASC, tr.created_at_unix_ms ASC, te.rowid ASC
`

type ListJoinArrivalsParams struct {
	BatchID    sql.NullString
	JoinNodeID sql.NullString
}

type ListJoinArrivalsRow struct {
	ID                   string
	ParallelBranchEdgeID sql.NullString
	WorkflowEdgeID       sql.NullString
	SourceNodeKey        string
	OutputValuesJson     string
}

func (q *Queries) ListJoinArrivals(ctx context.Context, arg ListJoinArrivalsParams) ([]ListJoinArrivalsRow, error) {
	rows, err := q.db.QueryContext(ctx, listJoinArrivals, arg.BatchID, arg.JoinNodeID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListJoinArrivalsRow
	for rows.Next() {
		var i ListJoinArrivalsRow
		if err := rows.Scan(
			&i.ID,
			&i.ParallelBranchEdgeID,
			&i.WorkflowEdgeID,
			&i.SourceNodeKey,
			&i.OutputValuesJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listJoinExpectedBranches = `-- name: ListJoinExpectedBranches :many
SELECT target_placement_id
FROM task_transition_edges
WHERE task_transition_id = ?1
  AND target_placement_id IS NOT NULL
ORDER BY rowid ASC
`

func (q *Queries) ListJoinExpectedBranches(ctx context.Context, batchID string) ([]sql.NullString, error) {
	rows, err := q.db.QueryContext(ctx, listJoinExpectedBranches, batchID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []sql.NullString
	for rows.Next() {
		var target_placement_id sql.NullString
		if err := rows.Scan(&target_placement_id); err != nil {
			return nil, err
		}
		items = append(items, target_placement_id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPendingApprovalManualMoveSources = `-- name: ListPendingApprovalManualMoveSources :many
SELECT tt.id, tt.source_placement_id, p.node_id
FROM task_transitions tt
JOIN task_node_placements p ON p.id = tt.source_placement_id
WHERE tt.task_id = ?1
  AND tt.state = 'pending_approval'
ORDER BY tt.created_at_unix_ms DESC, tt.rowid DESC
`

type ListPendingApprovalManualMoveSourcesRow struct {
	ID                string
	SourcePlacementID sql.NullString
	NodeID            sql.NullString
}

func (q *Queries) ListPendingApprovalManualMoveSources(ctx context.Context, taskID string) ([]ListPendingApprovalManualMoveSourcesRow, error) {
	rows, err := q.db.QueryContext(ctx, listPendingApprovalManualMoveSources, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListPendingApprovalManualMoveSourcesRow
	for rows.Next() {
		var i ListPendingApprovalManualMoveSourcesRow
		if err := rows.Scan(&i.ID, &i.SourcePlacementID, &i.NodeID); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPendingApprovalSourcePlacementsByTasks = `-- name: ListPendingApprovalSourcePlacementsByTasks :many
SELECT
    CAST(COALESCE('pending-approval:' || id, '') AS TEXT) AS id,
    task_id,
    source_node_id AS node_id,
    'waiting_approval' AS state,
    '' AS created_by_transition_id,
    CAST(NULL AS TEXT) AS parallel_batch_transition_id,
    CAST(NULL AS TEXT) AS parallel_branch_edge_id,
    created_at_unix_ms,
    created_at_unix_ms AS updated_at_unix_ms
FROM task_transition_records
WHERE task_id IN (/*SLICE:task_ids*/?)
  AND state = 'pending_approval'
  AND source_node_id IS NOT NULL
  AND trim(source_node_id) != ''
ORDER BY task_id ASC, created_at_unix_ms ASC, id ASC
`

type ListPendingApprovalSourcePlacementsByTasksRow struct {
	ID                        string
	TaskID                    string
	NodeID                    sql.NullString
	State                     string
	CreatedByTransitionID     string
	ParallelBatchTransitionID sql.NullString
	ParallelBranchEdgeID      sql.NullString
	CreatedAtUnixMs           int64
	UpdatedAtUnixMs           int64
}

func (q *Queries) ListPendingApprovalSourcePlacementsByTasks(ctx context.Context, taskIds []string) ([]ListPendingApprovalSourcePlacementsByTasksRow, error) {
	query := listPendingApprovalSourcePlacementsByTasks
	var queryParams []interface{}
	if len(taskIds) > 0 {
		for _, v := range taskIds {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:task_ids*/?", strings.Repeat(",?", len(taskIds))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:task_ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListPendingApprovalSourcePlacementsByTasksRow
	for rows.Next() {
		var i ListPendingApprovalSourcePlacementsByTasksRow
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.NodeID,
			&i.State,
			&i.CreatedByTransitionID,
			&i.ParallelBatchTransitionID,
			&i.ParallelBranchEdgeID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPendingApprovalTransitionIDsByTask = `-- name: ListPendingApprovalTransitionIDsByTask :many
SELECT id
FROM task_transition_records
WHERE task_id = ?1
  AND state = 'pending_approval'
ORDER BY created_at_unix_ms ASC, id ASC
`

func (q *Queries) ListPendingApprovalTransitionIDsByTask(ctx context.Context, taskID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listPendingApprovalTransitionIDsByTask, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPendingApprovalTransitionIDsByWorkflow = `-- name: ListPendingApprovalTransitionIDsByWorkflow :many
SELECT tt.id
FROM task_transition_records tt
JOIN task_records t ON t.id = tt.task_id
WHERE t.workflow_id = ?1
  AND t.canceled_at_unix_ms = 0
  AND tt.state = 'pending_approval'
ORDER BY tt.created_at_unix_ms ASC, tt.id ASC
`

func (q *Queries) ListPendingApprovalTransitionIDsByWorkflow(ctx context.Context, workflowID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listPendingApprovalTransitionIDsByWorkflow, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectHomeSummaries = `-- name: ListProjectHomeSummaries :many
SELECT
    p.id AS project_id,
    p.project_key,
    p.display_name,
    COALESCE(w.id, '') AS primary_workspace_id,
    COALESCE(w.canonical_root_path, '') AS primary_workspace_root_path,
    CAST(COALESCE(w.updated_at_unix_ms, p.updated_at_unix_ms) AS INTEGER) AS primary_workspace_updated_at_unix_ms,
    COALESCE(default_workflow.id, '') AS default_workflow_id,
    COALESCE(default_workflow.name, '') AS default_workflow_name,
    CASE WHEN default_workflow.id IS NULL THEN 0 ELSE 1 END AS default_workflow_valid,
    CAST(MAX(
        p.updated_at_unix_ms,
        COALESCE(w.updated_at_unix_ms, 0),
        COALESCE((SELECT MAX(t.updated_at_unix_ms) FROM task_records t WHERE t.project_id = p.id), 0),
        COALESCE((
            SELECT MAX(tnp.updated_at_unix_ms)
            FROM task_node_placements tnp
            JOIN task_records placement_tasks ON placement_tasks.id = tnp.task_id
            WHERE placement_tasks.project_id = p.id
        ), 0),
        COALESCE((
            SELECT MAX(tr.updated_at_unix_ms)
            FROM task_run_records tr
            JOIN task_records run_tasks ON run_tasks.id = tr.task_id
            WHERE run_tasks.project_id = p.id
        ), 0),
        COALESCE((
            SELECT MAX(MAX(tt.created_at_unix_ms, tt.applied_at_unix_ms))
            FROM task_transitions tt
            JOIN task_records transition_tasks ON transition_tasks.id = tt.task_id
            WHERE transition_tasks.project_id = p.id
        ), 0),
        COALESCE((
            SELECT MAX(tc.updated_at_unix_ms)
            FROM task_comments tc
            JOIN task_records comment_tasks ON comment_tasks.id = tc.task_id
            WHERE comment_tasks.project_id = p.id
        ), 0),
        COALESCE((SELECT MAX(s.updated_at_unix_ms) FROM sessions s WHERE s.project_id = p.id AND s.launch_visible <> 0), 0),
        COALESCE((SELECT MAX(pwl.updated_at_unix_ms) FROM project_workflow_links pwl WHERE pwl.project_id = p.id), 0)
    ) AS INTEGER) AS latest_activity_unix_ms,
    CAST((SELECT COUNT(*) FROM task_records t WHERE t.project_id = p.id) AS INTEGER) AS task_count,
    CAST((
        SELECT COUNT(DISTINCT attention_tasks.id)
        FROM task_records attention_tasks
        WHERE attention_tasks.project_id = p.id
          AND attention_tasks.canceled_at_unix_ms = 0
          AND (
              EXISTS (
                  SELECT 1
                  FROM task_node_placements tnp
                  WHERE tnp.task_id = attention_tasks.id
                    AND tnp.state = 'waiting_approval'
              )
              OR EXISTS (
                  SELECT 1
                  FROM task_transitions tt
                  WHERE tt.task_id = attention_tasks.id
                    AND tt.state = 'pending_approval'
              )
              OR EXISTS (
                  SELECT 1
                  FROM task_run_records tr
                  WHERE tr.task_id = attention_tasks.id
                    AND tr.completed_at_unix_ms = 0
                    AND (
                        tr.interrupted_at_unix_ms > 0
                        OR trim(tr.waiting_ask_id) <> ''
                    )
              )
          )
    ) AS INTEGER) AS attention_count,
    CAST((
        SELECT COUNT(*)
        FROM project_workflow_links pwl
        WHERE pwl.project_id = p.id
    ) AS INTEGER) AS workflow_count
FROM projects p
LEFT JOIN workspaces w ON w.id = p.primary_workspace_id AND w.project_id = p.id
LEFT JOIN project_workflow_links default_link
    ON default_link.id = p.default_project_workflow_link_id
   AND default_link.project_id = p.id
LEFT JOIN workflows default_workflow ON default_workflow.id = default_link.workflow_id
WHERE (?1 = '' OR p.id = ?1)
ORDER BY latest_activity_unix_ms DESC, p.rowid DESC
LIMIT ?3
OFFSET ?2
`

type ListProjectHomeSummariesParams struct {
	ProjectID  interface{}
	OffsetRows int64
	LimitRows  int64
}

type ListProjectHomeSummariesRow struct {
	ProjectID                       string
	ProjectKey                      string
	DisplayName                     string
	PrimaryWorkspaceID              string
	PrimaryWorkspaceRootPath        string
	PrimaryWorkspaceUpdatedAtUnixMs int64
	DefaultWorkflowID               string
	DefaultWorkflowName             string
	DefaultWorkflowValid            int64
	LatestActivityUnixMs            int64
	TaskCount                       int64
	AttentionCount                  int64
	WorkflowCount                   int64
}

func (q *Queries) ListProjectHomeSummaries(ctx context.Context, arg ListProjectHomeSummariesParams) ([]ListProjectHomeSummariesRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectHomeSummaries, arg.ProjectID, arg.OffsetRows, arg.LimitRows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectHomeSummariesRow
	for rows.Next() {
		var i ListProjectHomeSummariesRow
		if err := rows.Scan(
			&i.ProjectID,
			&i.ProjectKey,
			&i.DisplayName,
			&i.PrimaryWorkspaceID,
			&i.PrimaryWorkspaceRootPath,
			&i.PrimaryWorkspaceUpdatedAtUnixMs,
			&i.DefaultWorkflowID,
			&i.DefaultWorkflowName,
			&i.DefaultWorkflowValid,
			&i.LatestActivityUnixMs,
			&i.TaskCount,
			&i.AttentionCount,
			&i.WorkflowCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectKeyRows = `-- name: ListProjectKeyRows :many
SELECT
    id,
    display_name,
    project_key
FROM projects
ORDER BY created_at_unix_ms ASC, rowid ASC
`

type ListProjectKeyRowsRow struct {
	ID          string
	DisplayName string
	ProjectKey  string
}

func (q *Queries) ListProjectKeyRows(ctx context.Context) ([]ListProjectKeyRowsRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectKeyRows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectKeyRowsRow
	for rows.Next() {
		var i ListProjectKeyRowsRow
		if err := rows.Scan(&i.ID, &i.DisplayName, &i.ProjectKey); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectSessionArtifacts = `-- name: ListProjectSessionArtifacts :many
SELECT
    id,
    artifact_relpath
FROM sessions
WHERE project_id = ?1
  AND trim(artifact_relpath) != ''
ORDER BY rowid ASC
`

type ListProjectSessionArtifactsRow struct {
	ID              string
	ArtifactRelpath string
}

func (q *Queries) ListProjectSessionArtifacts(ctx context.Context, projectID string) ([]ListProjectSessionArtifactsRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectSessionArtifacts, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectSessionArtifactsRow
	for rows.Next() {
		var i ListProjectSessionArtifactsRow
		if err := rows.Scan(&i.ID, &i.ArtifactRelpath); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectSessionIDs = `-- name: ListProjectSessionIDs :many
SELECT id
FROM sessions
WHERE project_id = ?1
ORDER BY rowid ASC
`

func (q *Queries) ListProjectSessionIDs(ctx context.Context, projectID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listProjectSessionIDs, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectWorkflowLinkTaskReferences = `-- name: ListProjectWorkflowLinkTaskReferences :many
SELECT
    id,
    short_id,
    title
FROM tasks
WHERE project_workflow_link_id = ?1
ORDER BY updated_at_unix_ms DESC, id ASC
LIMIT ?2
`

type ListProjectWorkflowLinkTaskReferencesParams struct {
	ProjectWorkflowLinkID string
	Limit                 int64
}

type ListProjectWorkflowLinkTaskReferencesRow struct {
	ID      string
	ShortID string
	Title   string
}

func (q *Queries) ListProjectWorkflowLinkTaskReferences(ctx context.Context, arg ListProjectWorkflowLinkTaskReferencesParams) ([]ListProjectWorkflowLinkTaskReferencesRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectWorkflowLinkTaskReferences, arg.ProjectWorkflowLinkID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectWorkflowLinkTaskReferencesRow
	for rows.Next() {
		var i ListProjectWorkflowLinkTaskReferencesRow
		if err := rows.Scan(&i.ID, &i.ShortID, &i.Title); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectWorkflowLinks = `-- name: ListProjectWorkflowLinks :many
SELECT
    id,
    project_id,
    workflow_id,
    is_default,
    created_at_unix_ms,
    updated_at_unix_ms
FROM project_workflow_link_records
WHERE project_id = ?1
ORDER BY is_default DESC, created_at_unix_ms ASC, id ASC
`

func (q *Queries) ListProjectWorkflowLinks(ctx context.Context, projectID string) ([]ProjectWorkflowLinkRecord, error) {
	rows, err := q.db.QueryContext(ctx, listProjectWorkflowLinks, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ProjectWorkflowLinkRecord
	for rows.Next() {
		var i ProjectWorkflowLinkRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.WorkflowID,
			&i.IsDefault,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectWorkflowTaskActivity = `-- name: ListProjectWorkflowTaskActivity :many
SELECT
    workflow_id,
    CAST(MAX(updated_at_unix_ms) AS INTEGER) AS latest_updated_at_unix_ms
FROM task_records
WHERE project_id = ?1
GROUP BY workflow_id
ORDER BY latest_updated_at_unix_ms DESC, workflow_id ASC
`

type ListProjectWorkflowTaskActivityRow struct {
	WorkflowID            string
	LatestUpdatedAtUnixMs int64
}

func (q *Queries) ListProjectWorkflowTaskActivity(ctx context.Context, projectID string) ([]ListProjectWorkflowTaskActivityRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectWorkflowTaskActivity, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectWorkflowTaskActivityRow
	for rows.Next() {
		var i ListProjectWorkflowTaskActivityRow
		if err := rows.Scan(&i.WorkflowID, &i.LatestUpdatedAtUnixMs); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectWorkspaces = `-- name: ListProjectWorkspaces :many
SELECT
    w.id,
    w.canonical_root_path AS root_path,
    CASE WHEN w.id = p.primary_workspace_id THEN 1 ELSE 0 END AS is_primary,
    CAST(COALESCE(COUNT(s.id), 0) AS INTEGER) AS session_count,
    COALESCE(MAX(s.updated_at_unix_ms), w.updated_at_unix_ms) AS latest_activity_unix_ms
FROM workspaces w
JOIN projects p ON p.id = w.project_id
LEFT JOIN sessions s ON s.workspace_id = w.id AND s.launch_visible <> 0
WHERE w.project_id = ?1
GROUP BY w.id, w.canonical_root_path, p.primary_workspace_id, w.updated_at_unix_ms
ORDER BY CASE WHEN w.id = p.primary_workspace_id THEN 1 ELSE 0 END DESC, latest_activity_unix_ms DESC, w.created_at_unix_ms ASC, w.rowid ASC
`

type ListProjectWorkspacesRow struct {
	ID                   string
	RootPath             string
	IsPrimary            int64
	SessionCount         int64
	LatestActivityUnixMs int64
}

func (q *Queries) ListProjectWorkspaces(ctx context.Context, projectID string) ([]ListProjectWorkspacesRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectWorkspaces, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectWorkspacesRow
	for rows.Next() {
		var i ListProjectWorkspacesRow
		if err := rows.Scan(
			&i.ID,
			&i.RootPath,
			&i.IsPrimary,
			&i.SessionCount,
			&i.LatestActivityUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjectWorkspacesPage = `-- name: ListProjectWorkspacesPage :many
SELECT
    w.id,
    w.canonical_root_path AS root_path,
    CASE WHEN w.id = p.primary_workspace_id THEN 1 ELSE 0 END AS is_primary,
    CAST(COALESCE(COUNT(s.id), 0) AS INTEGER) AS session_count,
    COALESCE(MAX(s.updated_at_unix_ms), w.updated_at_unix_ms) AS latest_activity_unix_ms
FROM workspaces w
JOIN projects p ON p.id = w.project_id
LEFT JOIN sessions s ON s.workspace_id = w.id AND s.launch_visible <> 0
WHERE w.project_id = ?1
GROUP BY w.id, w.canonical_root_path, p.primary_workspace_id, w.updated_at_unix_ms
ORDER BY CASE WHEN w.id = p.primary_workspace_id THEN 1 ELSE 0 END DESC, w.created_at_unix_ms DESC, w.rowid DESC
LIMIT ?3
OFFSET ?2
`

type ListProjectWorkspacesPageParams struct {
	ProjectID  string
	OffsetRows int64
	LimitRows  int64
}

type ListProjectWorkspacesPageRow struct {
	ID                   string
	RootPath             string
	IsPrimary            int64
	SessionCount         int64
	LatestActivityUnixMs int64
}

func (q *Queries) ListProjectWorkspacesPage(ctx context.Context, arg ListProjectWorkspacesPageParams) ([]ListProjectWorkspacesPageRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjectWorkspacesPage, arg.ProjectID, arg.OffsetRows, arg.LimitRows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectWorkspacesPageRow
	for rows.Next() {
		var i ListProjectWorkspacesPageRow
		if err := rows.Scan(
			&i.ID,
			&i.RootPath,
			&i.IsPrimary,
			&i.SessionCount,
			&i.LatestActivityUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listProjects = `-- name: ListProjects :many
SELECT
    p.id,
    p.display_name,
    p.project_key,
    COALESCE(w.canonical_root_path, '') AS root_path,
    CAST(COALESCE(COUNT(s.id), 0) AS INTEGER) AS session_count,
    COALESCE(MAX(s.updated_at_unix_ms), p.updated_at_unix_ms) AS latest_activity_unix_ms
FROM projects p
LEFT JOIN workspaces w ON w.id = p.primary_workspace_id AND w.project_id = p.id
LEFT JOIN sessions s ON s.project_id = p.id AND s.launch_visible <> 0
GROUP BY p.id, p.display_name, p.project_key, w.canonical_root_path, p.updated_at_unix_ms
ORDER BY latest_activity_unix_ms DESC
`

type ListProjectsRow struct {
	ID                   string
	DisplayName          string
	ProjectKey           string
	RootPath             string
	SessionCount         int64
	LatestActivityUnixMs int64
}

func (q *Queries) ListProjects(ctx context.Context) ([]ListProjectsRow, error) {
	rows, err := q.db.QueryContext(ctx, listProjects)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListProjectsRow
	for rows.Next() {
		var i ListProjectsRow
		if err := rows.Scan(
			&i.ID,
			&i.DisplayName,
			&i.ProjectKey,
			&i.RootPath,
			&i.SessionCount,
			&i.LatestActivityUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listResumeTaskRunCandidates = `-- name: ListResumeTaskRunCandidates :many
SELECT
    r.id,
    r.run_start_snapshot_json
FROM task_run_records r
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.task_id = ?1
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms > 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
ORDER BY r.interrupted_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

type ListResumeTaskRunCandidatesRow struct {
	ID                   string
	RunStartSnapshotJson string
}

func (q *Queries) ListResumeTaskRunCandidates(ctx context.Context, taskID string) ([]ListResumeTaskRunCandidatesRow, error) {
	rows, err := q.db.QueryContext(ctx, listResumeTaskRunCandidates, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListResumeTaskRunCandidatesRow
	for rows.Next() {
		var i ListResumeTaskRunCandidatesRow
		if err := rows.Scan(&i.ID, &i.RunStartSnapshotJson); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRunnableWorkflowRuns = `-- name: ListRunnableWorkflowRuns :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.automation_requested_at_unix_ms > 0
  AND r.started_at_unix_ms = 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND r.waiting_ask_id = ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
ORDER BY r.automation_requested_at_unix_ms ASC, r.id ASC
LIMIT ?1
`

func (q *Queries) ListRunnableWorkflowRuns(ctx context.Context, limit int64) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, listRunnableWorkflowRuns, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSessionNamesByIDs = `-- name: ListSessionNamesByIDs :many
SELECT id, name
FROM sessions
WHERE id IN (/*SLICE:ids*/?)
`

type ListSessionNamesByIDsRow struct {
	ID   string
	Name string
}

func (q *Queries) ListSessionNamesByIDs(ctx context.Context, ids []string) ([]ListSessionNamesByIDsRow, error) {
	query := listSessionNamesByIDs
	var queryParams []interface{}
	if len(ids) > 0 {
		for _, v := range ids {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:ids*/?", strings.Repeat(",?", len(ids))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListSessionNamesByIDsRow
	for rows.Next() {
		var i ListSessionNamesByIDsRow
		if err := rows.Scan(&i.ID, &i.Name); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSessionPromptHistoryText = `-- name: ListSessionPromptHistoryText :many
SELECT text
FROM session_prompt_history_entries
WHERE session_id = ?1
ORDER BY sequence ASC
`

func (q *Queries) ListSessionPromptHistoryText(ctx context.Context, sessionID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listSessionPromptHistoryText, sessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var text string
		if err := rows.Scan(&text); err != nil {
			return nil, err
		}
		items = append(items, text)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSessionsByProject = `-- name: ListSessionsByProject :many
SELECT
    id,
    name,
    first_prompt_preview,
    updated_at_unix_ms
FROM sessions
WHERE project_id = ?1
  AND launch_visible <> 0
ORDER BY updated_at_unix_ms DESC, rowid DESC
`

type ListSessionsByProjectRow struct {
	ID                 string
	Name               string
	FirstPromptPreview string
	UpdatedAtUnixMs    int64
}

func (q *Queries) ListSessionsByProject(ctx context.Context, projectID string) ([]ListSessionsByProjectRow, error) {
	rows, err := q.db.QueryContext(ctx, listSessionsByProject, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListSessionsByProjectRow
	for rows.Next() {
		var i ListSessionsByProjectRow
		if err := rows.Scan(
			&i.ID,
			&i.Name,
			&i.FirstPromptPreview,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listSessionsTargetingWorktree = `-- name: ListSessionsTargetingWorktree :many
SELECT
    id,
    name,
    updated_at_unix_ms
FROM sessions
WHERE worktree_id = ?1
ORDER BY updated_at_unix_ms DESC, rowid DESC
`

type ListSessionsTargetingWorktreeRow struct {
	ID              string
	Name            string
	UpdatedAtUnixMs int64
}

func (q *Queries) ListSessionsTargetingWorktree(ctx context.Context, worktreeID sql.NullString) ([]ListSessionsTargetingWorktreeRow, error) {
	rows, err := q.db.QueryContext(ctx, listSessionsTargetingWorktree, worktreeID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListSessionsTargetingWorktreeRow
	for rows.Next() {
		var i ListSessionsTargetingWorktreeRow
		if err := rows.Scan(&i.ID, &i.Name, &i.UpdatedAtUnixMs); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStartedWorkflowRunRecoveryCandidates = `-- name: ListStartedWorkflowRunRecoveryCandidates :many
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE started_at_unix_ms > 0
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND waiting_ask_id = ''
ORDER BY updated_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = task_run_records.id
) ASC
`

type ListStartedWorkflowRunRecoveryCandidatesRow struct {
	ID                      string
	TaskID                  string
	PlacementID             string
	NodeID                  sql.NullString
	SessionID               sql.NullString
	RunGeneration           int64
	StartedAtUnixMs         int64
	CompletedAtUnixMs       int64
	InterruptedAtUnixMs     int64
	InterruptionReason      string
	InterruptionDetailJson  string
	WaitingAskID            string
	EffectiveCompletionMode string
	InvalidCompletionCount  int64
	RunStartSnapshotJson    string
	MetadataJson            string
}

func (q *Queries) ListStartedWorkflowRunRecoveryCandidates(ctx context.Context) ([]ListStartedWorkflowRunRecoveryCandidatesRow, error) {
	rows, err := q.db.QueryContext(ctx, listStartedWorkflowRunRecoveryCandidates)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListStartedWorkflowRunRecoveryCandidatesRow
	for rows.Next() {
		var i ListStartedWorkflowRunRecoveryCandidatesRow
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskComments = `-- name: ListTaskComments :many
SELECT
    id,
    task_id,
    body,
    author_kind,
    author_id,
    created_at_unix_ms,
    updated_at_unix_ms
FROM task_comments
WHERE task_id = ?1
ORDER BY created_at_unix_ms DESC, id DESC
LIMIT ?3
OFFSET ?2
`

type ListTaskCommentsParams struct {
	TaskID     string
	OffsetRows int64
	LimitRows  int64
}

func (q *Queries) ListTaskComments(ctx context.Context, arg ListTaskCommentsParams) ([]TaskComment, error) {
	rows, err := q.db.QueryContext(ctx, listTaskComments, arg.TaskID, arg.OffsetRows, arg.LimitRows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskComment
	for rows.Next() {
		var i TaskComment
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.Body,
			&i.AuthorKind,
			&i.AuthorID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskCommentsByIDs = `-- name: ListTaskCommentsByIDs :many
SELECT
    id,
    task_id,
    body,
    author_kind,
    author_id,
    created_at_unix_ms,
    updated_at_unix_ms
FROM task_comments
WHERE id IN (/*SLICE:ids*/?)
`

func (q *Queries) ListTaskCommentsByIDs(ctx context.Context, ids []string) ([]TaskComment, error) {
	query := listTaskCommentsByIDs
	var queryParams []interface{}
	if len(ids) > 0 {
		for _, v := range ids {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:ids*/?", strings.Repeat(",?", len(ids))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskComment
	for rows.Next() {
		var i TaskComment
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.Body,
			&i.AuthorKind,
			&i.AuthorID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskCommentsPage = `-- name: ListTaskCommentsPage :many
SELECT
    id,
    task_id,
    body,
    author_kind,
    author_id,
    created_at_unix_ms,
    updated_at_unix_ms
FROM task_comments
WHERE task_id = ?1
    AND (
        ?2 = 0
        OR created_at_unix_ms < ?3
        OR (
            created_at_unix_ms = ?3
            AND id < ?4
        )
    )
ORDER BY created_at_unix_ms DESC, id DESC
LIMIT ?5
`

type ListTaskCommentsPageParams struct {
	TaskID                string
	HasCursor             interface{}
	CursorCreatedAtUnixMs int64
	CursorID              string
	LimitRows             int64
}

func (q *Queries) ListTaskCommentsPage(ctx context.Context, arg ListTaskCommentsPageParams) ([]TaskComment, error) {
	rows, err := q.db.QueryContext(ctx, listTaskCommentsPage,
		arg.TaskID,
		arg.HasCursor,
		arg.CursorCreatedAtUnixMs,
		arg.CursorID,
		arg.LimitRows,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskComment
	for rows.Next() {
		var i TaskComment
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.Body,
			&i.AuthorKind,
			&i.AuthorID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskNodePlacements = `-- name: ListTaskNodePlacements :many
SELECT
    id,
    task_id,
    node_id,
    state,
    created_by_transition_id,
    parallel_batch_transition_id,
    parallel_branch_edge_id,
    created_at_unix_ms,
    updated_at_unix_ms
FROM task_node_placement_records
WHERE task_id = ?1
ORDER BY created_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_node_placements storage
    WHERE storage.id = task_node_placement_records.id
) ASC
`

func (q *Queries) ListTaskNodePlacements(ctx context.Context, taskID string) ([]TaskNodePlacementRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTaskNodePlacements, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskNodePlacementRecord
	for rows.Next() {
		var i TaskNodePlacementRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.NodeID,
			&i.State,
			&i.CreatedByTransitionID,
			&i.ParallelBatchTransitionID,
			&i.ParallelBranchEdgeID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskNodePlacementsByTasks = `-- name: ListTaskNodePlacementsByTasks :many
SELECT
    id,
    task_id,
    node_id,
    state,
    created_by_transition_id,
    parallel_batch_transition_id,
    parallel_branch_edge_id,
    created_at_unix_ms,
    updated_at_unix_ms
FROM task_node_placement_records
WHERE task_id IN (/*SLICE:task_ids*/?)
ORDER BY task_id ASC, created_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_node_placements storage
    WHERE storage.id = task_node_placement_records.id
) ASC
`

func (q *Queries) ListTaskNodePlacementsByTasks(ctx context.Context, taskIds []string) ([]TaskNodePlacementRecord, error) {
	query := listTaskNodePlacementsByTasks
	var queryParams []interface{}
	if len(taskIds) > 0 {
		for _, v := range taskIds {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:task_ids*/?", strings.Repeat(",?", len(taskIds))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:task_ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskNodePlacementRecord
	for rows.Next() {
		var i TaskNodePlacementRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.NodeID,
			&i.State,
			&i.CreatedByTransitionID,
			&i.ParallelBatchTransitionID,
			&i.ParallelBranchEdgeID,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskRunIDsByPlacementForTransitionResult = `-- name: ListTaskRunIDsByPlacementForTransitionResult :many
SELECT id
FROM task_runs
WHERE placement_id = ?1
ORDER BY created_at_unix_ms ASC, rowid ASC
`

func (q *Queries) ListTaskRunIDsByPlacementForTransitionResult(ctx context.Context, placementID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listTaskRunIDsByPlacementForTransitionResult, placementID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskRuns = `-- name: ListTaskRuns :many
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE task_id = ?1
ORDER BY created_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = task_run_records.id
) ASC
`

func (q *Queries) ListTaskRuns(ctx context.Context, taskID string) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTaskRuns, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskRunsByIDs = `-- name: ListTaskRunsByIDs :many
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE id IN (/*SLICE:ids*/?)
`

func (q *Queries) ListTaskRunsByIDs(ctx context.Context, ids []string) ([]TaskRunRecord, error) {
	query := listTaskRunsByIDs
	var queryParams []interface{}
	if len(ids) > 0 {
		for _, v := range ids {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:ids*/?", strings.Repeat(",?", len(ids))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskTransitionEdges = `-- name: ListTaskTransitionEdges :many
SELECT
    id,
    task_transition_id,
    workflow_edge_id,
    edge_key,
    workflow_revision_seen,
    target_node_id,
    target_node_key,
    target_node_display_name,
    target_node_kind,
    target_placement_id,
    state,
    context_mode,
    requires_approval,
    input_bindings_json,
    output_requirements_json,
    metadata_json
FROM task_transition_edge_records
WHERE task_transition_id = ?1
ORDER BY (
    SELECT storage.rowid
    FROM task_transition_edges storage
    WHERE storage.id = task_transition_edge_records.id
) ASC
`

func (q *Queries) ListTaskTransitionEdges(ctx context.Context, taskTransitionID string) ([]TaskTransitionEdgeRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTaskTransitionEdges, taskTransitionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskTransitionEdgeRecord
	for rows.Next() {
		var i TaskTransitionEdgeRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskTransitionID,
			&i.WorkflowEdgeID,
			&i.EdgeKey,
			&i.WorkflowRevisionSeen,
			&i.TargetNodeID,
			&i.TargetNodeKey,
			&i.TargetNodeDisplayName,
			&i.TargetNodeKind,
			&i.TargetPlacementID,
			&i.State,
			&i.ContextMode,
			&i.RequiresApproval,
			&i.InputBindingsJson,
			&i.OutputRequirementsJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskTransitionEdgesByTransitionIDs = `-- name: ListTaskTransitionEdgesByTransitionIDs :many
SELECT
    id,
    task_transition_id,
    workflow_edge_id,
    edge_key,
    workflow_revision_seen,
    target_node_id,
    target_node_key,
    target_node_display_name,
    target_node_kind,
    target_placement_id,
    state,
    context_mode,
    requires_approval,
    input_bindings_json,
    output_requirements_json,
    metadata_json
FROM task_transition_edge_records
WHERE task_transition_id IN (/*SLICE:transition_ids*/?)
ORDER BY task_transition_id ASC, (
    SELECT storage.rowid
    FROM task_transition_edges storage
    WHERE storage.id = task_transition_edge_records.id
) ASC
`

func (q *Queries) ListTaskTransitionEdgesByTransitionIDs(ctx context.Context, transitionIds []string) ([]TaskTransitionEdgeRecord, error) {
	query := listTaskTransitionEdgesByTransitionIDs
	var queryParams []interface{}
	if len(transitionIds) > 0 {
		for _, v := range transitionIds {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:transition_ids*/?", strings.Repeat(",?", len(transitionIds))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:transition_ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskTransitionEdgeRecord
	for rows.Next() {
		var i TaskTransitionEdgeRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskTransitionID,
			&i.WorkflowEdgeID,
			&i.EdgeKey,
			&i.WorkflowRevisionSeen,
			&i.TargetNodeID,
			&i.TargetNodeKey,
			&i.TargetNodeDisplayName,
			&i.TargetNodeKind,
			&i.TargetPlacementID,
			&i.State,
			&i.ContextMode,
			&i.RequiresApproval,
			&i.InputBindingsJson,
			&i.OutputRequirementsJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskTransitions = `-- name: ListTaskTransitions :many
SELECT
    id,
    task_id,
    source_run_id,
    source_placement_id,
    source_node_id,
    source_node_key,
    source_node_display_name,
    transition_group_id,
    transition_id,
    transition_display_name,
    workflow_revision_seen,
    actor,
    state,
    commentary,
    output_values_json,
    created_at_unix_ms,
    applied_at_unix_ms
FROM task_transition_records
WHERE task_id = ?1
ORDER BY created_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_transitions storage
    WHERE storage.id = task_transition_records.id
) ASC
`

func (q *Queries) ListTaskTransitions(ctx context.Context, taskID string) ([]TaskTransitionRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTaskTransitions, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskTransitionRecord
	for rows.Next() {
		var i TaskTransitionRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.SourceRunID,
			&i.SourcePlacementID,
			&i.SourceNodeID,
			&i.SourceNodeKey,
			&i.SourceNodeDisplayName,
			&i.TransitionGroupID,
			&i.TransitionID,
			&i.TransitionDisplayName,
			&i.WorkflowRevisionSeen,
			&i.Actor,
			&i.State,
			&i.Commentary,
			&i.OutputValuesJson,
			&i.CreatedAtUnixMs,
			&i.AppliedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskTransitionsByIDs = `-- name: ListTaskTransitionsByIDs :many
SELECT
    id,
    task_id,
    source_run_id,
    source_placement_id,
    source_node_id,
    source_node_key,
    source_node_display_name,
    transition_group_id,
    transition_id,
    transition_display_name,
    workflow_revision_seen,
    actor,
    state,
    commentary,
    output_values_json,
    created_at_unix_ms,
    applied_at_unix_ms
FROM task_transition_records
WHERE id IN (/*SLICE:ids*/?)
`

func (q *Queries) ListTaskTransitionsByIDs(ctx context.Context, ids []string) ([]TaskTransitionRecord, error) {
	query := listTaskTransitionsByIDs
	var queryParams []interface{}
	if len(ids) > 0 {
		for _, v := range ids {
			queryParams = append(queryParams, v)
		}
		query = strings.Replace(query, "/*SLICE:ids*/?", strings.Repeat(",?", len(ids))[1:], 1)
	} else {
		query = strings.Replace(query, "/*SLICE:ids*/?", "NULL", 1)
	}
	rows, err := q.db.QueryContext(ctx, query, queryParams...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskTransitionRecord
	for rows.Next() {
		var i TaskTransitionRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.SourceRunID,
			&i.SourcePlacementID,
			&i.SourceNodeID,
			&i.SourceNodeKey,
			&i.SourceNodeDisplayName,
			&i.TransitionGroupID,
			&i.TransitionID,
			&i.TransitionDisplayName,
			&i.WorkflowRevisionSeen,
			&i.Actor,
			&i.State,
			&i.Commentary,
			&i.OutputValuesJson,
			&i.CreatedAtUnixMs,
			&i.AppliedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTasksByProject = `-- name: ListTasksByProject :many
SELECT
    id,
    project_id,
    project_workflow_link_id,
    workflow_id,
    workflow_revision_seen,
    task_seq,
    short_id,
    title,
    body,
    source_url,
    source_workspace_id,
    managed_worktree_id,
    canceled_at_unix_ms,
    cancellation_reason,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
FROM task_records
WHERE project_workflow_link_id IN (
    SELECT id
    FROM project_workflow_links
    WHERE project_workflow_links.project_id = ?1
)
ORDER BY updated_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM tasks storage
    WHERE storage.id = task_records.id
) DESC
`

func (q *Queries) ListTasksByProject(ctx context.Context, projectID string) ([]TaskRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTasksByProject, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRecord
	for rows.Next() {
		var i TaskRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTasksByShortID = `-- name: ListTasksByShortID :many
SELECT
    id,
    project_id,
    project_workflow_link_id,
    workflow_id,
    workflow_revision_seen,
    task_seq,
    short_id,
    title,
    body,
    source_url,
    source_workspace_id,
    managed_worktree_id,
    canceled_at_unix_ms,
    cancellation_reason,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
FROM task_records
WHERE short_id = ?1
ORDER BY created_at_unix_ms ASC, id ASC
`

func (q *Queries) ListTasksByShortID(ctx context.Context, shortID string) ([]TaskRecord, error) {
	rows, err := q.db.QueryContext(ctx, listTasksByShortID, shortID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRecord
	for rows.Next() {
		var i TaskRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWaitingAskWorkflowRuns = `-- name: ListWaitingAskWorkflowRuns :many
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE waiting_ask_id != ''
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
ORDER BY updated_at_unix_ms ASC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = task_run_records.id
) ASC
`

func (q *Queries) ListWaitingAskWorkflowRuns(ctx context.Context) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, listWaitingAskWorkflowRuns)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowApprovalAttentionItems = `-- name: ListWorkflowApprovalAttentionItems :many
SELECT tt.id AS task_transition_id, t.project_id, t.workflow_id, t.id AS task_id, t.short_id, t.title, tt.created_at_unix_ms
FROM task_transitions tt
JOIN task_records t ON t.id = tt.task_id
WHERE tt.state = 'pending_approval'
  AND t.canceled_at_unix_ms = 0
  AND (?1 = '' OR t.project_id = ?1)
  AND (?2 = '' OR t.id = ?2)
ORDER BY tt.created_at_unix_ms DESC, tt.rowid DESC
`

type ListWorkflowApprovalAttentionItemsParams struct {
	ProjectID interface{}
	TaskID    interface{}
}

type ListWorkflowApprovalAttentionItemsRow struct {
	TaskTransitionID string
	ProjectID        string
	WorkflowID       string
	TaskID           string
	ShortID          string
	Title            string
	CreatedAtUnixMs  int64
}

func (q *Queries) ListWorkflowApprovalAttentionItems(ctx context.Context, arg ListWorkflowApprovalAttentionItemsParams) ([]ListWorkflowApprovalAttentionItemsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowApprovalAttentionItems, arg.ProjectID, arg.TaskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowApprovalAttentionItemsRow
	for rows.Next() {
		var i ListWorkflowApprovalAttentionItemsRow
		if err := rows.Scan(
			&i.TaskTransitionID,
			&i.ProjectID,
			&i.WorkflowID,
			&i.TaskID,
			&i.ShortID,
			&i.Title,
			&i.CreatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowAttentionCandidates = `-- name: ListWorkflowAttentionCandidates :many
WITH attention_candidates(
    kind,
    id,
    project_id,
    workflow_id,
    task_id,
    short_id,
    title,
    run_id,
    session_id,
    ask_id,
    task_transition_id,
    interruption_reason,
    interruption_detail_json,
    occurred_at_unix_ms
) AS (
    SELECT
        'approval' AS kind,
        CAST('approval:' || tt.id AS TEXT) AS id,
        t.project_id,
        t.workflow_id,
        t.id AS task_id,
        t.short_id,
        t.title,
        '' AS run_id,
        '' AS session_id,
        '' AS ask_id,
        tt.id AS task_transition_id,
        '' AS interruption_reason,
        '' AS interruption_detail_json,
        tt.created_at_unix_ms AS occurred_at_unix_ms
    FROM task_transitions tt
    JOIN task_records t ON t.id = tt.task_id
    WHERE tt.state = 'pending_approval'
      AND t.canceled_at_unix_ms = 0
      AND (?2 = '' OR t.project_id = ?2)
      AND (?3 = '' OR t.id = ?3)
      AND (
          CAST(?4 AS INTEGER) = 0
          OR tt.created_at_unix_ms < ?5
          OR (tt.created_at_unix_ms = ?5 AND ('approval:' || tt.id) < ?6)
      )
    UNION ALL
    SELECT
        'question' AS kind,
        CAST('question:' || r.id || ':' || r.waiting_ask_id AS TEXT) AS id,
        t.project_id,
        t.workflow_id,
        t.id AS task_id,
        t.short_id,
        t.title,
        r.id AS run_id,
        COALESCE(r.session_id, '') AS session_id,
        r.waiting_ask_id AS ask_id,
        '' AS task_transition_id,
        '' AS interruption_reason,
        '' AS interruption_detail_json,
        r.updated_at_unix_ms AS occurred_at_unix_ms
    FROM task_run_records r
    JOIN task_records t ON t.id = r.task_id
    WHERE trim(r.waiting_ask_id) != ''
      AND r.completed_at_unix_ms = 0
      AND r.interrupted_at_unix_ms = 0
      AND t.canceled_at_unix_ms = 0
      AND (?2 = '' OR t.project_id = ?2)
      AND (?3 = '' OR t.id = ?3)
      AND (
          CAST(?4 AS INTEGER) = 0
          OR r.updated_at_unix_ms < ?5
          OR (r.updated_at_unix_ms = ?5 AND ('question:' || r.id || ':' || r.waiting_ask_id) < ?6)
      )
    UNION ALL
    SELECT
        'interrupted_run' AS kind,
        CAST('interrupted_run:' || r.id AS TEXT) AS id,
        t.project_id,
        t.workflow_id,
        t.id AS task_id,
        t.short_id,
        t.title,
        r.id AS run_id,
        COALESCE(r.session_id, '') AS session_id,
        '' AS ask_id,
        '' AS task_transition_id,
        r.interruption_reason,
        r.interruption_detail_json,
        r.interrupted_at_unix_ms AS occurred_at_unix_ms
    FROM task_run_records r
    JOIN task_records t ON t.id = r.task_id
    JOIN task_node_placements p ON p.id = r.placement_id
    WHERE r.interrupted_at_unix_ms > 0
      AND r.completed_at_unix_ms = 0
      AND trim(COALESCE(r.interruption_reason, '')) NOT IN ('user_interrupt', 'workflow_runtime_canceled')
      AND p.state IN ('active', 'waiting_approval')
      AND t.canceled_at_unix_ms = 0
      AND (?2 = '' OR t.project_id = ?2)
      AND (?3 = '' OR t.id = ?3)
      AND (
        CAST(?4 AS INTEGER) = 0
        OR r.interrupted_at_unix_ms < ?5
        OR (r.interrupted_at_unix_ms = ?5 AND ('interrupted_run:' || r.id) < ?6)
      )
    UNION ALL
    SELECT
        'validation_blocker' AS kind,
        CAST('validation_blocker:' || project_id || ':' || workflow_id AS TEXT) AS id,
        project_id,
        workflow_id,
        '' AS task_id,
        '' AS short_id,
        '' AS title,
        '' AS run_id,
        '' AS session_id,
        '' AS ask_id,
        '' AS task_transition_id,
        '' AS interruption_reason,
        '' AS interruption_detail_json,
        updated_at_unix_ms AS occurred_at_unix_ms
    FROM project_workflow_links
    WHERE (?2 = '' OR project_id = ?2)
      AND ?3 = ''
      AND (
          CAST(?4 AS INTEGER) = 0
          OR updated_at_unix_ms < ?5
          OR (updated_at_unix_ms = ?5 AND ('validation_blocker:' || project_id || ':' || workflow_id) < ?6)
      )
)
SELECT
    kind,
    id,
    project_id,
    workflow_id,
    task_id,
    short_id,
    title,
    run_id,
    session_id,
    ask_id,
    task_transition_id,
    interruption_reason,
    interruption_detail_json,
    occurred_at_unix_ms
FROM attention_candidates
ORDER BY occurred_at_unix_ms DESC, id DESC
LIMIT ?1
`

type ListWorkflowAttentionCandidatesParams struct {
	PageLimit              int64
	ProjectID              interface{}
	TaskID                 interface{}
	CursorActive           int64
	CursorOccurredAtUnixMs int64
	CursorItemID           string
}

type ListWorkflowAttentionCandidatesRow struct {
	Kind                   string
	ID                     string
	ProjectID              string
	WorkflowID             string
	TaskID                 string
	ShortID                string
	Title                  string
	RunID                  string
	SessionID              string
	AskID                  string
	TaskTransitionID       string
	InterruptionReason     string
	InterruptionDetailJson string
	OccurredAtUnixMs       int64
}

func (q *Queries) ListWorkflowAttentionCandidates(ctx context.Context, arg ListWorkflowAttentionCandidatesParams) ([]ListWorkflowAttentionCandidatesRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowAttentionCandidates,
		arg.PageLimit,
		arg.ProjectID,
		arg.TaskID,
		arg.CursorActive,
		arg.CursorOccurredAtUnixMs,
		arg.CursorItemID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowAttentionCandidatesRow
	for rows.Next() {
		var i ListWorkflowAttentionCandidatesRow
		if err := rows.Scan(
			&i.Kind,
			&i.ID,
			&i.ProjectID,
			&i.WorkflowID,
			&i.TaskID,
			&i.ShortID,
			&i.Title,
			&i.RunID,
			&i.SessionID,
			&i.AskID,
			&i.TaskTransitionID,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.OccurredAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowEdges = `-- name: ListWorkflowEdges :many
SELECT
    e.id,
    source.workflow_id AS workflow_id,
    e.transition_group_id,
    e.edge_key,
    e.target_node_id,
    e.requires_approval,
    e.context_mode,
    e.context_source_kind,
    e.context_source_node_key,
    e.prompt_template,
    e.parameters_json,
    e.input_bindings_json,
    e.output_requirements_json,
    e.sort_order
FROM workflow_edges e
JOIN workflow_transition_groups tg ON tg.id = e.transition_group_id
JOIN workflow_nodes source ON source.id = tg.source_node_id
WHERE source.workflow_id = ?1
ORDER BY e.sort_order ASC, e.rowid ASC
`

type ListWorkflowEdgesRow struct {
	ID                     string
	WorkflowID             string
	TransitionGroupID      string
	EdgeKey                string
	TargetNodeID           string
	RequiresApproval       int64
	ContextMode            string
	ContextSourceKind      string
	ContextSourceNodeKey   string
	PromptTemplate         string
	ParametersJson         string
	InputBindingsJson      string
	OutputRequirementsJson string
	SortOrder              int64
}

func (q *Queries) ListWorkflowEdges(ctx context.Context, workflowID string) ([]ListWorkflowEdgesRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowEdges, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowEdgesRow
	for rows.Next() {
		var i ListWorkflowEdgesRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.TransitionGroupID,
			&i.EdgeKey,
			&i.TargetNodeID,
			&i.RequiresApproval,
			&i.ContextMode,
			&i.ContextSourceKind,
			&i.ContextSourceNodeKey,
			&i.PromptTemplate,
			&i.ParametersJson,
			&i.InputBindingsJson,
			&i.OutputRequirementsJson,
			&i.SortOrder,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowInterruptedRunAttentionItems = `-- name: ListWorkflowInterruptedRunAttentionItems :many
SELECT t.project_id, t.workflow_id, t.id AS task_id, t.short_id, t.title, r.id AS run_id, COALESCE(r.session_id, '') AS session_id, r.interruption_reason, r.interruption_detail_json, r.interrupted_at_unix_ms
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
WHERE r.interrupted_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND trim(COALESCE(r.interruption_reason, '')) NOT IN ('user_interrupt', 'workflow_runtime_canceled')
  AND p.state IN ('active', 'waiting_approval')
  AND t.canceled_at_unix_ms = 0
  AND (?1 = '' OR t.project_id = ?1)
  AND (?2 = '' OR t.id = ?2)
ORDER BY r.interrupted_at_unix_ms DESC, r.id DESC
`

type ListWorkflowInterruptedRunAttentionItemsParams struct {
	ProjectID interface{}
	TaskID    interface{}
}

type ListWorkflowInterruptedRunAttentionItemsRow struct {
	ProjectID              string
	WorkflowID             string
	TaskID                 string
	ShortID                string
	Title                  string
	RunID                  string
	SessionID              string
	InterruptionReason     string
	InterruptionDetailJson string
	InterruptedAtUnixMs    int64
}

func (q *Queries) ListWorkflowInterruptedRunAttentionItems(ctx context.Context, arg ListWorkflowInterruptedRunAttentionItemsParams) ([]ListWorkflowInterruptedRunAttentionItemsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowInterruptedRunAttentionItems, arg.ProjectID, arg.TaskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowInterruptedRunAttentionItemsRow
	for rows.Next() {
		var i ListWorkflowInterruptedRunAttentionItemsRow
		if err := rows.Scan(
			&i.ProjectID,
			&i.WorkflowID,
			&i.TaskID,
			&i.ShortID,
			&i.Title,
			&i.RunID,
			&i.SessionID,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.InterruptedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowNodeGroups = `-- name: ListWorkflowNodeGroups :many
SELECT
    id,
    workflow_id,
    group_key,
    display_name,
    sort_order
FROM workflow_node_groups
WHERE workflow_id = ?1
ORDER BY sort_order ASC, rowid ASC
`

func (q *Queries) ListWorkflowNodeGroups(ctx context.Context, workflowID string) ([]WorkflowNodeGroup, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowNodeGroups, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []WorkflowNodeGroup
	for rows.Next() {
		var i WorkflowNodeGroup
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.GroupKey,
			&i.DisplayName,
			&i.SortOrder,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowNodes = `-- name: ListWorkflowNodes :many
SELECT
    id,
    workflow_id,
    node_key,
    kind,
    display_name,
    subagent_role,
    prompt_template,
    completion_mode,
    script_path,
    input_fields_json,
    join_input_providers_json,
    output_fields_json,
    group_id,
    sort_order
FROM workflow_nodes
WHERE workflow_id = ?1
ORDER BY sort_order ASC, rowid ASC
`

type ListWorkflowNodesRow struct {
	ID                     string
	WorkflowID             string
	NodeKey                string
	Kind                   string
	DisplayName            string
	SubagentRole           string
	PromptTemplate         string
	CompletionMode         string
	ScriptPath             sql.NullString
	InputFieldsJson        string
	JoinInputProvidersJson string
	OutputFieldsJson       string
	GroupID                sql.NullString
	SortOrder              int64
}

func (q *Queries) ListWorkflowNodes(ctx context.Context, workflowID string) ([]ListWorkflowNodesRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowNodes, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowNodesRow
	for rows.Next() {
		var i ListWorkflowNodesRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.NodeKey,
			&i.Kind,
			&i.DisplayName,
			&i.SubagentRole,
			&i.PromptTemplate,
			&i.CompletionMode,
			&i.ScriptPath,
			&i.InputFieldsJson,
			&i.JoinInputProvidersJson,
			&i.OutputFieldsJson,
			&i.GroupID,
			&i.SortOrder,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowProjectLinks = `-- name: ListWorkflowProjectLinks :many
SELECT
    id,
    project_id,
    workflow_id,
    is_default,
    created_at_unix_ms,
    updated_at_unix_ms
FROM project_workflow_link_records
WHERE workflow_id = ?1
ORDER BY project_id ASC, is_default DESC, created_at_unix_ms ASC
`

func (q *Queries) ListWorkflowProjectLinks(ctx context.Context, workflowID string) ([]ProjectWorkflowLinkRecord, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowProjectLinks, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ProjectWorkflowLinkRecord
	for rows.Next() {
		var i ProjectWorkflowLinkRecord
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.WorkflowID,
			&i.IsDefault,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowQuestionAttentionItems = `-- name: ListWorkflowQuestionAttentionItems :many
SELECT r.id AS run_id, COALESCE(r.session_id, '') AS session_id, r.waiting_ask_id, t.project_id, t.workflow_id, t.id AS task_id, t.short_id, t.title, r.updated_at_unix_ms
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
WHERE trim(r.waiting_ask_id) != ''
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND t.canceled_at_unix_ms = 0
  AND (?1 = '' OR t.project_id = ?1)
  AND (?2 = '' OR t.id = ?2)
ORDER BY r.updated_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

type ListWorkflowQuestionAttentionItemsParams struct {
	ProjectID interface{}
	TaskID    interface{}
}

type ListWorkflowQuestionAttentionItemsRow struct {
	RunID           string
	SessionID       string
	WaitingAskID    string
	ProjectID       string
	WorkflowID      string
	TaskID          string
	ShortID         string
	Title           string
	UpdatedAtUnixMs int64
}

func (q *Queries) ListWorkflowQuestionAttentionItems(ctx context.Context, arg ListWorkflowQuestionAttentionItemsParams) ([]ListWorkflowQuestionAttentionItemsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowQuestionAttentionItems, arg.ProjectID, arg.TaskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowQuestionAttentionItemsRow
	for rows.Next() {
		var i ListWorkflowQuestionAttentionItemsRow
		if err := rows.Scan(
			&i.RunID,
			&i.SessionID,
			&i.WaitingAskID,
			&i.ProjectID,
			&i.WorkflowID,
			&i.TaskID,
			&i.ShortID,
			&i.Title,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowRecordsPage = `-- name: ListWorkflowRecordsPage :many
WITH workflow_list(
    id,
    name,
    description,
    version,
    created_at_unix_ms,
    updated_at_unix_ms,
    activity_at_unix_ms
) AS (
    SELECT
        workflows.id,
        workflows.name,
        workflows.description,
        workflows.version,
        workflows.created_at_unix_ms,
        workflows.updated_at_unix_ms,
        CAST(MAX(
            workflows.updated_at_unix_ms,
            COALESCE((
                SELECT MAX(task_records.updated_at_unix_ms)
                FROM task_records
                WHERE task_records.workflow_id = workflows.id
            ), 0)
        ) AS INTEGER) AS activity_at_unix_ms
    FROM workflows
    WHERE (?2 = '' OR workflows.name = ?2)
      AND (
          ?3 = ''
          OR lower(workflows.name) LIKE '%' || lower(?3) || '%'
          OR lower(workflows.description) LIKE '%' || lower(?3) || '%'
      )
      AND (
          ?4 = 0
          OR MAX(
              workflows.updated_at_unix_ms,
              COALESCE((
                  SELECT MAX(task_records.updated_at_unix_ms)
                  FROM task_records
                  WHERE task_records.workflow_id = workflows.id
              ), 0)
          ) < ?5
          OR (
              MAX(
                  workflows.updated_at_unix_ms,
                  COALESCE((
                      SELECT MAX(task_records.updated_at_unix_ms)
                      FROM task_records
                      WHERE task_records.workflow_id = workflows.id
                  ), 0)
              ) = ?5
              AND workflows.id < ?6
          )
      )
)
SELECT
    id,
    name,
    description,
    version,
    created_at_unix_ms,
    updated_at_unix_ms,
    activity_at_unix_ms
FROM workflow_list
ORDER BY activity_at_unix_ms DESC, id DESC
LIMIT ?1
`

type ListWorkflowRecordsPageParams struct {
	PageLimit              int64
	ExactName              interface{}
	SearchQuery            interface{}
	CursorActive           interface{}
	CursorActivityAtUnixMs int64
	CursorWorkflowID       string
}

type ListWorkflowRecordsPageRow struct {
	ID               string
	Name             string
	Description      string
	Version          int64
	CreatedAtUnixMs  int64
	UpdatedAtUnixMs  int64
	ActivityAtUnixMs int64
}

func (q *Queries) ListWorkflowRecordsPage(ctx context.Context, arg ListWorkflowRecordsPageParams) ([]ListWorkflowRecordsPageRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowRecordsPage,
		arg.PageLimit,
		arg.ExactName,
		arg.SearchQuery,
		arg.CursorActive,
		arg.CursorActivityAtUnixMs,
		arg.CursorWorkflowID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowRecordsPageRow
	for rows.Next() {
		var i ListWorkflowRecordsPageRow
		if err := rows.Scan(
			&i.ID,
			&i.Name,
			&i.Description,
			&i.Version,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.ActivityAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowTaskActivityRows = `-- name: ListWorkflowTaskActivityRows :many
WITH activity(
    activity_id,
    kind,
    source_id,
    occurred_at_unix_ms,
    updated_at_unix_ms,
    actor
) AS (
    SELECT
        CAST('comment:' || c.id AS TEXT) AS activity_id,
        'comment' AS kind,
        c.id AS source_id,
        c.updated_at_unix_ms AS occurred_at_unix_ms,
        c.updated_at_unix_ms AS updated_at_unix_ms,
        c.author_kind AS actor
    FROM task_comments c
    WHERE c.task_id = ?2
      AND (
          ?3 = 0
          OR c.updated_at_unix_ms < ?4
          OR (c.updated_at_unix_ms = ?4 AND ('comment:' || c.id) < ?5)
      )

    UNION ALL

    SELECT
        CAST('transition:' || tt.id AS TEXT) AS activity_id,
        'transition' AS kind,
        tt.id AS source_id,
        tt.created_at_unix_ms AS occurred_at_unix_ms,
        tt.applied_at_unix_ms AS updated_at_unix_ms,
        tt.actor AS actor
    FROM task_transitions tt
    WHERE tt.task_id = ?2
      AND (
          ?3 = 0
          OR tt.created_at_unix_ms < ?4
          OR (tt.created_at_unix_ms = ?4 AND ('transition:' || tt.id) < ?5)
      )

    UNION ALL

    SELECT
        CAST('run_started:' || r.id AS TEXT) AS activity_id,
        'run_started' AS kind,
        r.id AS source_id,
        r.started_at_unix_ms AS occurred_at_unix_ms,
        r.updated_at_unix_ms AS updated_at_unix_ms,
        '' AS actor
    FROM task_run_records r
    WHERE r.task_id = ?2
      AND r.started_at_unix_ms > 0
      AND (
          ?3 = 0
          OR r.started_at_unix_ms < ?4
          OR (r.started_at_unix_ms = ?4 AND ('run_started:' || r.id) < ?5)
      )

    UNION ALL

    SELECT
        CAST('run_completed:' || r.id AS TEXT) AS activity_id,
        'run_completed' AS kind,
        r.id AS source_id,
        r.completed_at_unix_ms AS occurred_at_unix_ms,
        r.updated_at_unix_ms AS updated_at_unix_ms,
        '' AS actor
    FROM task_run_records r
    WHERE r.task_id = ?2
      AND r.completed_at_unix_ms > 0
      AND (
          ?3 = 0
          OR r.completed_at_unix_ms < ?4
          OR (r.completed_at_unix_ms = ?4 AND ('run_completed:' || r.id) < ?5)
      )

    UNION ALL

    SELECT
        CAST('run_interrupted:' || r.id AS TEXT) AS activity_id,
        'run_interrupted' AS kind,
        r.id AS source_id,
        r.interrupted_at_unix_ms AS occurred_at_unix_ms,
        r.updated_at_unix_ms AS updated_at_unix_ms,
        '' AS actor
    FROM task_run_records r
    WHERE r.task_id = ?2
      AND r.interrupted_at_unix_ms > 0
      AND (
          ?3 = 0
          OR r.interrupted_at_unix_ms < ?4
          OR (r.interrupted_at_unix_ms = ?4 AND ('run_interrupted:' || r.id) < ?5)
      )

    UNION ALL

    SELECT
        CAST('task_canceled:' || t.id AS TEXT) AS activity_id,
        'task_canceled' AS kind,
        t.id AS source_id,
        t.canceled_at_unix_ms AS occurred_at_unix_ms,
        t.updated_at_unix_ms AS updated_at_unix_ms,
        '' AS actor
    FROM task_records t
    WHERE t.id = ?2
      AND t.canceled_at_unix_ms > 0
      AND (
          ?3 = 0
          OR t.canceled_at_unix_ms < ?4
          OR (t.canceled_at_unix_ms = ?4 AND ('task_canceled:' || t.id) < ?5)
      )
)
SELECT activity_id, kind, source_id, occurred_at_unix_ms, updated_at_unix_ms, actor
FROM activity
ORDER BY occurred_at_unix_ms DESC, activity_id DESC
LIMIT ?1
`

type ListWorkflowTaskActivityRowsParams struct {
	PageLimit              int64
	TaskID                 string
	CursorActive           interface{}
	CursorOccurredAtUnixMs int64
	CursorActivityID       string
}

type ListWorkflowTaskActivityRowsRow struct {
	ActivityID       string
	Kind             string
	SourceID         string
	OccurredAtUnixMs int64
	UpdatedAtUnixMs  int64
	Actor            string
}

func (q *Queries) ListWorkflowTaskActivityRows(ctx context.Context, arg ListWorkflowTaskActivityRowsParams) ([]ListWorkflowTaskActivityRowsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowTaskActivityRows,
		arg.PageLimit,
		arg.TaskID,
		arg.CursorActive,
		arg.CursorOccurredAtUnixMs,
		arg.CursorActivityID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowTaskActivityRowsRow
	for rows.Next() {
		var i ListWorkflowTaskActivityRowsRow
		if err := rows.Scan(
			&i.ActivityID,
			&i.Kind,
			&i.SourceID,
			&i.OccurredAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.Actor,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowTaskIDs = `-- name: ListWorkflowTaskIDs :many
SELECT id
FROM task_records
WHERE workflow_id = ?1
`

func (q *Queries) ListWorkflowTaskIDs(ctx context.Context, workflowID string) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowTaskIDs, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowTaskListRows = `-- name: ListWorkflowTaskListRows :many
WITH args AS (
    SELECT
    CAST(?1 AS INTEGER) AS status_filter_set,
    CAST(?2 AS TEXT) AS status_keys_json,
    CAST(?3 AS INTEGER) AS run_status_filter_set,
    CAST(?4 AS TEXT) AS run_statuses_json,
    CAST(?5 AS TEXT) AS visible_columns_json,
    CAST(?6 AS TEXT) AS project_id,
    CAST(?7 AS TEXT) AS workflow_id,
    CAST(?8 AS TEXT) AS canceled_terminal_node_id,
    CAST(?9 AS INTEGER) AS cursor_set,
    CAST(?10 AS TEXT) AS cursor_task_id,
    CAST(?11 AS INTEGER) AS cursor_created_at_unix_ms,
    CAST(?12 AS INTEGER) AS cursor_updated_at_unix_ms,
    CAST(?13 AS INTEGER) AS cursor_status_order,
    CAST(?14 AS INTEGER) AS cursor_run_count,
    CAST(?15 AS TEXT) AS cursor_title_sort,
    CAST(?16 AS TEXT) AS sort_1_field,
    CAST(?17 AS INTEGER) AS sort_1_desc,
    CAST(?18 AS TEXT) AS sort_2_field,
    CAST(?19 AS INTEGER) AS sort_2_desc,
    CAST(?20 AS TEXT) AS sort_3_field,
    CAST(?21 AS INTEGER) AS sort_3_desc,
    CAST(?22 AS TEXT) AS sort_4_field,
    CAST(?23 AS INTEGER) AS sort_4_desc,
    CAST(?24 AS TEXT) AS sort_5_field,
    CAST(?25 AS INTEGER) AS sort_5_desc,
    CAST(?26 AS INTEGER) AS limit_rows
),
visible_columns AS (
    SELECT
        CAST(json_extract(value, '$.node_id') AS TEXT) AS node_id,
        CAST(json_extract(value, '$.node_key') AS TEXT) AS node_key,
        CAST(json_extract(value, '$.node_kind') AS TEXT) AS node_kind,
        CAST(json_extract(value, '$.status_order') AS INTEGER) AS status_order
    FROM args, json_each(args.visible_columns_json)
),
selected_tasks AS (
    SELECT task_records.id, task_records.project_id, task_records.project_workflow_link_id, task_records.workflow_id, task_records.workflow_revision_seen, task_records.task_seq, task_records.short_id, task_records.title, task_records.body, task_records.source_url, task_records.source_workspace_id, task_records.managed_worktree_id, task_records.canceled_at_unix_ms, task_records.cancellation_reason, task_records.created_at_unix_ms, task_records.updated_at_unix_ms, task_records.metadata_json
    FROM task_records
    CROSS JOIN args
    WHERE task_records.project_id = args.project_id
      AND task_records.workflow_id = args.workflow_id
),
effective_placements AS (
    SELECT t.id AS task_id, p.id AS placement_id, p.node_id AS node_id, p.state AS state, vc.status_order AS status_order, vc.node_key AS node_key, vc.node_kind AS node_kind
    FROM selected_tasks t
    CROSS JOIN args
    JOIN task_node_placements p ON p.task_id = t.id
    JOIN visible_columns vc ON vc.node_id = p.node_id
    WHERE (
          (p.state IN ('active', 'waiting_approval') AND vc.node_kind != 'terminal')
          OR (p.state = 'completed' AND vc.node_kind = 'terminal')
      )
      AND (t.canceled_at_unix_ms = 0 OR vc.node_kind = 'terminal' OR trim(args.canceled_terminal_node_id) = '')
    UNION
    SELECT t.id AS task_id, '' AS placement_id, vc.node_id AS node_id, 'active' AS state, vc.status_order AS status_order, vc.node_key AS node_key, vc.node_kind AS node_kind
    FROM selected_tasks t
    CROSS JOIN args
    JOIN visible_columns vc ON vc.node_id = args.canceled_terminal_node_id
    WHERE t.canceled_at_unix_ms != 0
      AND trim(args.canceled_terminal_node_id) != ''
      AND NOT EXISTS (
          SELECT 1
          FROM task_node_placements p
          JOIN workflow_nodes n ON n.id = p.node_id
          WHERE p.task_id = t.id
            AND p.state = 'completed'
            AND n.kind = 'terminal'
      )
    UNION
    SELECT t.id AS task_id, 'pending-approval:' || tt.id AS placement_id, tt.source_node_id AS node_id, 'waiting_approval' AS state, vc.status_order AS status_order, vc.node_key AS node_key, vc.node_kind AS node_kind
    FROM task_transition_records tt
    JOIN selected_tasks t ON t.id = tt.task_id
    CROSS JOIN args
    JOIN visible_columns vc ON vc.node_id = tt.source_node_id
    WHERE tt.state = 'pending_approval'
      AND (t.canceled_at_unix_ms = 0 OR trim(args.canceled_terminal_node_id) = '')
),
per_task_status AS (
    SELECT task_id, MIN(status_order) AS status_order
    FROM effective_placements
    GROUP BY task_id
),
run_counts AS (
    SELECT r.task_id, COUNT(*) AS run_count
    FROM task_run_records r
    JOIN selected_tasks t ON t.id = r.task_id
    GROUP BY r.task_id
)
SELECT
    t.id, t.project_id, t.project_workflow_link_id, t.workflow_id, t.workflow_revision_seen, t.task_seq, t.short_id, t.title, t.body, t.source_url, t.source_workspace_id, t.managed_worktree_id, t.canceled_at_unix_ms, t.cancellation_reason, t.created_at_unix_ms, t.updated_at_unix_ms, t.metadata_json,
    CAST(pts.status_order AS INTEGER) AS status_order,
    CAST(COALESCE(rc.run_count, 0) AS INTEGER) AS run_count,
    CASE
        WHEN t.canceled_at_unix_ms != 0 THEN 'canceled'
        WHEN EXISTS (SELECT 1 FROM effective_placements ep_done WHERE ep_done.task_id = t.id AND ep_done.node_kind = 'terminal') THEN 'done'
        WHEN EXISTS (SELECT 1 FROM effective_placements ep_waiting WHERE ep_waiting.task_id = t.id AND ep_waiting.state = 'waiting_approval')
          OR EXISTS (
              SELECT 1
              FROM task_run_records r
              JOIN effective_placements ep_run ON ep_run.placement_id = r.placement_id
              WHERE ep_run.task_id = t.id
                AND r.completed_at_unix_ms = 0
                AND (r.started_at_unix_ms != 0 OR r.interrupted_at_unix_ms != 0 OR trim(r.waiting_ask_id) != '')
          ) THEN 'running'
        ELSE 'open'
    END AS run_status,
    LOWER(t.title) AS title_sort
FROM selected_tasks t
CROSS JOIN args
JOIN per_task_status pts ON pts.task_id = t.id
LEFT JOIN run_counts rc ON rc.task_id = t.id
GROUP BY t.id
HAVING (
    args.status_filter_set = 0
    OR EXISTS (SELECT 1 FROM effective_placements ep_filter WHERE ep_filter.task_id = t.id AND ep_filter.node_key IN (SELECT value FROM json_each(args.status_keys_json)))
)
  AND (
    args.run_status_filter_set = 0
    OR run_status IN (SELECT value FROM json_each(args.run_statuses_json))
)
  AND (
    args.cursor_set = 0
    OR (((args.sort_1_field = 'created' AND ((args.sort_1_desc = 0 AND created_at_unix_ms > args.cursor_created_at_unix_ms) OR (args.sort_1_desc != 0 AND created_at_unix_ms < args.cursor_created_at_unix_ms))) OR (args.sort_1_field = 'updated' AND ((args.sort_1_desc = 0 AND updated_at_unix_ms > args.cursor_updated_at_unix_ms) OR (args.sort_1_desc != 0 AND updated_at_unix_ms < args.cursor_updated_at_unix_ms))) OR (args.sort_1_field = 'status' AND ((args.sort_1_desc = 0 AND CAST(pts.status_order AS INTEGER) > args.cursor_status_order) OR (args.sort_1_desc != 0 AND CAST(pts.status_order AS INTEGER) < args.cursor_status_order))) OR (args.sort_1_field = 'run_count' AND ((args.sort_1_desc = 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) > args.cursor_run_count) OR (args.sort_1_desc != 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) < args.cursor_run_count))) OR (args.sort_1_field = 'title' AND ((args.sort_1_desc = 0 AND title_sort > args.cursor_title_sort) OR (args.sort_1_desc != 0 AND title_sort < args.cursor_title_sort)))))
        OR ((args.sort_1_field = '' OR (args.sort_1_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_1_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_1_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_1_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_1_field = 'title' AND title_sort = args.cursor_title_sort)) AND ((args.sort_2_field = 'created' AND ((args.sort_2_desc = 0 AND created_at_unix_ms > args.cursor_created_at_unix_ms) OR (args.sort_2_desc != 0 AND created_at_unix_ms < args.cursor_created_at_unix_ms))) OR (args.sort_2_field = 'updated' AND ((args.sort_2_desc = 0 AND updated_at_unix_ms > args.cursor_updated_at_unix_ms) OR (args.sort_2_desc != 0 AND updated_at_unix_ms < args.cursor_updated_at_unix_ms))) OR (args.sort_2_field = 'status' AND ((args.sort_2_desc = 0 AND CAST(pts.status_order AS INTEGER) > args.cursor_status_order) OR (args.sort_2_desc != 0 AND CAST(pts.status_order AS INTEGER) < args.cursor_status_order))) OR (args.sort_2_field = 'run_count' AND ((args.sort_2_desc = 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) > args.cursor_run_count) OR (args.sort_2_desc != 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) < args.cursor_run_count))) OR (args.sort_2_field = 'title' AND ((args.sort_2_desc = 0 AND title_sort > args.cursor_title_sort) OR (args.sort_2_desc != 0 AND title_sort < args.cursor_title_sort)))))
        OR ((args.sort_1_field = '' OR (args.sort_1_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_1_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_1_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_1_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_1_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_2_field = '' OR (args.sort_2_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_2_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_2_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_2_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_2_field = 'title' AND title_sort = args.cursor_title_sort)) AND ((args.sort_3_field = 'created' AND ((args.sort_3_desc = 0 AND created_at_unix_ms > args.cursor_created_at_unix_ms) OR (args.sort_3_desc != 0 AND created_at_unix_ms < args.cursor_created_at_unix_ms))) OR (args.sort_3_field = 'updated' AND ((args.sort_3_desc = 0 AND updated_at_unix_ms > args.cursor_updated_at_unix_ms) OR (args.sort_3_desc != 0 AND updated_at_unix_ms < args.cursor_updated_at_unix_ms))) OR (args.sort_3_field = 'status' AND ((args.sort_3_desc = 0 AND CAST(pts.status_order AS INTEGER) > args.cursor_status_order) OR (args.sort_3_desc != 0 AND CAST(pts.status_order AS INTEGER) < args.cursor_status_order))) OR (args.sort_3_field = 'run_count' AND ((args.sort_3_desc = 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) > args.cursor_run_count) OR (args.sort_3_desc != 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) < args.cursor_run_count))) OR (args.sort_3_field = 'title' AND ((args.sort_3_desc = 0 AND title_sort > args.cursor_title_sort) OR (args.sort_3_desc != 0 AND title_sort < args.cursor_title_sort)))))
        OR ((args.sort_1_field = '' OR (args.sort_1_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_1_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_1_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_1_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_1_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_2_field = '' OR (args.sort_2_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_2_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_2_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_2_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_2_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_3_field = '' OR (args.sort_3_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_3_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_3_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_3_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_3_field = 'title' AND title_sort = args.cursor_title_sort)) AND ((args.sort_4_field = 'created' AND ((args.sort_4_desc = 0 AND created_at_unix_ms > args.cursor_created_at_unix_ms) OR (args.sort_4_desc != 0 AND created_at_unix_ms < args.cursor_created_at_unix_ms))) OR (args.sort_4_field = 'updated' AND ((args.sort_4_desc = 0 AND updated_at_unix_ms > args.cursor_updated_at_unix_ms) OR (args.sort_4_desc != 0 AND updated_at_unix_ms < args.cursor_updated_at_unix_ms))) OR (args.sort_4_field = 'status' AND ((args.sort_4_desc = 0 AND CAST(pts.status_order AS INTEGER) > args.cursor_status_order) OR (args.sort_4_desc != 0 AND CAST(pts.status_order AS INTEGER) < args.cursor_status_order))) OR (args.sort_4_field = 'run_count' AND ((args.sort_4_desc = 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) > args.cursor_run_count) OR (args.sort_4_desc != 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) < args.cursor_run_count))) OR (args.sort_4_field = 'title' AND ((args.sort_4_desc = 0 AND title_sort > args.cursor_title_sort) OR (args.sort_4_desc != 0 AND title_sort < args.cursor_title_sort)))))
        OR ((args.sort_1_field = '' OR (args.sort_1_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_1_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_1_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_1_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_1_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_2_field = '' OR (args.sort_2_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_2_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_2_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_2_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_2_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_3_field = '' OR (args.sort_3_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_3_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_3_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_3_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_3_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_4_field = '' OR (args.sort_4_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_4_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_4_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_4_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_4_field = 'title' AND title_sort = args.cursor_title_sort)) AND ((args.sort_5_field = 'created' AND ((args.sort_5_desc = 0 AND created_at_unix_ms > args.cursor_created_at_unix_ms) OR (args.sort_5_desc != 0 AND created_at_unix_ms < args.cursor_created_at_unix_ms))) OR (args.sort_5_field = 'updated' AND ((args.sort_5_desc = 0 AND updated_at_unix_ms > args.cursor_updated_at_unix_ms) OR (args.sort_5_desc != 0 AND updated_at_unix_ms < args.cursor_updated_at_unix_ms))) OR (args.sort_5_field = 'status' AND ((args.sort_5_desc = 0 AND CAST(pts.status_order AS INTEGER) > args.cursor_status_order) OR (args.sort_5_desc != 0 AND CAST(pts.status_order AS INTEGER) < args.cursor_status_order))) OR (args.sort_5_field = 'run_count' AND ((args.sort_5_desc = 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) > args.cursor_run_count) OR (args.sort_5_desc != 0 AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) < args.cursor_run_count))) OR (args.sort_5_field = 'title' AND ((args.sort_5_desc = 0 AND title_sort > args.cursor_title_sort) OR (args.sort_5_desc != 0 AND title_sort < args.cursor_title_sort)))))
        OR ((args.sort_1_field = '' OR (args.sort_1_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_1_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_1_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_1_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_1_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_2_field = '' OR (args.sort_2_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_2_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_2_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_2_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_2_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_3_field = '' OR (args.sort_3_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_3_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_3_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_3_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_3_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_4_field = '' OR (args.sort_4_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_4_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_4_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_4_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_4_field = 'title' AND title_sort = args.cursor_title_sort)) AND (args.sort_5_field = '' OR (args.sort_5_field = 'created' AND created_at_unix_ms = args.cursor_created_at_unix_ms) OR (args.sort_5_field = 'updated' AND updated_at_unix_ms = args.cursor_updated_at_unix_ms) OR (args.sort_5_field = 'status' AND CAST(pts.status_order AS INTEGER) = args.cursor_status_order) OR (args.sort_5_field = 'run_count' AND CAST(COALESCE(rc.run_count, 0) AS INTEGER) = args.cursor_run_count) OR (args.sort_5_field = 'title' AND title_sort = args.cursor_title_sort)) AND id > args.cursor_task_id)
)
ORDER BY
    CASE WHEN args.sort_1_field = 'created' AND args.sort_1_desc = 0 THEN created_at_unix_ms WHEN args.sort_1_field = 'updated' AND args.sort_1_desc = 0 THEN updated_at_unix_ms WHEN args.sort_1_field = 'status' AND args.sort_1_desc = 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_1_field = 'run_count' AND args.sort_1_desc = 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END ASC,
    CASE WHEN args.sort_1_field = 'title' AND args.sort_1_desc = 0 THEN title_sort END ASC,
    CASE WHEN args.sort_1_field = 'created' AND args.sort_1_desc != 0 THEN created_at_unix_ms WHEN args.sort_1_field = 'updated' AND args.sort_1_desc != 0 THEN updated_at_unix_ms WHEN args.sort_1_field = 'status' AND args.sort_1_desc != 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_1_field = 'run_count' AND args.sort_1_desc != 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END DESC,
    CASE WHEN args.sort_1_field = 'title' AND args.sort_1_desc != 0 THEN title_sort END DESC,
    CASE WHEN args.sort_2_field = 'created' AND args.sort_2_desc = 0 THEN created_at_unix_ms WHEN args.sort_2_field = 'updated' AND args.sort_2_desc = 0 THEN updated_at_unix_ms WHEN args.sort_2_field = 'status' AND args.sort_2_desc = 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_2_field = 'run_count' AND args.sort_2_desc = 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END ASC,
    CASE WHEN args.sort_2_field = 'title' AND args.sort_2_desc = 0 THEN title_sort END ASC,
    CASE WHEN args.sort_2_field = 'created' AND args.sort_2_desc != 0 THEN created_at_unix_ms WHEN args.sort_2_field = 'updated' AND args.sort_2_desc != 0 THEN updated_at_unix_ms WHEN args.sort_2_field = 'status' AND args.sort_2_desc != 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_2_field = 'run_count' AND args.sort_2_desc != 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END DESC,
    CASE WHEN args.sort_2_field = 'title' AND args.sort_2_desc != 0 THEN title_sort END DESC,
    CASE WHEN args.sort_3_field = 'created' AND args.sort_3_desc = 0 THEN created_at_unix_ms WHEN args.sort_3_field = 'updated' AND args.sort_3_desc = 0 THEN updated_at_unix_ms WHEN args.sort_3_field = 'status' AND args.sort_3_desc = 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_3_field = 'run_count' AND args.sort_3_desc = 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END ASC,
    CASE WHEN args.sort_3_field = 'title' AND args.sort_3_desc = 0 THEN title_sort END ASC,
    CASE WHEN args.sort_3_field = 'created' AND args.sort_3_desc != 0 THEN created_at_unix_ms WHEN args.sort_3_field = 'updated' AND args.sort_3_desc != 0 THEN updated_at_unix_ms WHEN args.sort_3_field = 'status' AND args.sort_3_desc != 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_3_field = 'run_count' AND args.sort_3_desc != 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END DESC,
    CASE WHEN args.sort_3_field = 'title' AND args.sort_3_desc != 0 THEN title_sort END DESC,
    CASE WHEN args.sort_4_field = 'created' AND args.sort_4_desc = 0 THEN created_at_unix_ms WHEN args.sort_4_field = 'updated' AND args.sort_4_desc = 0 THEN updated_at_unix_ms WHEN args.sort_4_field = 'status' AND args.sort_4_desc = 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_4_field = 'run_count' AND args.sort_4_desc = 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END ASC,
    CASE WHEN args.sort_4_field = 'title' AND args.sort_4_desc = 0 THEN title_sort END ASC,
    CASE WHEN args.sort_4_field = 'created' AND args.sort_4_desc != 0 THEN created_at_unix_ms WHEN args.sort_4_field = 'updated' AND args.sort_4_desc != 0 THEN updated_at_unix_ms WHEN args.sort_4_field = 'status' AND args.sort_4_desc != 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_4_field = 'run_count' AND args.sort_4_desc != 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END DESC,
    CASE WHEN args.sort_4_field = 'title' AND args.sort_4_desc != 0 THEN title_sort END DESC,
    CASE WHEN args.sort_5_field = 'created' AND args.sort_5_desc = 0 THEN created_at_unix_ms WHEN args.sort_5_field = 'updated' AND args.sort_5_desc = 0 THEN updated_at_unix_ms WHEN args.sort_5_field = 'status' AND args.sort_5_desc = 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_5_field = 'run_count' AND args.sort_5_desc = 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END ASC,
    CASE WHEN args.sort_5_field = 'title' AND args.sort_5_desc = 0 THEN title_sort END ASC,
    CASE WHEN args.sort_5_field = 'created' AND args.sort_5_desc != 0 THEN created_at_unix_ms WHEN args.sort_5_field = 'updated' AND args.sort_5_desc != 0 THEN updated_at_unix_ms WHEN args.sort_5_field = 'status' AND args.sort_5_desc != 0 THEN CAST(pts.status_order AS INTEGER) WHEN args.sort_5_field = 'run_count' AND args.sort_5_desc != 0 THEN CAST(COALESCE(rc.run_count, 0) AS INTEGER) END DESC,
    CASE WHEN args.sort_5_field = 'title' AND args.sort_5_desc != 0 THEN title_sort END DESC,
    id ASC
LIMIT (SELECT limit_rows FROM args)
`

type ListWorkflowTaskListRowsParams struct {
	StatusFilterSet        int64
	StatusKeysJson         string
	RunStatusFilterSet     int64
	RunStatusesJson        string
	VisibleColumnsJson     string
	ProjectID              string
	WorkflowID             string
	CanceledTerminalNodeID string
	CursorSet              int64
	CursorTaskID           string
	CursorCreatedAtUnixMs  int64
	CursorUpdatedAtUnixMs  int64
	CursorStatusOrder      int64
	CursorRunCount         int64
	CursorTitleSort        string
	Sort1Field             string
	Sort1Desc              int64
	Sort2Field             string
	Sort2Desc              int64
	Sort3Field             string
	Sort3Desc              int64
	Sort4Field             string
	Sort4Desc              int64
	Sort5Field             string
	Sort5Desc              int64
	LimitRows              int64
}

type ListWorkflowTaskListRowsRow struct {
	ID                    string
	ProjectID             string
	ProjectWorkflowLinkID string
	WorkflowID            string
	WorkflowRevisionSeen  int64
	TaskSeq               int64
	ShortID               string
	Title                 string
	Body                  string
	SourceUrl             string
	SourceWorkspaceID     sql.NullString
	ManagedWorktreeID     sql.NullString
	CanceledAtUnixMs      int64
	CancellationReason    string
	CreatedAtUnixMs       int64
	UpdatedAtUnixMs       int64
	MetadataJson          string
	StatusOrder           int64
	RunCount              int64
	RunStatus             string
	TitleSort             string
}

func (q *Queries) ListWorkflowTaskListRows(ctx context.Context, arg ListWorkflowTaskListRowsParams) ([]ListWorkflowTaskListRowsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowTaskListRows,
		arg.StatusFilterSet,
		arg.StatusKeysJson,
		arg.RunStatusFilterSet,
		arg.RunStatusesJson,
		arg.VisibleColumnsJson,
		arg.ProjectID,
		arg.WorkflowID,
		arg.CanceledTerminalNodeID,
		arg.CursorSet,
		arg.CursorTaskID,
		arg.CursorCreatedAtUnixMs,
		arg.CursorUpdatedAtUnixMs,
		arg.CursorStatusOrder,
		arg.CursorRunCount,
		arg.CursorTitleSort,
		arg.Sort1Field,
		arg.Sort1Desc,
		arg.Sort2Field,
		arg.Sort2Desc,
		arg.Sort3Field,
		arg.Sort3Desc,
		arg.Sort4Field,
		arg.Sort4Desc,
		arg.Sort5Field,
		arg.Sort5Desc,
		arg.LimitRows,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowTaskListRowsRow
	for rows.Next() {
		var i ListWorkflowTaskListRowsRow
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.ProjectWorkflowLinkID,
			&i.WorkflowID,
			&i.WorkflowRevisionSeen,
			&i.TaskSeq,
			&i.ShortID,
			&i.Title,
			&i.Body,
			&i.SourceUrl,
			&i.SourceWorkspaceID,
			&i.ManagedWorktreeID,
			&i.CanceledAtUnixMs,
			&i.CancellationReason,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.MetadataJson,
			&i.StatusOrder,
			&i.RunCount,
			&i.RunStatus,
			&i.TitleSort,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowTransitionGroups = `-- name: ListWorkflowTransitionGroups :many
SELECT
    tg.id,
    source.workflow_id AS workflow_id,
    tg.source_node_id,
    tg.transition_id,
    tg.display_name,
    tg.description,
    tg.sort_order
FROM workflow_transition_groups tg
JOIN workflow_nodes source ON source.id = tg.source_node_id
WHERE source.workflow_id = ?1
ORDER BY tg.sort_order ASC, tg.rowid ASC
`

type ListWorkflowTransitionGroupsRow struct {
	ID           string
	WorkflowID   string
	SourceNodeID string
	TransitionID string
	DisplayName  string
	Description  string
	SortOrder    int64
}

func (q *Queries) ListWorkflowTransitionGroups(ctx context.Context, workflowID string) ([]ListWorkflowTransitionGroupsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowTransitionGroups, workflowID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowTransitionGroupsRow
	for rows.Next() {
		var i ListWorkflowTransitionGroupsRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkflowID,
			&i.SourceNodeID,
			&i.TransitionID,
			&i.DisplayName,
			&i.Description,
			&i.SortOrder,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowValidationAttentionItems = `-- name: ListWorkflowValidationAttentionItems :many
SELECT project_id, workflow_id, updated_at_unix_ms
FROM project_workflow_links
WHERE (?1 = '' OR project_id = ?1)
ORDER BY updated_at_unix_ms DESC, rowid DESC
`

type ListWorkflowValidationAttentionItemsRow struct {
	ProjectID       string
	WorkflowID      string
	UpdatedAtUnixMs int64
}

func (q *Queries) ListWorkflowValidationAttentionItems(ctx context.Context, projectID interface{}) ([]ListWorkflowValidationAttentionItemsRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflowValidationAttentionItems, projectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkflowValidationAttentionItemsRow
	for rows.Next() {
		var i ListWorkflowValidationAttentionItemsRow
		if err := rows.Scan(&i.ProjectID, &i.WorkflowID, &i.UpdatedAtUnixMs); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflows = `-- name: ListWorkflows :many
SELECT
    id,
    name,
    description,
    version,
    created_at_unix_ms,
    updated_at_unix_ms
FROM workflows
ORDER BY updated_at_unix_ms DESC, rowid DESC
`

func (q *Queries) ListWorkflows(ctx context.Context) ([]Workflow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkflows)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workflow
	for rows.Next() {
		var i Workflow
		if err := rows.Scan(
			&i.ID,
			&i.Name,
			&i.Description,
			&i.Version,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkspaceBindingsByCanonicalRoot = `-- name: ListWorkspaceBindingsByCanonicalRoot :many
SELECT
    p.id AS project_id,
    p.display_name AS project_display_name,
    p.project_key,
    w.id AS workspace_id,
    w.canonical_root_path AS workspace_root
FROM workspaces w
JOIN projects p ON p.id = w.project_id
WHERE w.canonical_root_path = ?1
ORDER BY p.created_at_unix_ms ASC, p.rowid ASC, w.created_at_unix_ms ASC, w.rowid ASC
`

type ListWorkspaceBindingsByCanonicalRootRow struct {
	ProjectID          string
	ProjectDisplayName string
	ProjectKey         string
	WorkspaceID        string
	WorkspaceRoot      string
}

func (q *Queries) ListWorkspaceBindingsByCanonicalRoot(ctx context.Context, canonicalRootPath string) ([]ListWorkspaceBindingsByCanonicalRootRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorkspaceBindingsByCanonicalRoot, canonicalRootPath)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorkspaceBindingsByCanonicalRootRow
	for rows.Next() {
		var i ListWorkspaceBindingsByCanonicalRootRow
		if err := rows.Scan(
			&i.ProjectID,
			&i.ProjectDisplayName,
			&i.ProjectKey,
			&i.WorkspaceID,
			&i.WorkspaceRoot,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkspaceSessionIDs = `-- name: ListWorkspaceSessionIDs :many
SELECT id
FROM sessions
WHERE workspace_id = ?1
ORDER BY rowid ASC
`

func (q *Queries) ListWorkspaceSessionIDs(ctx context.Context, workspaceID sql.NullString) ([]string, error) {
	rows, err := q.db.QueryContext(ctx, listWorkspaceSessionIDs, workspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []string
	for rows.Next() {
		var id string
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkspacesByCanonicalRoot = `-- name: ListWorkspacesByCanonicalRoot :many
SELECT
    id,
    project_id,
    canonical_root_path,
    git_metadata_json,
    created_at_unix_ms,
    updated_at_unix_ms
FROM workspaces
WHERE canonical_root_path = ?1
ORDER BY created_at_unix_ms ASC, rowid ASC
`

func (q *Queries) ListWorkspacesByCanonicalRoot(ctx context.Context, canonicalRootPath string) ([]Workspace, error) {
	rows, err := q.db.QueryContext(ctx, listWorkspacesByCanonicalRoot, canonicalRootPath)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []Workspace
	for rows.Next() {
		var i Workspace
		if err := rows.Scan(
			&i.ID,
			&i.ProjectID,
			&i.CanonicalRootPath,
			&i.GitMetadataJson,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorktreesByWorkspaceID = `-- name: ListWorktreesByWorkspaceID :many
SELECT
    wt.id,
    wt.workspace_id,
    wt.canonical_root_path,
    CASE WHEN wt.canonical_root_path = w.canonical_root_path THEN 1 ELSE 0 END AS is_main,
    wt.managed,
    wt.created_branch,
    wt.origin_session_id,
    wt.git_metadata_json,
    wt.created_at_unix_ms,
    wt.updated_at_unix_ms
FROM worktrees wt
JOIN workspaces w ON w.id = wt.workspace_id
WHERE wt.workspace_id = ?1
ORDER BY wt.created_at_unix_ms ASC, wt.rowid ASC
`

type ListWorktreesByWorkspaceIDRow struct {
	ID                string
	WorkspaceID       string
	CanonicalRootPath string
	IsMain            int64
	Managed           int64
	CreatedBranch     int64
	OriginSessionID   string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) ListWorktreesByWorkspaceID(ctx context.Context, workspaceID string) ([]ListWorktreesByWorkspaceIDRow, error) {
	rows, err := q.db.QueryContext(ctx, listWorktreesByWorkspaceID, workspaceID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListWorktreesByWorkspaceIDRow
	for rows.Next() {
		var i ListWorktreesByWorkspaceIDRow
		if err := rows.Scan(
			&i.ID,
			&i.WorkspaceID,
			&i.CanonicalRootPath,
			&i.IsMain,
			&i.Managed,
			&i.CreatedBranch,
			&i.OriginSessionID,
			&i.GitMetadataJson,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const recordInvalidCompletionProtocolViolation = `-- name: RecordInvalidCompletionProtocolViolation :one
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    invalid_completion_count = invalid_completion_count + 1,
    interrupted_at_unix_ms = CASE WHEN invalid_completion_count + 1 >= ?2 THEN ?3 ELSE interrupted_at_unix_ms END,
    interruption_reason = CASE WHEN invalid_completion_count + 1 >= ?2 THEN 'workflow_protocol_violation_limit' ELSE interruption_reason END,
    interruption_detail_json = CASE WHEN invalid_completion_count + 1 >= ?2 THEN ?4 ELSE interruption_detail_json END
WHERE id = ?5
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND (?6 = 0 OR run_generation = ?7)
RETURNING invalid_completion_count, interrupted_at_unix_ms
`

type RecordInvalidCompletionProtocolViolationParams struct {
	UpdatedAtUnixMs        int64
	MaxCount               int64
	InterruptedAtUnixMs    int64
	InterruptionDetailJson string
	RunID                  string
	RequireGeneration      interface{}
	ExpectedGeneration     int64
}

type RecordInvalidCompletionProtocolViolationRow struct {
	InvalidCompletionCount int64
	InterruptedAtUnixMs    int64
}

func (q *Queries) RecordInvalidCompletionProtocolViolation(ctx context.Context, arg RecordInvalidCompletionProtocolViolationParams) (RecordInvalidCompletionProtocolViolationRow, error) {
	row := q.db.QueryRowContext(ctx, recordInvalidCompletionProtocolViolation,
		arg.UpdatedAtUnixMs,
		arg.MaxCount,
		arg.InterruptedAtUnixMs,
		arg.InterruptionDetailJson,
		arg.RunID,
		arg.RequireGeneration,
		arg.ExpectedGeneration,
	)
	var i RecordInvalidCompletionProtocolViolationRow
	err := row.Scan(&i.InvalidCompletionCount, &i.InterruptedAtUnixMs)
	return i, err
}

const rejectPendingApprovalTransition = `-- name: RejectPendingApprovalTransition :execrows
UPDATE task_transitions
SET state = 'rejected'
WHERE id = ?1
  AND state = 'pending_approval'
`

func (q *Queries) RejectPendingApprovalTransition(ctx context.Context, transitionID string) (int64, error) {
	result, err := q.db.ExecContext(ctx, rejectPendingApprovalTransition, transitionID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const resolveActiveRunCompletionTargetByProjectShortID = `-- name: ResolveActiveRunCompletionTargetByProjectShortID :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND trim(COALESCE(r.session_id, '')) != ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND t.short_id = ?1
  AND t.project_id = ?2
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

type ResolveActiveRunCompletionTargetByProjectShortIDParams struct {
	ShortID   string
	ProjectID string
}

func (q *Queries) ResolveActiveRunCompletionTargetByProjectShortID(ctx context.Context, arg ResolveActiveRunCompletionTargetByProjectShortIDParams) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveActiveRunCompletionTargetByProjectShortID, arg.ShortID, arg.ProjectID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resolveActiveRunCompletionTargetByRunID = `-- name: ResolveActiveRunCompletionTargetByRunID :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND trim(COALESCE(r.session_id, '')) != ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND r.id = ?1
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

func (q *Queries) ResolveActiveRunCompletionTargetByRunID(ctx context.Context, runID string) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveActiveRunCompletionTargetByRunID, runID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resolveActiveRunCompletionTargetBySessionID = `-- name: ResolveActiveRunCompletionTargetBySessionID :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND trim(COALESCE(r.session_id, '')) != ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND r.session_id = ?1
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

func (q *Queries) ResolveActiveRunCompletionTargetBySessionID(ctx context.Context, sessionID sql.NullString) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveActiveRunCompletionTargetBySessionID, sessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resolveActiveRunCompletionTargetByShortID = `-- name: ResolveActiveRunCompletionTargetByShortID :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND trim(COALESCE(r.session_id, '')) != ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND t.short_id = ?1
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

func (q *Queries) ResolveActiveRunCompletionTargetByShortID(ctx context.Context, shortID string) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveActiveRunCompletionTargetByShortID, shortID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resolveActiveRunCompletionTargetByTaskID = `-- name: ResolveActiveRunCompletionTargetByTaskID :many
SELECT
    r.id,
    r.task_id,
    r.placement_id,
    r.node_id,
    r.session_id,
    r.run_generation,
    r.workflow_revision_seen,
    r.automation_requested_at_unix_ms,
    r.created_at_unix_ms,
    r.updated_at_unix_ms,
    r.started_at_unix_ms,
    r.completed_at_unix_ms,
    r.interrupted_at_unix_ms,
    r.interruption_reason,
    r.interruption_detail_json,
    r.waiting_ask_id,
    r.effective_completion_mode,
    r.invalid_completion_count,
    r.run_start_snapshot_json,
    r.metadata_json
FROM task_run_records r
JOIN task_records t ON t.id = r.task_id
JOIN task_node_placements p ON p.id = r.placement_id
JOIN workflow_nodes n ON n.id = r.node_id
WHERE r.started_at_unix_ms > 0
  AND r.completed_at_unix_ms = 0
  AND r.interrupted_at_unix_ms = 0
  AND trim(COALESCE(r.session_id, '')) != ''
  AND t.canceled_at_unix_ms = 0
  AND p.state = 'active'
  AND n.kind IN ('agent', 'script')
  AND t.id = ?1
ORDER BY r.started_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = r.id
) DESC
`

func (q *Queries) ResolveActiveRunCompletionTargetByTaskID(ctx context.Context, taskID string) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveActiveRunCompletionTargetByTaskID, taskID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resolveTaskWaitingAsk = `-- name: ResolveTaskWaitingAsk :many
SELECT
    id,
    task_id,
    placement_id,
    node_id,
    session_id,
    run_generation,
    workflow_revision_seen,
    automation_requested_at_unix_ms,
    created_at_unix_ms,
    updated_at_unix_ms,
    started_at_unix_ms,
    completed_at_unix_ms,
    interrupted_at_unix_ms,
    interruption_reason,
    interruption_detail_json,
    waiting_ask_id,
    effective_completion_mode,
    invalid_completion_count,
    run_start_snapshot_json,
    metadata_json
FROM task_run_records
WHERE task_id = ?1
  AND waiting_ask_id = ?2
  AND (?3 = '' OR id = ?3)
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND trim(COALESCE(session_id, '')) != ''
ORDER BY updated_at_unix_ms DESC, (
    SELECT storage.rowid
    FROM task_runs storage
    WHERE storage.id = task_run_records.id
) DESC
`

type ResolveTaskWaitingAskParams struct {
	TaskID string
	AskID  string
	RunID  interface{}
}

func (q *Queries) ResolveTaskWaitingAsk(ctx context.Context, arg ResolveTaskWaitingAskParams) ([]TaskRunRecord, error) {
	rows, err := q.db.QueryContext(ctx, resolveTaskWaitingAsk, arg.TaskID, arg.AskID, arg.RunID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []TaskRunRecord
	for rows.Next() {
		var i TaskRunRecord
		if err := rows.Scan(
			&i.ID,
			&i.TaskID,
			&i.PlacementID,
			&i.NodeID,
			&i.SessionID,
			&i.RunGeneration,
			&i.WorkflowRevisionSeen,
			&i.AutomationRequestedAtUnixMs,
			&i.CreatedAtUnixMs,
			&i.UpdatedAtUnixMs,
			&i.StartedAtUnixMs,
			&i.CompletedAtUnixMs,
			&i.InterruptedAtUnixMs,
			&i.InterruptionReason,
			&i.InterruptionDetailJson,
			&i.WaitingAskID,
			&i.EffectiveCompletionMode,
			&i.InvalidCompletionCount,
			&i.RunStartSnapshotJson,
			&i.MetadataJson,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Close(); err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const resumeTaskRun = `-- name: ResumeTaskRun :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    started_at_unix_ms = 0,
    interrupted_at_unix_ms = 0,
    interruption_reason = '',
    interruption_detail_json = '{}',
    waiting_ask_id = '',
    run_generation = run_generation + 1
WHERE id = ?2
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms > 0
`

type ResumeTaskRunParams struct {
	UpdatedAtUnixMs int64
	RunID           string
}

func (q *Queries) ResumeTaskRun(ctx context.Context, arg ResumeTaskRunParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, resumeTaskRun, arg.UpdatedAtUnixMs, arg.RunID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setProjectDefaultWorkflowLink = `-- name: SetProjectDefaultWorkflowLink :execrows
UPDATE projects
SET
    default_project_workflow_link_id = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type SetProjectDefaultWorkflowLinkParams struct {
	ProjectWorkflowLinkID string
	UpdatedAtUnixMs       int64
	ProjectID             string
}

func (q *Queries) SetProjectDefaultWorkflowLink(ctx context.Context, arg SetProjectDefaultWorkflowLinkParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setProjectDefaultWorkflowLink, arg.ProjectWorkflowLinkID, arg.UpdatedAtUnixMs, arg.ProjectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setProjectDisplayName = `-- name: SetProjectDisplayName :execrows
UPDATE projects
SET
    display_name = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type SetProjectDisplayNameParams struct {
	DisplayName     string
	UpdatedAtUnixMs int64
	ProjectID       string
}

func (q *Queries) SetProjectDisplayName(ctx context.Context, arg SetProjectDisplayNameParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setProjectDisplayName, arg.DisplayName, arg.UpdatedAtUnixMs, arg.ProjectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setProjectKey = `-- name: SetProjectKey :execrows
UPDATE projects
SET
    project_key = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type SetProjectKeyParams struct {
	ProjectKey      string
	UpdatedAtUnixMs int64
	ProjectID       string
}

func (q *Queries) SetProjectKey(ctx context.Context, arg SetProjectKeyParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setProjectKey, arg.ProjectKey, arg.UpdatedAtUnixMs, arg.ProjectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setProjectPrimaryWorkspace = `-- name: SetProjectPrimaryWorkspace :execrows
UPDATE projects
SET
    primary_workspace_id = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type SetProjectPrimaryWorkspaceParams struct {
	WorkspaceID     string
	UpdatedAtUnixMs int64
	ProjectID       string
}

func (q *Queries) SetProjectPrimaryWorkspace(ctx context.Context, arg SetProjectPrimaryWorkspaceParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setProjectPrimaryWorkspace, arg.WorkspaceID, arg.UpdatedAtUnixMs, arg.ProjectID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setRunWaitingAsk = `-- name: SetRunWaitingAsk :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    waiting_ask_id = ?2
WHERE id = ?3
  AND run_generation = ?4
  AND started_at_unix_ms > 0
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND waiting_ask_id = ''
`

type SetRunWaitingAskParams struct {
	UpdatedAtUnixMs int64
	AskID           string
	RunID           string
	RunGeneration   int64
}

func (q *Queries) SetRunWaitingAsk(ctx context.Context, arg SetRunWaitingAskParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setRunWaitingAsk,
		arg.UpdatedAtUnixMs,
		arg.AskID,
		arg.RunID,
		arg.RunGeneration,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const setTaskRunEffectiveCompletionMode = `-- name: SetTaskRunEffectiveCompletionMode :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    effective_completion_mode = ?2
WHERE id = ?3
  AND run_generation = ?4
  AND completed_at_unix_ms = 0
  AND interrupted_at_unix_ms = 0
  AND (
      effective_completion_mode = ''
      OR effective_completion_mode = ?2
  )
`

type SetTaskRunEffectiveCompletionModeParams struct {
	UpdatedAtUnixMs         int64
	EffectiveCompletionMode string
	ID                      string
	ExpectedGeneration      int64
}

func (q *Queries) SetTaskRunEffectiveCompletionMode(ctx context.Context, arg SetTaskRunEffectiveCompletionModeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, setTaskRunEffectiveCompletionMode,
		arg.UpdatedAtUnixMs,
		arg.EffectiveCompletionMode,
		arg.ID,
		arg.ExpectedGeneration,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const startTaskCompleteStartPlacement = `-- name: StartTaskCompleteStartPlacement :execrows
UPDATE task_node_placements
SET state = ?1, updated_at_unix_ms = ?2
WHERE task_node_placements.id = ?3
  AND state = 'active'
  AND task_id IN (
      SELECT tasks.id
      FROM tasks
      WHERE tasks.id = ?4
        AND tasks.canceled_at_unix_ms = 0
  )
`

type StartTaskCompleteStartPlacementParams struct {
	State           string
	UpdatedAtUnixMs int64
	PlacementID     string
	TaskID          string
}

func (q *Queries) StartTaskCompleteStartPlacement(ctx context.Context, arg StartTaskCompleteStartPlacementParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, startTaskCompleteStartPlacement,
		arg.State,
		arg.UpdatedAtUnixMs,
		arg.PlacementID,
		arg.TaskID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const supersedeCompletedTerminalManualMoveSourcePlacement = `-- name: SupersedeCompletedTerminalManualMoveSourcePlacement :execrows
UPDATE task_node_placements
SET state = 'superseded',
    updated_at_unix_ms = ?1
WHERE task_node_placements.id = ?2
  AND state = 'completed'
  AND EXISTS (
      SELECT 1
      FROM workflow_nodes n
      WHERE n.id = task_node_placements.node_id
        AND n.kind = 'terminal'
  )
`

type SupersedeCompletedTerminalManualMoveSourcePlacementParams struct {
	UpdatedAtUnixMs int64
	PlacementID     string
}

func (q *Queries) SupersedeCompletedTerminalManualMoveSourcePlacement(ctx context.Context, arg SupersedeCompletedTerminalManualMoveSourcePlacementParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, supersedeCompletedTerminalManualMoveSourcePlacement, arg.UpdatedAtUnixMs, arg.PlacementID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const touchTaskUpdatedAt = `-- name: TouchTaskUpdatedAt :execrows
UPDATE tasks
SET updated_at_unix_ms = ?1
WHERE id = ?2
`

type TouchTaskUpdatedAtParams struct {
	UpdatedAtUnixMs int64
	TaskID          string
}

func (q *Queries) TouchTaskUpdatedAt(ctx context.Context, arg TouchTaskUpdatedAtParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, touchTaskUpdatedAt, arg.UpdatedAtUnixMs, arg.TaskID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateSessionExecutionTargetByID = `-- name: UpdateSessionExecutionTargetByID :execrows
UPDATE sessions
SET
    workspace_id = ?1,
    worktree_id = ?2,
    cwd_relpath = ?3,
    updated_at_unix_ms = ?4
WHERE id = ?5
`

type UpdateSessionExecutionTargetByIDParams struct {
	WorkspaceID     sql.NullString
	WorktreeID      sql.NullString
	CwdRelpath      string
	UpdatedAtUnixMs int64
	SessionID       string
}

func (q *Queries) UpdateSessionExecutionTargetByID(ctx context.Context, arg UpdateSessionExecutionTargetByIDParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateSessionExecutionTargetByID,
		arg.WorkspaceID,
		arg.WorktreeID,
		arg.CwdRelpath,
		arg.UpdatedAtUnixMs,
		arg.SessionID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateTaskCommentBody = `-- name: UpdateTaskCommentBody :execrows
UPDATE task_comments
SET
    body = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type UpdateTaskCommentBodyParams struct {
	Body            string
	UpdatedAtUnixMs int64
	ID              string
}

func (q *Queries) UpdateTaskCommentBody(ctx context.Context, arg UpdateTaskCommentBodyParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateTaskCommentBody, arg.Body, arg.UpdatedAtUnixMs, arg.ID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateTaskEditableFields = `-- name: UpdateTaskEditableFields :execrows
UPDATE tasks
SET
    title = ?1,
    body = ?2,
    source_workspace_id = ?3,
    metadata_json = ?4,
    updated_at_unix_ms = ?5
WHERE id = ?6
`

type UpdateTaskEditableFieldsParams struct {
	Title             string
	Body              string
	SourceWorkspaceID sql.NullString
	MetadataJson      string
	UpdatedAtUnixMs   int64
	ID                string
}

func (q *Queries) UpdateTaskEditableFields(ctx context.Context, arg UpdateTaskEditableFieldsParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateTaskEditableFields,
		arg.Title,
		arg.Body,
		arg.SourceWorkspaceID,
		arg.MetadataJson,
		arg.UpdatedAtUnixMs,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateTaskManagedWorktree = `-- name: UpdateTaskManagedWorktree :execrows
UPDATE tasks
SET
    managed_worktree_id = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type UpdateTaskManagedWorktreeParams struct {
	ManagedWorktreeID sql.NullString
	UpdatedAtUnixMs   int64
	ID                string
}

func (q *Queries) UpdateTaskManagedWorktree(ctx context.Context, arg UpdateTaskManagedWorktreeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateTaskManagedWorktree, arg.ManagedWorktreeID, arg.UpdatedAtUnixMs, arg.ID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateTaskNodePlacementState = `-- name: UpdateTaskNodePlacementState :execrows
UPDATE task_node_placements
SET
    state = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type UpdateTaskNodePlacementStateParams struct {
	State           string
	UpdatedAtUnixMs int64
	ID              string
}

func (q *Queries) UpdateTaskNodePlacementState(ctx context.Context, arg UpdateTaskNodePlacementStateParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateTaskNodePlacementState, arg.State, arg.UpdatedAtUnixMs, arg.ID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateTaskRunOutcome = `-- name: UpdateTaskRunOutcome :execrows
UPDATE task_runs
SET
    updated_at_unix_ms = ?1,
    completed_at_unix_ms = ?2,
    interrupted_at_unix_ms = ?3,
    interruption_reason = ?4,
    interruption_detail_json = ?5,
    waiting_ask_id = ?6,
    invalid_completion_count = ?7
WHERE id = ?8
`

type UpdateTaskRunOutcomeParams struct {
	UpdatedAtUnixMs        int64
	CompletedAtUnixMs      int64
	InterruptedAtUnixMs    int64
	InterruptionReason     string
	InterruptionDetailJson string
	WaitingAskID           string
	InvalidCompletionCount int64
	ID                     string
}

func (q *Queries) UpdateTaskRunOutcome(ctx context.Context, arg UpdateTaskRunOutcomeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateTaskRunOutcome,
		arg.UpdatedAtUnixMs,
		arg.CompletedAtUnixMs,
		arg.InterruptedAtUnixMs,
		arg.InterruptionReason,
		arg.InterruptionDetailJson,
		arg.WaitingAskID,
		arg.InvalidCompletionCount,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowEdge = `-- name: UpdateWorkflowEdge :execrows
UPDATE workflow_edges
SET
    transition_group_id = ?1,
    edge_key = ?2,
    target_node_id = ?3,
    requires_approval = ?4,
    context_mode = ?5,
    context_source_kind = ?6,
    context_source_node_key = ?7,
    prompt_template = ?8,
    parameters_json = ?9,
    input_bindings_json = ?10,
    output_requirements_json = ?11
WHERE workflow_edges.id = ?12
  AND (
      SELECT source.workflow_id
      FROM workflow_edges existing
      JOIN workflow_transition_groups tg ON tg.id = existing.transition_group_id
      JOIN workflow_nodes source ON source.id = tg.source_node_id
      WHERE existing.id = ?12
  ) = ?13
  AND EXISTS (
      SELECT 1
      FROM workflow_transition_groups new_tg
      JOIN workflow_nodes new_source ON new_source.id = new_tg.source_node_id
      JOIN workflow_nodes target ON target.id = ?3
      WHERE new_tg.id = ?1
        AND new_source.workflow_id = ?13
        AND target.workflow_id = ?13
  )
`

type UpdateWorkflowEdgeParams struct {
	TransitionGroupID      string
	EdgeKey                string
	TargetNodeID           string
	RequiresApproval       int64
	ContextMode            string
	ContextSourceKind      string
	ContextSourceNodeKey   string
	PromptTemplate         string
	ParametersJson         string
	InputBindingsJson      string
	OutputRequirementsJson string
	EdgeID                 string
	WorkflowID             string
}

func (q *Queries) UpdateWorkflowEdge(ctx context.Context, arg UpdateWorkflowEdgeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowEdge,
		arg.TransitionGroupID,
		arg.EdgeKey,
		arg.TargetNodeID,
		arg.RequiresApproval,
		arg.ContextMode,
		arg.ContextSourceKind,
		arg.ContextSourceNodeKey,
		arg.PromptTemplate,
		arg.ParametersJson,
		arg.InputBindingsJson,
		arg.OutputRequirementsJson,
		arg.EdgeID,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowInfo = `-- name: UpdateWorkflowInfo :execrows
UPDATE workflows
SET
    name = ?1,
    description = ?2,
    version = version + 1,
    updated_at_unix_ms = ?3
WHERE id = ?4
`

type UpdateWorkflowInfoParams struct {
	Name            string
	Description     string
	UpdatedAtUnixMs int64
	ID              string
}

func (q *Queries) UpdateWorkflowInfo(ctx context.Context, arg UpdateWorkflowInfoParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowInfo,
		arg.Name,
		arg.Description,
		arg.UpdatedAtUnixMs,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowInfoWithoutVersion = `-- name: UpdateWorkflowInfoWithoutVersion :execrows
UPDATE workflows
SET
    name = ?1,
    description = ?2,
    updated_at_unix_ms = ?3
WHERE id = ?4
`

type UpdateWorkflowInfoWithoutVersionParams struct {
	Name            string
	Description     string
	UpdatedAtUnixMs int64
	ID              string
}

func (q *Queries) UpdateWorkflowInfoWithoutVersion(ctx context.Context, arg UpdateWorkflowInfoWithoutVersionParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowInfoWithoutVersion,
		arg.Name,
		arg.Description,
		arg.UpdatedAtUnixMs,
		arg.ID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowNode = `-- name: UpdateWorkflowNode :execrows
UPDATE workflow_nodes
SET
    node_key = ?1,
    kind = ?2,
    display_name = ?3,
    subagent_role = ?4,
    prompt_template = ?5,
    completion_mode = ?6,
    script_path = ?7,
    input_fields_json = ?8,
    join_input_providers_json = ?9,
    output_fields_json = ?10,
    group_id = ?11
WHERE id = ?12
  AND workflow_id = ?13
`

type UpdateWorkflowNodeParams struct {
	NodeKey                string
	Kind                   string
	DisplayName            string
	SubagentRole           string
	PromptTemplate         string
	CompletionMode         string
	ScriptPath             sql.NullString
	InputFieldsJson        string
	JoinInputProvidersJson string
	OutputFieldsJson       string
	GroupID                sql.NullString
	ID                     string
	WorkflowID             string
}

func (q *Queries) UpdateWorkflowNode(ctx context.Context, arg UpdateWorkflowNodeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowNode,
		arg.NodeKey,
		arg.Kind,
		arg.DisplayName,
		arg.SubagentRole,
		arg.PromptTemplate,
		arg.CompletionMode,
		arg.ScriptPath,
		arg.InputFieldsJson,
		arg.JoinInputProvidersJson,
		arg.OutputFieldsJson,
		arg.GroupID,
		arg.ID,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowNodeGroup = `-- name: UpdateWorkflowNodeGroup :execrows
UPDATE workflow_node_groups
SET
    group_key = ?1,
    display_name = ?2,
    sort_order = ?3
WHERE id = ?4
  AND workflow_id = ?5
`

type UpdateWorkflowNodeGroupParams struct {
	GroupKey    string
	DisplayName string
	SortOrder   int64
	ID          string
	WorkflowID  string
}

func (q *Queries) UpdateWorkflowNodeGroup(ctx context.Context, arg UpdateWorkflowNodeGroupParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowNodeGroup,
		arg.GroupKey,
		arg.DisplayName,
		arg.SortOrder,
		arg.ID,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkflowTransitionGroup = `-- name: UpdateWorkflowTransitionGroup :execrows
UPDATE workflow_transition_groups
SET
    source_node_id = ?1,
    transition_id = ?2,
    display_name = ?3,
    description = ?4
WHERE workflow_transition_groups.id = ?5
  AND (
      SELECT source.workflow_id
      FROM workflow_transition_groups existing
      JOIN workflow_nodes source ON source.id = existing.source_node_id
      WHERE existing.id = ?5
  ) = ?6
  AND EXISTS (
      SELECT 1
      FROM workflow_nodes new_source
      WHERE new_source.id = ?1
        AND new_source.workflow_id = ?6
  )
`

type UpdateWorkflowTransitionGroupParams struct {
	SourceNodeID      string
	TransitionID      string
	DisplayName       string
	Description       string
	TransitionGroupID string
	WorkflowID        string
}

func (q *Queries) UpdateWorkflowTransitionGroup(ctx context.Context, arg UpdateWorkflowTransitionGroupParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkflowTransitionGroup,
		arg.SourceNodeID,
		arg.TransitionID,
		arg.DisplayName,
		arg.Description,
		arg.TransitionGroupID,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorkspaceBindingCanonicalRoot = `-- name: UpdateWorkspaceBindingCanonicalRoot :execrows
UPDATE workspaces
SET
    canonical_root_path = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type UpdateWorkspaceBindingCanonicalRootParams struct {
	CanonicalRootPath string
	UpdatedAtUnixMs   int64
	ID                string
}

func (q *Queries) UpdateWorkspaceBindingCanonicalRoot(ctx context.Context, arg UpdateWorkspaceBindingCanonicalRootParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorkspaceBindingCanonicalRoot, arg.CanonicalRootPath, arg.UpdatedAtUnixMs, arg.ID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const updateWorktreeCanonicalRoot = `-- name: UpdateWorktreeCanonicalRoot :execrows
UPDATE worktrees
SET
    canonical_root_path = ?1,
    updated_at_unix_ms = ?2
WHERE id = ?3
`

type UpdateWorktreeCanonicalRootParams struct {
	CanonicalRootPath string
	UpdatedAtUnixMs   int64
	ID                string
}

func (q *Queries) UpdateWorktreeCanonicalRoot(ctx context.Context, arg UpdateWorktreeCanonicalRootParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, updateWorktreeCanonicalRoot, arg.CanonicalRootPath, arg.UpdatedAtUnixMs, arg.ID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const upsertProject = `-- name: UpsertProject :exec
INSERT INTO projects (
    id,
    display_name,
    created_at_unix_ms,
    updated_at_unix_ms,
    metadata_json
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5
)
ON CONFLICT(id) DO UPDATE SET
    display_name = excluded.display_name,
    updated_at_unix_ms = excluded.updated_at_unix_ms,
    metadata_json = excluded.metadata_json
`

type UpsertProjectParams struct {
	ID              string
	DisplayName     string
	CreatedAtUnixMs int64
	UpdatedAtUnixMs int64
	MetadataJson    string
}

func (q *Queries) UpsertProject(ctx context.Context, arg UpsertProjectParams) error {
	_, err := q.db.ExecContext(ctx, upsertProject,
		arg.ID,
		arg.DisplayName,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
		arg.MetadataJson,
	)
	return err
}

const upsertSession = `-- name: UpsertSession :exec
INSERT INTO sessions (
    id,
    project_id,
    workspace_id,
    worktree_id,
    artifact_relpath,
    name,
    first_prompt_preview,
    input_draft,
    parent_session_id,
    created_at_unix_ms,
    updated_at_unix_ms,
    last_sequence,
    model_request_count,
    launch_visible,
    cwd_relpath,
    continuation_json,
    locked_json,
    usage_state_json,
    metadata_json
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14,
    ?15,
    ?16,
    ?17,
    ?18,
    ?19
)
ON CONFLICT(id) DO UPDATE SET
    project_id = excluded.project_id,
    workspace_id = excluded.workspace_id,
    worktree_id = excluded.worktree_id,
    artifact_relpath = excluded.artifact_relpath,
    name = excluded.name,
    first_prompt_preview = excluded.first_prompt_preview,
    input_draft = excluded.input_draft,
    parent_session_id = excluded.parent_session_id,
    updated_at_unix_ms = excluded.updated_at_unix_ms,
    last_sequence = excluded.last_sequence,
    model_request_count = excluded.model_request_count,
    launch_visible = CASE
        WHEN sessions.launch_visible <> 0 OR excluded.launch_visible <> 0 THEN 1
        ELSE 0
    END,
    cwd_relpath = excluded.cwd_relpath,
    continuation_json = excluded.continuation_json,
    locked_json = excluded.locked_json,
    usage_state_json = excluded.usage_state_json,
    metadata_json = excluded.metadata_json
`

type UpsertSessionParams struct {
	ID                 string
	ProjectID          string
	WorkspaceID        sql.NullString
	WorktreeID         sql.NullString
	ArtifactRelpath    string
	Name               string
	FirstPromptPreview string
	InputDraft         string
	ParentSessionID    string
	CreatedAtUnixMs    int64
	UpdatedAtUnixMs    int64
	LastSequence       int64
	ModelRequestCount  int64
	LaunchVisible      int64
	CwdRelpath         string
	ContinuationJson   string
	LockedJson         string
	UsageStateJson     string
	MetadataJson       string
}

func (q *Queries) UpsertSession(ctx context.Context, arg UpsertSessionParams) error {
	_, err := q.db.ExecContext(ctx, upsertSession,
		arg.ID,
		arg.ProjectID,
		arg.WorkspaceID,
		arg.WorktreeID,
		arg.ArtifactRelpath,
		arg.Name,
		arg.FirstPromptPreview,
		arg.InputDraft,
		arg.ParentSessionID,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
		arg.LastSequence,
		arg.ModelRequestCount,
		arg.LaunchVisible,
		arg.CwdRelpath,
		arg.ContinuationJson,
		arg.LockedJson,
		arg.UsageStateJson,
		arg.MetadataJson,
	)
	return err
}

const upsertWorkflowEdge = `-- name: UpsertWorkflowEdge :execrows
INSERT INTO workflow_edges (id, transition_group_id, edge_key, target_node_id, requires_approval, context_mode, context_source_kind, context_source_node_key, prompt_template, parameters_json, input_bindings_json, output_requirements_json, sort_order)
SELECT
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13
WHERE EXISTS (
    SELECT 1
    FROM workflow_transition_groups tg
    JOIN workflow_nodes source ON source.id = tg.source_node_id
    JOIN workflow_nodes target ON target.id = ?4
    WHERE tg.id = ?2
      AND source.workflow_id = ?14
      AND target.workflow_id = ?14
)
ON CONFLICT(id) DO UPDATE SET
    transition_group_id = excluded.transition_group_id,
    edge_key = excluded.edge_key,
    target_node_id = excluded.target_node_id,
    requires_approval = excluded.requires_approval,
    context_mode = excluded.context_mode,
    context_source_kind = excluded.context_source_kind,
    context_source_node_key = excluded.context_source_node_key,
    prompt_template = excluded.prompt_template,
    parameters_json = excluded.parameters_json,
    input_bindings_json = excluded.input_bindings_json,
    output_requirements_json = excluded.output_requirements_json,
    sort_order = excluded.sort_order
WHERE EXISTS (
    SELECT 1
    FROM workflow_transition_groups tg
    JOIN workflow_nodes source ON source.id = tg.source_node_id
    WHERE tg.id = workflow_edges.transition_group_id
      AND source.workflow_id = (
          SELECT new_source.workflow_id
          FROM workflow_transition_groups new_tg
          JOIN workflow_nodes new_source ON new_source.id = new_tg.source_node_id
          WHERE new_tg.id = excluded.transition_group_id
      )
)
`

type UpsertWorkflowEdgeParams struct {
	ID                     string
	TransitionGroupID      string
	EdgeKey                string
	TargetNodeID           string
	RequiresApproval       int64
	ContextMode            string
	ContextSourceKind      string
	ContextSourceNodeKey   string
	PromptTemplate         string
	ParametersJson         string
	InputBindingsJson      string
	OutputRequirementsJson string
	SortOrder              int64
	WorkflowID             string
}

func (q *Queries) UpsertWorkflowEdge(ctx context.Context, arg UpsertWorkflowEdgeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, upsertWorkflowEdge,
		arg.ID,
		arg.TransitionGroupID,
		arg.EdgeKey,
		arg.TargetNodeID,
		arg.RequiresApproval,
		arg.ContextMode,
		arg.ContextSourceKind,
		arg.ContextSourceNodeKey,
		arg.PromptTemplate,
		arg.ParametersJson,
		arg.InputBindingsJson,
		arg.OutputRequirementsJson,
		arg.SortOrder,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const upsertWorkflowNode = `-- name: UpsertWorkflowNode :execrows
INSERT INTO workflow_nodes (id, workflow_id, node_key, kind, display_name, subagent_role, prompt_template, completion_mode, script_path, input_fields_json, join_input_providers_json, output_fields_json, group_id, sort_order)
VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9,
    ?10,
    ?11,
    ?12,
    ?13,
    ?14
)
ON CONFLICT(id) DO UPDATE SET
    node_key = excluded.node_key,
    kind = excluded.kind,
    display_name = excluded.display_name,
    subagent_role = excluded.subagent_role,
    prompt_template = excluded.prompt_template,
    completion_mode = excluded.completion_mode,
    script_path = excluded.script_path,
    input_fields_json = excluded.input_fields_json,
    join_input_providers_json = excluded.join_input_providers_json,
    output_fields_json = excluded.output_fields_json,
    group_id = excluded.group_id,
    sort_order = excluded.sort_order
WHERE workflow_nodes.workflow_id = excluded.workflow_id
`

type UpsertWorkflowNodeParams struct {
	ID                     string
	WorkflowID             string
	NodeKey                string
	Kind                   string
	DisplayName            string
	SubagentRole           string
	PromptTemplate         string
	CompletionMode         string
	ScriptPath             sql.NullString
	InputFieldsJson        string
	JoinInputProvidersJson string
	OutputFieldsJson       string
	GroupID                sql.NullString
	SortOrder              int64
}

func (q *Queries) UpsertWorkflowNode(ctx context.Context, arg UpsertWorkflowNodeParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, upsertWorkflowNode,
		arg.ID,
		arg.WorkflowID,
		arg.NodeKey,
		arg.Kind,
		arg.DisplayName,
		arg.SubagentRole,
		arg.PromptTemplate,
		arg.CompletionMode,
		arg.ScriptPath,
		arg.InputFieldsJson,
		arg.JoinInputProvidersJson,
		arg.OutputFieldsJson,
		arg.GroupID,
		arg.SortOrder,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const upsertWorkflowNodeGroup = `-- name: UpsertWorkflowNodeGroup :execrows
INSERT INTO workflow_node_groups (id, workflow_id, group_key, display_name, sort_order)
VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5
)
ON CONFLICT(id) DO UPDATE SET
    group_key = excluded.group_key,
    display_name = excluded.display_name,
    sort_order = excluded.sort_order
WHERE workflow_node_groups.workflow_id = excluded.workflow_id
`

type UpsertWorkflowNodeGroupParams struct {
	ID          string
	WorkflowID  string
	GroupKey    string
	DisplayName string
	SortOrder   int64
}

func (q *Queries) UpsertWorkflowNodeGroup(ctx context.Context, arg UpsertWorkflowNodeGroupParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, upsertWorkflowNodeGroup,
		arg.ID,
		arg.WorkflowID,
		arg.GroupKey,
		arg.DisplayName,
		arg.SortOrder,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const upsertWorkflowTransitionGroup = `-- name: UpsertWorkflowTransitionGroup :execrows
INSERT INTO workflow_transition_groups (id, source_node_id, transition_id, display_name, description, sort_order)
SELECT
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6
WHERE EXISTS (
    SELECT 1
    FROM workflow_nodes source
    WHERE source.id = ?2
      AND source.workflow_id = ?7
)
ON CONFLICT(id) DO UPDATE SET
    source_node_id = excluded.source_node_id,
    transition_id = excluded.transition_id,
    display_name = excluded.display_name,
    description = excluded.description,
    sort_order = excluded.sort_order
WHERE EXISTS (
    SELECT 1
    FROM workflow_nodes source
    WHERE source.id = workflow_transition_groups.source_node_id
      AND source.workflow_id = (
          SELECT new_source.workflow_id
          FROM workflow_nodes new_source
          WHERE new_source.id = excluded.source_node_id
      )
)
`

type UpsertWorkflowTransitionGroupParams struct {
	ID           string
	SourceNodeID string
	TransitionID string
	DisplayName  string
	Description  string
	SortOrder    int64
	WorkflowID   string
}

func (q *Queries) UpsertWorkflowTransitionGroup(ctx context.Context, arg UpsertWorkflowTransitionGroupParams) (int64, error) {
	result, err := q.db.ExecContext(ctx, upsertWorkflowTransitionGroup,
		arg.ID,
		arg.SourceNodeID,
		arg.TransitionID,
		arg.DisplayName,
		arg.Description,
		arg.SortOrder,
		arg.WorkflowID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

const upsertWorkspace = `-- name: UpsertWorkspace :exec
INSERT INTO workspaces (
    id,
    project_id,
    canonical_root_path,
    git_metadata_json,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6
)
ON CONFLICT(id) DO UPDATE SET
    project_id = excluded.project_id,
    canonical_root_path = excluded.canonical_root_path,
    git_metadata_json = excluded.git_metadata_json,
    updated_at_unix_ms = excluded.updated_at_unix_ms
`

type UpsertWorkspaceParams struct {
	ID                string
	ProjectID         string
	CanonicalRootPath string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) UpsertWorkspace(ctx context.Context, arg UpsertWorkspaceParams) error {
	_, err := q.db.ExecContext(ctx, upsertWorkspace,
		arg.ID,
		arg.ProjectID,
		arg.CanonicalRootPath,
		arg.GitMetadataJson,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const upsertWorktree = `-- name: UpsertWorktree :exec
INSERT INTO worktrees (
    id,
    workspace_id,
    canonical_root_path,
    managed,
    created_branch,
    origin_session_id,
    git_metadata_json,
    created_at_unix_ms,
    updated_at_unix_ms
) VALUES (
    ?1,
    ?2,
    ?3,
    ?4,
    ?5,
    ?6,
    ?7,
    ?8,
    ?9
)
ON CONFLICT(canonical_root_path) DO UPDATE SET
    workspace_id = excluded.workspace_id,
    managed = excluded.managed,
    created_branch = excluded.created_branch,
    origin_session_id = excluded.origin_session_id,
    git_metadata_json = excluded.git_metadata_json,
    updated_at_unix_ms = excluded.updated_at_unix_ms
`

type UpsertWorktreeParams struct {
	ID                string
	WorkspaceID       string
	CanonicalRootPath string
	Managed           int64
	CreatedBranch     int64
	OriginSessionID   string
	GitMetadataJson   string
	CreatedAtUnixMs   int64
	UpdatedAtUnixMs   int64
}

func (q *Queries) UpsertWorktree(ctx context.Context, arg UpsertWorktreeParams) error {
	_, err := q.db.ExecContext(ctx, upsertWorktree,
		arg.ID,
		arg.WorkspaceID,
		arg.CanonicalRootPath,
		arg.Managed,
		arg.CreatedBranch,
		arg.OriginSessionID,
		arg.GitMetadataJson,
		arg.CreatedAtUnixMs,
		arg.UpdatedAtUnixMs,
	)
	return err
}

const workflowHasContinueSessionEdge = `-- name: WorkflowHasContinueSessionEdge :one
SELECT CAST(EXISTS (
    SELECT 1
    FROM workflow_edges e
    JOIN workflow_transition_groups g ON g.id = e.transition_group_id
    JOIN workflow_nodes n ON n.id = g.source_node_id
    WHERE n.workflow_id = ?1
      AND e.context_mode = 'continue_session'
) AS INTEGER) AS has_continue_session_edge
`

func (q *Queries) WorkflowHasContinueSessionEdge(ctx context.Context, workflowID string) (int64, error) {
	row := q.db.QueryRowContext(ctx, workflowHasContinueSessionEdge, workflowID)
	var has_continue_session_edge int64
	err := row.Scan(&has_continue_session_edge)
	return has_continue_session_edge, err
}
