// Code generated by sqlc. DO NOT EDIT. // versions: // sqlc v1.31.1 // source: tasks.sql package postgresdb import ( "context" "time" "github.com/jackc/pgx/v5/pgtype" ) const activeTasksByOrigin = `-- name: ActiveTasksByOrigin :many SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted FROM tasks WHERE origin = $1 AND origin <> '' AND status IN ('queued', 'running') AND ($2::text IS NULL OR org_id = $2) ORDER BY id ` type ActiveTasksByOriginParams struct { Origin string ScopeOrg pgtype.Text } // The queued and running tasks one conversation created, for its /stop. func (q *Queries) ActiveTasksByOrigin(ctx context.Context, arg ActiveTasksByOriginParams) ([]Task, error) { rows, err := q.db.Query(ctx, activeTasksByOrigin, arg.Origin, arg.ScopeOrg) if err != nil { return nil, err } defer rows.Close() var items []Task for rows.Next() { var i Task if err := rows.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const appendPendingReview = `-- name: AppendPendingReview :execrows UPDATE tasks SET pending_reviews = CASE WHEN review_payload = $2::text THEN pending_reviews WHEN pending_reviews @> jsonb_build_array($2::text) THEN pending_reviews ELSE pending_reviews || jsonb_build_array($2::text) END, updated_at = now() WHERE id = $1 AND status IN ('queued', 'running') AND workflow = 'remediate' ` type AppendPendingReviewParams struct { ID int64 Column2 string } // A distinct review that arrived while a remediation owned the task. The two // containment tests are the dedup: a re-delivered reaction, or a poll that // re-publishes a review already queued, appends nothing, and one already // active in review_payload is not queued to run a second time. func (q *Queries) AppendPendingReview(ctx context.Context, arg AppendPendingReviewParams) (int64, error) { result, err := q.db.Exec(ctx, appendPendingReview, arg.ID, arg.Column2) if err != nil { return 0, err } return result.RowsAffected(), nil } const archiveTaskDelete = `-- name: ArchiveTaskDelete :execrows DELETE FROM tasks WHERE id = $1 AND status = $2 ` type ArchiveTaskDeleteParams struct { ID int64 Status string } func (q *Queries) ArchiveTaskDelete(ctx context.Context, arg ArchiveTaskDeleteParams) (int64, error) { result, err := q.db.Exec(ctx, archiveTaskDelete, arg.ID, arg.Status) if err != nil { return 0, err } return result.RowsAffected(), nil } const beginRemediationTask = `-- name: BeginRemediationTask :execrows UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = $2, retry_mode = 'continue_pushed_work', resume_from = '', resume_results = '{}', updated_at = now() WHERE id = $1 AND status = 'pr_open' ` type BeginRemediationTaskParams struct { ID int64 ReviewPayload string } // A remediation must continue the branch its pull request lives on, so it // records that dispatch mode explicitly (taskstate.RetryContinuePushedWork) // rather than leaving prepareWorkspace to infer it from the workflow. func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediationTaskParams) (int64, error) { result, err := q.db.Exec(ctx, beginRemediationTask, arg.ID, arg.ReviewPayload) if err != nil { return 0, err } return result.RowsAffected(), nil } const claimByIssue = `-- name: ClaimByIssue :one UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now() WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued' RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted ` type ClaimByIssueParams struct { Owner string Repo string IssueNumber int64 } // The claim starts the attempt's output set empty, as ClaimNextTask does: // outputs is attempt-scoped (docs/prds/workflow-call-outputs.md). func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Task, error) { row := q.db.QueryRow(ctx, claimByIssue, arg.Owner, arg.Repo, arg.IssueNumber) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const claimNextTask = `-- name: ClaimNextTask :one UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now() WHERE id = ( SELECT id FROM tasks WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1 ) RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted ` // FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two // claimers running at once take different rows instead of blocking, so the // daemon no longer depends on holding the only connection to the file. // The claim also starts the attempt's output set empty: outputs is // attempt-scoped, so nothing the previous attempt wrote survives // (docs/prds/workflow-call-outputs.md). func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) { row := q.db.QueryRow(ctx, claimNextTask) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const clearTerminalTasks = `-- name: ClearTerminalTasks :execrows DELETE FROM tasks WHERE status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed') AND ($1::text IS NULL OR org_id = $1) ` func (q *Queries) ClearTerminalTasks(ctx context.Context, scopeOrg pgtype.Text) (int64, error) { result, err := q.db.Exec(ctx, clearTerminalTasks, scopeOrg) if err != nil { return 0, err } return result.RowsAffected(), nil } const countTasksByStatus = `-- name: CountTasksByStatus :many SELECT status, count(*)::int AS count FROM tasks WHERE ($1::text IS NULL OR org_id = $1) GROUP BY status ` type CountTasksByStatusRow struct { Status string Count int32 } func (q *Queries) CountTasksByStatus(ctx context.Context, scopeOrg pgtype.Text) ([]CountTasksByStatusRow, error) { rows, err := q.db.Query(ctx, countTasksByStatus, scopeOrg) if err != nil { return nil, err } defer rows.Close() var items []CountTasksByStatusRow for rows.Next() { var i CountTasksByStatusRow if err := rows.Scan(&i.Status, &i.Count); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const enqueueIssue = `-- name: EnqueueIssue :execrows INSERT INTO tasks (owner, repo, issue_number, title, body, labels, identity, org_id, workspace_id) VALUES ( $1, $2, $3, $4, $5, $6, $7, COALESCE( (SELECT a.org_id FROM org_agents a WHERE a.identity_id = $7), (SELECT m.org_id FROM memberships m WHERE m.identity_id = $7 ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), 'org-sys' ), 'default' ) ON CONFLICT (org_id, identity, owner, repo, issue_number) DO NOTHING ` type EnqueueIssueParams struct { Owner string Repo string IssueNumber int64 Title string Body string Labels string Identity string } // The org is derived from the identity at the one place a task row is // written (an agent's assignment, else a membership, else the default org); // uniqueness follows the record's identity: two orgs may work the same // issue under their own identities, one may not work it twice. func (q *Queries) EnqueueIssue(ctx context.Context, arg EnqueueIssueParams) (int64, error) { result, err := q.db.Exec(ctx, enqueueIssue, arg.Owner, arg.Repo, arg.IssueNumber, arg.Title, arg.Body, arg.Labels, arg.Identity, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const insertChatTask = `-- name: InsertChatTask :one WITH number AS ( INSERT INTO chat_issue_numbers (owner, repo, last_number) VALUES ($1, $2, $12::bigint + 1) ON CONFLICT (owner, repo) DO UPDATE SET last_number = chat_issue_numbers.last_number + 1 RETURNING last_number ) INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs, origin, workflow_definition_yaml, workflow_definition_digest) SELECT $1, $2, number.last_number, $3, $4, 'chat', $5, CASE WHEN $6::text = '' THEN 'chat' ELSE 'test' END, $7, owner_org.id, $8, $9, $6::text, $10::text FROM number, (SELECT COALESCE( (SELECT a.org_id FROM org_agents a WHERE a.identity_id = $7), (SELECT m.org_id FROM memberships m WHERE m.identity_id = $7 ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), 'org-sys' ) AS id) AS owner_org WHERE $11::text IS NULL OR owner_org.id = $11 RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted ` type InsertChatTaskParams struct { Owner string Repo string Title string Body string Workflow string DraftYaml string Identity string Inputs string Origin string DraftDigest string ScopeOrg pgtype.Text FallbackIssueNumber int64 } // The synthetic issue number keeps chat-sourced tasks off the forge's real // issue numbers; chat_issue_numbers is the single source of truth for it, and // bumping its row serializes concurrent inserts in one repository. // fallback_issue_number is only the seed for a repo's first chat task -- the // passed value is not the issue number that lands. // inputs is the chat task's own workflow inputs; a binding dispatch passes // its inputs here too, so this insert is the single writer of the column and // StampTaskBinding adds only the provenance. // The task runs in its identity's org; a caller confined to another org // inserts nothing, so it cannot start work under an identity it does not own. // A non-empty draft_yaml makes the task a test run: it is pinned to that // definition and its source is 'test'. func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams) (Task, error) { row := q.db.QueryRow(ctx, insertChatTask, arg.Owner, arg.Repo, arg.Title, arg.Body, arg.Workflow, arg.DraftYaml, arg.Identity, arg.Inputs, arg.Origin, arg.DraftDigest, arg.ScopeOrg, arg.FallbackIssueNumber, ) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const insertTransition = `-- name: InsertTransition :exec INSERT INTO transitions (task_id, from_status, to_status, detail, org_id, workspace_id) SELECT t.id, $1, $2, $3, t.org_id, t.workspace_id FROM tasks t WHERE t.id = $4 ` type InsertTransitionParams struct { FromStatus string ToStatus string Detail string TaskID int64 } func (q *Queries) InsertTransition(ctx context.Context, arg InsertTransitionParams) error { _, err := q.db.Exec(ctx, insertTransition, arg.FromStatus, arg.ToStatus, arg.Detail, arg.TaskID, ) return err } const listOpenPRs = `-- name: ListOpenPRs :many SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt, review_cursor, watch_comment_id, outputs FROM tasks WHERE status = 'pr_open' AND ($1::text IS NULL OR org_id = $1) ` type ListOpenPRsRow struct { ID int64 Owner string Repo string IssueNumber int64 PrNumber int64 Status string Source string Identity string Attempt int64 ReviewCursor int64 WatchCommentID int64 Outputs string } func (q *Queries) ListOpenPRs(ctx context.Context, scopeOrg pgtype.Text) ([]ListOpenPRsRow, error) { rows, err := q.db.Query(ctx, listOpenPRs, scopeOrg) if err != nil { return nil, err } defer rows.Close() var items []ListOpenPRsRow for rows.Next() { var i ListOpenPRsRow if err := rows.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.PrNumber, &i.Status, &i.Source, &i.Identity, &i.Attempt, &i.ReviewCursor, &i.WatchCommentID, &i.Outputs, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const listTaskSummaries = `-- name: ListTaskSummaries :many SELECT id, owner, repo, issue_number, title, status, workflow, pr_number, tokens_used, iterations, attempt, park_reason, retry_count, created_at, updated_at, plan, source, identity, binding_id, binding_version, outputs, review_gate, rereview_rounds FROM tasks WHERE ($1::text IS NULL OR org_id = $1) AND (cardinality($2::text[]) = 0 OR status = ANY($2::text[])) AND ($3::text = '' OR workflow = $3::text) AND ($4::timestamptz IS NULL OR (updated_at, id) < ($4::timestamptz, $5::bigint)) ORDER BY updated_at DESC, id DESC LIMIT $6 ` type ListTaskSummariesParams struct { ScopeOrg pgtype.Text Statuses []string Workflow string BeforeUpdated pgtype.Timestamptz BeforeID int64 PageLimit int32 } type ListTaskSummariesRow struct { ID int64 Owner string Repo string IssueNumber int64 Title string Status string Workflow string PrNumber int64 TokensUsed int64 Iterations int64 Attempt int64 ParkReason string RetryCount int64 CreatedAt time.Time UpdatedAt time.Time Plan string Source string Identity string BindingID string BindingVersion int64 Outputs string ReviewGate string RereviewRounds int64 } // The dashboard's list. This projection is deliberately narrow: Plan gates // the "Decision required" panel and Source labels the row, and widening it // back would send rows without them. outputs rides it because the task row's // own structured result is part of the summary a caller or the dashboard // reads (docs/prds/workflow-call-outputs.md, "Storage and wire"). // review_gate and rereview_rounds join it deliberately: the offer the gate // wrote is what the operator reads before answering it // (docs/prds/pr-review-operator-response.md, "The review the operator // answers"), and the round count is the cap's visible half. func (q *Queries) ListTaskSummaries(ctx context.Context, arg ListTaskSummariesParams) ([]ListTaskSummariesRow, error) { rows, err := q.db.Query(ctx, listTaskSummaries, arg.ScopeOrg, arg.Statuses, arg.Workflow, arg.BeforeUpdated, arg.BeforeID, arg.PageLimit, ) if err != nil { return nil, err } defer rows.Close() var items []ListTaskSummariesRow for rows.Next() { var i ListTaskSummariesRow if err := rows.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Status, &i.Workflow, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.RetryCount, &i.CreatedAt, &i.UpdatedAt, &i.Plan, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const lockReviewUnits = `-- name: LockReviewUnits :one SELECT status, workflow, review_payload, pending_reviews::text AS pending_reviews FROM tasks WHERE id = $1 FOR UPDATE ` type LockReviewUnitsRow struct { Status string Workflow string ReviewPayload string PendingReviews string } // The remediation's review units, locked so a comment merge cannot race the // claim that freezes the active unit or the promotion of a pending one. func (q *Queries) LockReviewUnits(ctx context.Context, id int64) (LockReviewUnitsRow, error) { row := q.db.QueryRow(ctx, lockReviewUnits, id) var i LockReviewUnitsRow err := row.Scan( &i.Status, &i.Workflow, &i.ReviewPayload, &i.PendingReviews, ) return i, err } const lockTaskStatus = `-- name: LockTaskStatus :one SELECT status FROM tasks WHERE id = $1 FOR UPDATE ` // Locks the task's row and returns its current status, so the staleness and // transition-table checks that decide a guarded write hold against a // concurrent claim or transition until the update in the same transaction. func (q *Queries) LockTaskStatus(ctx context.Context, id int64) (string, error) { row := q.db.QueryRow(ctx, lockTaskStatus, id) var status string err := row.Scan(&status) return status, err } const markOutcomePosted = `-- name: MarkOutcomePosted :exec UPDATE tasks SET outcome_posted = true WHERE id = $1 ` func (q *Queries) MarkOutcomePosted(ctx context.Context, id int64) error { _, err := q.db.Exec(ctx, markOutcomePosted, id) return err } const parkTask = `-- name: ParkTask :execrows UPDATE tasks SET status = 'parked', park_reason = $2, park_class = $3, updated_at = now() WHERE id = $1 AND status = $4 ` type ParkTaskParams struct { ID int64 ParkReason string ParkClass string Status string } func (q *Queries) ParkTask(ctx context.Context, arg ParkTaskParams) (int64, error) { result, err := q.db.Exec(ctx, parkTask, arg.ID, arg.ParkReason, arg.ParkClass, arg.Status, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const promotePendingReview = `-- name: PromotePendingReview :execrows UPDATE tasks SET status = 'queued', workflow = 'remediate', park_reason = '', park_class = 'needs_human', review_payload = pending_reviews->>0, pending_reviews = pending_reviews - 0, retry_mode = 'continue_pushed_work', resume_from = '', resume_results = '{}', updated_at = now() WHERE id = $1 AND status = 'pr_open' AND workflow = 'remediate' AND jsonb_array_length(pending_reviews) > 0 ` // The run that owned the task returned it to pr_open with reviews still // waiting: the oldest becomes the active payload and the task is queued // again, so it is remediated after the run that just finished. func (q *Queries) PromotePendingReview(ctx context.Context, id int64) (int64, error) { result, err := q.db.Exec(ctx, promotePendingReview, id) if err != nil { return 0, err } return result.RowsAffected(), nil } const recoverStaleTasks = `-- name: RecoverStaleTasks :execrows UPDATE tasks SET status = 'queued', updated_at = now() WHERE status = 'running' ` func (q *Queries) RecoverStaleTasks(ctx context.Context) (int64, error) { result, err := q.db.Exec(ctx, recoverStaleTasks) if err != nil { return 0, err } return result.RowsAffected(), nil } const requeueTask = `-- name: RequeueTask :execrows UPDATE tasks SET status = 'queued', workflow = CASE WHEN $1::text = '' THEN workflow ELSE $1::text END, park_reason = '', park_class = 'needs_human', updated_at = now() WHERE id = $2 AND status = $3 ` type RequeueTaskParams struct { Workflow string ID int64 FromStatus string } func (q *Queries) RequeueTask(ctx context.Context, arg RequeueTaskParams) (int64, error) { result, err := q.db.Exec(ctx, requeueTask, arg.Workflow, arg.ID, arg.FromStatus) if err != nil { return 0, err } return result.RowsAffected(), nil } const rereviewRounds = `-- name: RereviewRounds :one SELECT rereview_rounds FROM tasks WHERE id = $1 ` // Read under the lock LockTaskStatus takes in the same transaction, so the // cap decision and the increment it guards cannot interleave with a second // response write. func (q *Queries) RereviewRounds(ctx context.Context, id int64) (int64, error) { row := q.db.QueryRow(ctx, rereviewRounds, id) var rereview_rounds int64 err := row.Scan(&rereview_rounds) return rereview_rounds, err } const respondReviewGateTask = `-- name: RespondReviewGateTask :execrows UPDATE tasks SET status = 'queued', review_gate = $1::text, rereview_rounds = rereview_rounds + CASE WHEN $2::bool THEN 1 ELSE 0 END, park_reason = '', park_class = 'needs_human', updated_at = now() WHERE id = $3 AND status = $4 AND ($2::bool = false OR rereview_rounds < $5::bigint) ` type RespondReviewGateTaskParams struct { Gate string Rereview bool ID int64 FromStatus string Cap int64 } // The review gate response write (docs/prds/pr-review-operator-response.md, // Decision 2): one guarded requeue beside RetryTask/BeginRemediation. The // from-status guard and the transition table live in the store's transaction // around this statement; the rereview cap is enforced HERE, in the row, so // two simultaneous re-reviews cannot spend a round the cap forbids. An // approve passes rereview=false and bumps nothing. func (q *Queries) RespondReviewGateTask(ctx context.Context, arg RespondReviewGateTaskParams) (int64, error) { result, err := q.db.Exec(ctx, respondReviewGateTask, arg.Gate, arg.Rereview, arg.ID, arg.FromStatus, arg.Cap, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const retryTask = `-- name: RetryTask :execrows UPDATE tasks SET status = 'queued', retry_count = retry_count + 1, workflow = CASE WHEN $1::text = '' THEN workflow ELSE $1::text END, retry_mode = $2::text, resume_from = $3::text, resume_results = $4::jsonb, park_reason = '', park_class = 'needs_human', updated_at = now() WHERE id = $5 AND status = $6 ` type RetryTaskParams struct { Workflow string RetryMode string ResumeFrom string ResumeResults []byte ID int64 FromStatus string } func (q *Queries) RetryTask(ctx context.Context, arg RetryTaskParams) (int64, error) { result, err := q.db.Exec(ctx, retryTask, arg.Workflow, arg.RetryMode, arg.ResumeFrom, arg.ResumeResults, arg.ID, arg.FromStatus, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const setReviewCursors = `-- name: SetReviewCursors :execrows UPDATE tasks SET review_cursor = $2, watch_comment_id = $3, updated_at = now() WHERE id = $1 AND status = 'pr_open' ` type SetReviewCursorsParams struct { ID int64 ReviewCursor int64 WatchCommentID int64 } func (q *Queries) SetReviewCursors(ctx context.Context, arg SetReviewCursorsParams) (int64, error) { result, err := q.db.Exec(ctx, setReviewCursors, arg.ID, arg.ReviewCursor, arg.WatchCommentID) if err != nil { return 0, err } return result.RowsAffected(), nil } const setReviewUnits = `-- name: SetReviewUnits :exec UPDATE tasks SET review_payload = $2, pending_reviews = CAST(CAST($3 AS text) AS jsonb), updated_at = now() WHERE id = $1 ` type SetReviewUnitsParams struct { ID int64 ReviewPayload string PendingReviews string } func (q *Queries) SetReviewUnits(ctx context.Context, arg SetReviewUnitsParams) error { _, err := q.db.Exec(ctx, setReviewUnits, arg.ID, arg.ReviewPayload, arg.PendingReviews) return err } const stampTaskBinding = `-- name: StampTaskBinding :exec UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1 ` type StampTaskBindingParams struct { ID int64 BindingID string BindingVersion int64 } func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingParams) error { _, err := q.db.Exec(ctx, stampTaskBinding, arg.ID, arg.BindingID, arg.BindingVersion) return err } const taskByID = `-- name: TaskByID :one SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted FROM tasks WHERE id = $1 AND ($2::text IS NULL OR org_id = $2) ` type TaskByIDParams struct { ID int64 ScopeOrg pgtype.Text } func (q *Queries) TaskByID(ctx context.Context, arg TaskByIDParams) (Task, error) { row := q.db.QueryRow(ctx, taskByID, arg.ID, arg.ScopeOrg) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const taskByIssue = `-- name: TaskByIssue :one SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND ($4::text IS NULL OR org_id = $4) ` type TaskByIssueParams struct { Owner string Repo string IssueNumber int64 ScopeOrg pgtype.Text } func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task, error) { row := q.db.QueryRow(ctx, taskByIssue, arg.Owner, arg.Repo, arg.IssueNumber, arg.ScopeOrg, ) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const taskByPR = `-- name: TaskByPR :one SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4 AND ($5::text IS NULL OR org_id = $5) ` type TaskByPRParams struct { Owner string Repo string PrNumber int64 Status string ScopeOrg pgtype.Text } // OpenTaskByPR is the live-task lookup: it only resolves a PR the task is // currently tracking as open, so a merged or rejected task does not read as // the owner of a PR number it no longer holds. func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error) { row := q.db.QueryRow(ctx, taskByPR, arg.Owner, arg.Repo, arg.PrNumber, arg.Status, arg.ScopeOrg, ) var i Task err := row.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ) return i, err } const transitionTask = `-- name: TransitionTask :execrows UPDATE tasks SET status = $2, park_reason = CASE WHEN $2 = 'parked' THEN $3 ELSE park_reason END, park_class = CASE WHEN $2 = 'parked' THEN $4 ELSE park_class END, updated_at = now() WHERE id = $1 AND status = $5 ` type TransitionTaskParams struct { ID int64 Status string ParkReason string ParkClass string Status_2 string } // Arriving at 'parked' also records why. The class is normalized by the // caller, so an unknown value persists as needs_human rather than as itself. func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams) (int64, error) { result, err := q.db.Exec(ctx, transitionTask, arg.ID, arg.Status, arg.ParkReason, arg.ParkClass, arg.Status_2, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const unpostedOutcomes = `-- name: UnpostedOutcomes :many SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin, call_key, outcome_posted FROM tasks WHERE origin <> '' AND NOT outcome_posted AND status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed') AND ($1::text IS NULL OR org_id = $1) ORDER BY id LIMIT 50 ` // Finished chat tasks whose outcome has not reached their conversation yet. func (q *Queries) UnpostedOutcomes(ctx context.Context, scopeOrg pgtype.Text) ([]Task, error) { rows, err := q.db.Query(ctx, unpostedOutcomes, scopeOrg) if err != nil { return nil, err } defer rows.Close() var items []Task for rows.Next() { var i Task if err := rows.Scan( &i.ID, &i.Owner, &i.Repo, &i.IssueNumber, &i.Title, &i.Body, &i.Labels, &i.Status, &i.Workflow, &i.Branch, &i.Plan, &i.Notes, &i.PrNumber, &i.TokensUsed, &i.Iterations, &i.Attempt, &i.ParkReason, &i.WatchCommentID, &i.ParkClass, &i.RemediationRounds, &i.RetryCount, &i.Source, &i.Identity, &i.BindingID, &i.BindingVersion, &i.ReviewPayload, &i.WorkflowDefinitionVersion, &i.WorkflowDefinitionDigest, &i.WorkflowDefinitionYaml, &i.CreatedAt, &i.UpdatedAt, &i.ReviewCursor, &i.Inputs, &i.OrgID, &i.WorkspaceID, &i.CallParentTaskID, &i.CallDepth, &i.Outputs, &i.ReviewGate, &i.RereviewRounds, &i.RetryMode, &i.ResumeFrom, &i.ResumeResults, &i.PendingReviews, &i.Origin, &i.CallKey, &i.OutcomePosted, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const updateTask = `-- name: UpdateTask :exec UPDATE tasks SET workflow = $1, branch = $2, plan = $3, notes = $4, pr_number = $5, tokens_used = $6, iterations = $7, park_reason = $8, watch_comment_id = $9, retry_count = $10, remediation_rounds = $11, review_payload = $12, workflow_definition_version = CASE WHEN $13::text = '' THEN workflow_definition_version ELSE $14 END, workflow_definition_digest = CASE WHEN $13::text = '' THEN workflow_definition_digest ELSE $15 END, workflow_definition_yaml = CASE WHEN $13::text = '' THEN workflow_definition_yaml ELSE $13::text END, outputs = $16, review_gate = $17, rereview_rounds = $18, retry_mode = $19, updated_at = now() WHERE id = $20 ` type UpdateTaskParams struct { Workflow string Branch string Plan string Notes string PrNumber int64 TokensUsed int64 Iterations int64 ParkReason string WatchCommentID int64 RetryCount int64 RemediationRounds int64 ReviewPayload string WorkflowDefinitionYaml string WorkflowDefinitionVersion int64 WorkflowDefinitionDigest string Outputs string ReviewGate string RereviewRounds int64 RetryMode string ID int64 } // An update without a definition keeps the stored pin: a task's own // credential sends none, so it cannot replace the definition it runs. func (q *Queries) UpdateTask(ctx context.Context, arg UpdateTaskParams) error { _, err := q.db.Exec(ctx, updateTask, arg.Workflow, arg.Branch, arg.Plan, arg.Notes, arg.PrNumber, arg.TokensUsed, arg.Iterations, arg.ParkReason, arg.WatchCommentID, arg.RetryCount, arg.RemediationRounds, arg.ReviewPayload, arg.WorkflowDefinitionYaml, arg.WorkflowDefinitionVersion, arg.WorkflowDefinitionDigest, arg.Outputs, arg.ReviewGate, arg.RereviewRounds, arg.RetryMode, arg.ID, ) return err }