Files
sam 5edf58fd68 fix(daemon): reconcile and merge tasks whose PR was merged on the forge (#1872)
ListOpenPRs dropped org_id, so the reconciler resolved the forge and
worktrees in the default org instead of the task's own and skipped the
task silently. Select the org, log a skipped task, and let the Merge
action succeed when the forge reports the PR already merged.
2026-11-14 04:01:31 +11:00

1654 lines
49 KiB
Go

// 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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues 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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
); 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_decision', 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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues
`
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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues
`
// 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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
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) WHERE handoff_to_task_id IS NULL 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
AND m.org_id = $11::text LIMIT 1),
(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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues
`
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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
return i, err
}
const insertHandoffTask = `-- name: InsertHandoffTask :one
INSERT INTO tasks (id, owner, repo, issue_number, title, body, labels, workflow, source, identity,
org_id, workspace_id, inputs, plan, plan_document, binding_id, binding_version, binding_signature,
binding_addr, origin, call_parent_task_id, call_depth, handoff_from_task_id)
SELECT $1, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, $2, t.source, t.identity,
t.org_id, t.workspace_id, t.inputs, t.plan, t.plan_document, t.binding_id, t.binding_version, t.binding_signature,
t.binding_addr, t.origin, t.call_parent_task_id, t.call_depth, t.id
FROM tasks t WHERE t.id = $3
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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues
`
type InsertHandoffTaskParams struct {
SuccessorID int64
Workflow string
ID int64
}
// The successor run carries the work item and the decisions made on it; its
// run state (attempts, branch, outputs, review state) starts fresh.
func (q *Queries) InsertHandoffTask(ctx context.Context, arg InsertHandoffTaskParams) (Task, error) {
row := q.db.QueryRow(ctx, insertHandoffTask, arg.SuccessorID, arg.Workflow, arg.ID)
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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
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, org_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
OrgID string
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.OrgID,
&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, plan_document, source, identity, binding_id, binding_version,
outputs, review_gate, rereview_rounds, org_id, park_class, park_blocker,
handoff_from_task_id, handoff_to_task_id
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
PlanDocument string
Source string
Identity string
BindingID string
BindingVersion int64
Outputs string
ReviewGate string
RereviewRounds int64
OrgID string
ParkClass string
ParkBlocker string
HandoffFromTaskID pgtype.Int8
HandoffToTaskID pgtype.Int8
}
// 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.PlanDocument,
&i.Source,
&i.Identity,
&i.BindingID,
&i.BindingVersion,
&i.Outputs,
&i.ReviewGate,
&i.RereviewRounds,
&i.OrgID,
&i.ParkClass,
&i.ParkBlocker,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
); 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 markBlockerChanged = `-- name: MarkBlockerChanged :execrows
UPDATE tasks
SET park_reason = park_reason || ' [blocker changed]', updated_at = now()
WHERE status = 'parked' AND org_id = $1 AND park_blocker = ANY($2::text[])
AND park_reason NOT LIKE '%[blocker changed]'
`
type MarkBlockerChangedParams struct {
OrgID string
Blockers []string
}
// A parked task that names one of these blockers is flagged once, so the
// operator sees the resource it waited on was edited; retry stays theirs.
func (q *Queries) MarkBlockerChanged(ctx context.Context, arg MarkBlockerChangedParams) (int64, error) {
result, err := q.db.Exec(ctx, markBlockerChanged, arg.OrgID, arg.Blockers)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const markHandedOff = `-- name: MarkHandedOff :execrows
UPDATE tasks SET handoff_to_task_id = $1, updated_at = now()
WHERE id = $2 AND handoff_to_task_id IS NULL
`
type MarkHandedOffParams struct {
SuccessorID pgtype.Int8
ID int64
}
// The run leaves the item's unique key before its successor takes it.
func (q *Queries) MarkHandedOff(ctx context.Context, arg MarkHandedOffParams) (int64, error) {
result, err := q.db.Exec(ctx, markHandedOff, arg.SuccessorID, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const markOutcomePosted = `-- name: MarkOutcomePosted :exec
UPDATE tasks SET outcome_posted_status = COALESCE(NULLIF($1::text, ''), status) WHERE id = $2
`
type MarkOutcomePostedParams struct {
Posted string
ID int64
}
// Records the status whose state reached the task's conversation. A caller
// that names none (an older archied) marks the current status, so a mixed
// deploy cannot leave a posted state looking unposted forever.
func (q *Queries) MarkOutcomePosted(ctx context.Context, arg MarkOutcomePostedParams) error {
_, err := q.db.Exec(ctx, markOutcomePosted, arg.Posted, arg.ID)
return err
}
const nextTaskID = `-- name: NextTaskID :one
SELECT nextval(pg_get_serial_sequence('tasks', 'id'))::bigint
`
func (q *Queries) NextTaskID(ctx context.Context) (int64, error) {
row := q.db.QueryRow(ctx, nextTaskID)
var column_1 int64
err := row.Scan(&column_1)
return column_1, err
}
const parkRecoveredTask = `-- name: ParkRecoveredTask :execrows
UPDATE tasks SET status = 'parked', park_reason = $1, park_class = 'needs_decision', updated_at = now()
WHERE id = $2 AND status = 'running'
`
type ParkRecoveredTaskParams struct {
ParkReason string
ID int64
}
func (q *Queries) ParkRecoveredTask(ctx context.Context, arg ParkRecoveredTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, parkRecoveredTask, arg.ParkReason, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const parkTask = `-- name: ParkTask :execrows
UPDATE tasks
SET status = 'parked', park_reason = $2, park_class = $3, park_blocker = $5, updated_at = now()
WHERE id = $1 AND status = $4
`
type ParkTaskParams struct {
ID int64
ParkReason string
ParkClass string
Status string
ParkBlocker 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,
arg.ParkBlocker,
)
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_decision',
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 requeueRecoveredTask = `-- name: RequeueRecoveredTask :execrows
UPDATE tasks SET status = 'queued', restart_requeues = restart_requeues + 1,
retry_mode = $1::text, resume_results = $2::jsonb,
resume_history = CASE WHEN resume_from = $3::text THEN resume_history ELSE 'null' END,
resume_from = $3::text, updated_at = now()
WHERE id = $4 AND status = 'running'
`
type RequeueRecoveredTaskParams struct {
RetryMode string
ResumeResults []byte
ResumeFrom string
ID int64
}
// The restart's re-queue of a task it found running, resuming where the
// interrupted attempt stood. The conversation is kept only for the step the
// row already resumed at.
func (q *Queries) RequeueRecoveredTask(ctx context.Context, arg RequeueRecoveredTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, requeueRecoveredTask,
arg.RetryMode,
arg.ResumeResults,
arg.ResumeFrom,
arg.ID,
)
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_decision', restart_requeues = 0, 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_decision', 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, restart_requeues = 0,
workflow = CASE WHEN $1::text = '' THEN workflow ELSE $1::text END,
retry_mode = $2::text,
resume_from = $3::text, resume_results = $4::jsonb, resume_history = 'null',
workflow_definition_yaml = CASE WHEN $5::bool THEN '' ELSE workflow_definition_yaml END,
workflow_definition_digest = CASE WHEN $5::bool THEN '' ELSE workflow_definition_digest END,
workflow_definition_version = CASE WHEN $5::bool THEN 0 ELSE workflow_definition_version END,
park_reason = '', park_class = 'needs_decision', updated_at = now()
WHERE id = $6 AND status = $7
`
type RetryTaskParams struct {
Workflow string
RetryMode string
ResumeFrom string
ResumeResults []byte
CurrentDefinition bool
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.CurrentDefinition,
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 = $1, binding_version = $2,
binding_signature = c.signature, binding_addr = c.remote_addr
FROM (SELECT CASE WHEN authenticated THEN 'valid' WHEN unsigned THEN 'unsigned' ELSE 'unverified' END AS signature,
remote_addr
FROM captures WHERE captures.id = $4) c
WHERE tasks.id = $3
`
type StampTaskBindingParams struct {
BindingID string
BindingVersion int64
ID int64
CaptureID string
}
// The capture's signature result is spelled as the access context spells it.
func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingParams) error {
_, err := q.db.Exec(ctx, stampTaskBinding,
arg.BindingID,
arg.BindingVersion,
arg.ID,
arg.CaptureID,
)
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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues 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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND handoff_to_task_id IS NULL
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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues 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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
)
return i, err
}
const taskRetryCount = `-- name: TaskRetryCount :one
SELECT retry_count FROM tasks WHERE id = $1
`
// Read under the lock the park's guard takes, so the escalation decision
// cannot interleave with a retry.
func (q *Queries) TaskRetryCount(ctx context.Context, id int64) (int64, error) {
row := q.db.QueryRow(ctx, taskRetryCount, id)
var retry_count int64
err := row.Scan(&retry_count)
return retry_count, 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,
park_blocker = CASE WHEN $2 = 'parked' THEN '' ELSE park_blocker 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_decision 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, binding_signature, binding_addr, park_blocker, outcome_posted_status, plan_document, handoff_from_task_id, handoff_to_task_id, resume_history, restart_requeues FROM tasks
WHERE origin <> '' AND outcome_posted_status <> status
AND status IN ('merged', 'rejected', 'dead', 'closed_wont_do', 'completed', 'waiting_approval', 'pr_open')
AND handoff_to_task_id IS NULL
AND ($1::text IS NULL OR org_id = $1)
ORDER BY id
LIMIT 50
`
// Chat tasks that finished, wait for approval or have a pull request open,
// whose state 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.BindingSignature,
&i.BindingAddr,
&i.ParkBlocker,
&i.OutcomePostedStatus,
&i.PlanDocument,
&i.HandoffFromTaskID,
&i.HandoffToTaskID,
&i.ResumeHistory,
&i.RestartRequeues,
); 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, plan_document = $4, notes = $5,
pr_number = $6, tokens_used = $7, iterations = $8, park_reason = $9,
watch_comment_id = $10, retry_count = $11, remediation_rounds = $12,
review_payload = $13,
workflow_definition_version = CASE WHEN $14::text = '' THEN workflow_definition_version ELSE $15 END,
workflow_definition_digest = CASE WHEN $14::text = '' THEN workflow_definition_digest ELSE $16 END,
workflow_definition_yaml = CASE WHEN $14::text = '' THEN workflow_definition_yaml ELSE $14::text END,
outputs = $17, review_gate = $18, rereview_rounds = $19,
retry_mode = $20, resume_from = $21::text, resume_results = $22::jsonb,
resume_history = $23::jsonb, updated_at = now()
WHERE id = $24
`
type UpdateTaskParams struct {
Workflow string
Branch string
Plan string
PlanDocument 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
ResumeFrom string
ResumeResults []byte
ResumeHistory []byte
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.PlanDocument,
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.ResumeFrom,
arg.ResumeResults,
arg.ResumeHistory,
arg.ID,
)
return err
}