feat(postgres): port events/identities/status surfaces, fix shipped defects

CHECKPOINT -- the full State Store port is in progress; this lands the
compile-clean core so the review pass has a diff to work against. Remaining:
advisory-lock ownership, event-insert serialization, maintenance, and the
ported test battery.

Two corrections to behaviour that already shipped, not new features:
- UpdateTask wrote park_reason raw where SQLite applies clip(park_reason,
  4000); the PostgreSQL adapter now clips before binding (clip.go).
- tasks.review_cursor existed on the protobuf wire and in workflow.Task but
  not in the PostgreSQL schema; 0004 adds it as a NEW migration rather than
  amending 0001 because a dev database may already have applied 0001 and
  goose tracks version numbers, not checksums.

Also moves the control-plane Resource/ResourceWrite types and their sentinels
into storecontract so the postgres package can stop importing internal/store
(they stay aliased there for daemon callers).
This commit is contained in:
sam committed 2026-09-24 02:17:44 +10:00
1 parent cebbcb5690
commit 0cece95b4a
17 files changed
+2424 -29

No files matched your search

@@ -0,0 +1,339 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: events.sql
package postgresdb
import (
"context"
"time"
)
const insertEvent = `-- name: InsertEvent :one
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
RETURNING id
`
type InsertEventParams struct {
At time.Time
Kind string
TaskID int64
Repo string
Issue int64
Workflow string
Stage string
Attempt int64
ActorID string
ActorKind string
PrincipalID string
Detail string
Data string
}
// Event-log queries. The (at, id) cursor is a wire contract: at is the
// fixed-width sort key and id only breaks ties, so a reader pages by
// "after (at, id)" and never skips or repeats a row. See
// internal/domain/storecontract/cursor.go.
func (q *Queries) InsertEvent(ctx context.Context, arg InsertEventParams) (int64, error) {
row := q.db.QueryRow(ctx, insertEvent,
arg.At,
arg.Kind,
arg.TaskID,
arg.Repo,
arg.Issue,
arg.Workflow,
arg.Stage,
arg.Attempt,
arg.ActorID,
arg.ActorKind,
arg.PrincipalID,
arg.Detail,
arg.Data,
)
var id int64
err := row.Scan(&id)
return id, err
}
const listEventsAfter = `-- name: ListEventsAfter :many
SELECT id, at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data
FROM events
WHERE at > $1 OR (at = $1 AND id > $2)
ORDER BY at, id
LIMIT $3
`
type ListEventsAfterParams struct {
At time.Time
ID int64
Limit int32
}
func (q *Queries) ListEventsAfter(ctx context.Context, arg ListEventsAfterParams) ([]Event, error) {
rows, err := q.db.Query(ctx, listEventsAfter, arg.At, arg.ID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Event
for rows.Next() {
var i Event
if err := rows.Scan(
&i.ID,
&i.At,
&i.Kind,
&i.TaskID,
&i.Repo,
&i.Issue,
&i.Workflow,
&i.Stage,
&i.Attempt,
&i.ActorID,
&i.ActorKind,
&i.PrincipalID,
&i.Detail,
&i.Data,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listEventsFromBeginning = `-- name: ListEventsFromBeginning :many
SELECT id, at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data
FROM events
ORDER BY at, id
LIMIT $1
`
func (q *Queries) ListEventsFromBeginning(ctx context.Context, limit int32) ([]Event, error) {
rows, err := q.db.Query(ctx, listEventsFromBeginning, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Event
for rows.Next() {
var i Event
if err := rows.Scan(
&i.ID,
&i.At,
&i.Kind,
&i.TaskID,
&i.Repo,
&i.Issue,
&i.Workflow,
&i.Stage,
&i.Attempt,
&i.ActorID,
&i.ActorKind,
&i.PrincipalID,
&i.Detail,
&i.Data,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const stageStats = `-- name: StageStats :many
SELECT workflow, stage,
COUNT(*)::int AS runs,
CAST(AVG((data::jsonb ->> 'duration_ms')::numeric) AS bigint) AS avg_ms,
COUNT(*) FILTER (WHERE (data::jsonb ->> 'error') IS NOT NULL)::int AS errors
FROM events
WHERE kind = 'stage_finish'
GROUP BY workflow, stage
ORDER BY workflow, stage
`
type StageStatsRow struct {
Workflow string
Stage string
Runs int32
AvgMs int64
Errors int32
}
func (q *Queries) StageStats(ctx context.Context) ([]StageStatsRow, error) {
rows, err := q.db.Query(ctx, stageStats)
if err != nil {
return nil, err
}
defer rows.Close()
var items []StageStatsRow
for rows.Next() {
var i StageStatsRow
if err := rows.Scan(
&i.Workflow,
&i.Stage,
&i.Runs,
&i.AvgMs,
&i.Errors,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const taskEventsByID = `-- name: TaskEventsByID :many
SELECT id, at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data
FROM events
WHERE task_id = $1
ORDER BY id
`
func (q *Queries) TaskEventsByID(ctx context.Context, taskID int64) ([]Event, error) {
rows, err := q.db.Query(ctx, taskEventsByID, taskID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Event
for rows.Next() {
var i Event
if err := rows.Scan(
&i.ID,
&i.At,
&i.Kind,
&i.TaskID,
&i.Repo,
&i.Issue,
&i.Workflow,
&i.Stage,
&i.Attempt,
&i.ActorID,
&i.ActorKind,
&i.PrincipalID,
&i.Detail,
&i.Data,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const tokensByDay = `-- name: TokensByDay :many
WITH event_totals AS (
SELECT task_id, to_char(at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day,
SUM(CASE WHEN jsonb_typeof(data::jsonb -> 'tokens') = 'number'
THEN (data::jsonb ->> 'tokens')::bigint ELSE 0 END) AS tokens,
SUM(CASE WHEN jsonb_typeof(data::jsonb -> 'tokens') = 'number' THEN 1 ELSE 0 END) AS valid_tokens
FROM events WHERE kind = 'agent_finish'
GROUP BY task_id, day
), usage AS (
SELECT day, tokens FROM event_totals WHERE valid_tokens > 0
UNION ALL
SELECT to_char(t.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD'), t.tokens_used
FROM tasks t
WHERE t.tokens_used != 0 AND NOT EXISTS (
SELECT 1 FROM event_totals e
WHERE e.task_id = t.id AND e.valid_tokens > 0
)
)
SELECT day, SUM(tokens)::bigint AS tokens
FROM usage GROUP BY day ORDER BY day DESC LIMIT $1
`
type TokensByDayRow struct {
Day string
Tokens int64
}
func (q *Queries) TokensByDay(ctx context.Context, limit int32) ([]TokensByDayRow, error) {
rows, err := q.db.Query(ctx, tokensByDay, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []TokensByDayRow
for rows.Next() {
var i TokensByDayRow
if err := rows.Scan(&i.Day, &i.Tokens); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const workflowStats = `-- name: WorkflowStats :many
SELECT workflow,
COUNT(*)::int AS runs,
COUNT(*) FILTER (WHERE status = 'merged')::int AS merged,
COUNT(*) FILTER (WHERE status = 'pr_open')::int AS pr_open,
COUNT(*) FILTER (WHERE status = 'parked')::int AS parked,
CAST(AVG(tokens_used) AS bigint) AS avg_tokens,
AVG(iterations)::float8 AS avg_steps,
SUM(tokens_used)::bigint AS total_tokens
FROM tasks
WHERE workflow <> ''
GROUP BY workflow
ORDER BY COUNT(*) DESC
`
type WorkflowStatsRow struct {
Workflow string
Runs int32
Merged int32
PrOpen int32
Parked int32
AvgTokens int64
AvgSteps float64
TotalTokens int64
}
func (q *Queries) WorkflowStats(ctx context.Context) ([]WorkflowStatsRow, error) {
rows, err := q.db.Query(ctx, workflowStats)
if err != nil {
return nil, err
}
defer rows.Close()
var items []WorkflowStatsRow
for rows.Next() {
var i WorkflowStatsRow
if err := rows.Scan(
&i.Workflow,
&i.Runs,
&i.Merged,
&i.PrOpen,
&i.Parked,
&i.AvgTokens,
&i.AvgSteps,
&i.TotalTokens,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -0,0 +1,270 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: identities.sql
package postgresdb
import (
"context"
"time"
)
const getIdentity = `-- name: GetIdentity :one
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities WHERE id = $1
`
func (q *Queries) GetIdentity(ctx context.Context, id string) (Identity, error) {
row := q.db.QueryRow(ctx, getIdentity, id)
var i Identity
err := row.Scan(
&i.ID,
&i.Kind,
&i.DisplayName,
&i.Lifecycle,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertIdentity = `-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`
type InsertIdentityParams struct {
ID string
Kind string
DisplayName string
Lifecycle string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) InsertIdentity(ctx context.Context, arg InsertIdentityParams) error {
_, err := q.db.Exec(ctx, insertIdentity,
arg.ID,
arg.Kind,
arg.DisplayName,
arg.Lifecycle,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertIdentityAlias = `-- name: InsertIdentityAlias :exec
INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2)
`
type InsertIdentityAliasParams struct {
Alias string
IdentityID string
}
func (q *Queries) InsertIdentityAlias(ctx context.Context, arg InsertIdentityAliasParams) error {
_, err := q.db.Exec(ctx, insertIdentityAlias, arg.Alias, arg.IdentityID)
return err
}
const insertIdentityAliasIgnoreConflict = `-- name: InsertIdentityAliasIgnoreConflict :exec
INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO NOTHING
`
type InsertIdentityAliasIgnoreConflictParams struct {
Alias string
IdentityID string
}
func (q *Queries) InsertIdentityAliasIgnoreConflict(ctx context.Context, arg InsertIdentityAliasIgnoreConflictParams) error {
_, err := q.db.Exec(ctx, insertIdentityAliasIgnoreConflict, arg.Alias, arg.IdentityID)
return err
}
const insertIdentityEvent = `-- name: InsertIdentityEvent :exec
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`
type InsertIdentityEventParams struct {
IdentityID string
EventType string
FromLifecycle string
ToLifecycle string
DisplayName string
ActorID string
Source string
RequestID string
At time.Time
}
func (q *Queries) InsertIdentityEvent(ctx context.Context, arg InsertIdentityEventParams) error {
_, err := q.db.Exec(ctx, insertIdentityEvent,
arg.IdentityID,
arg.EventType,
arg.FromLifecycle,
arg.ToLifecycle,
arg.DisplayName,
arg.ActorID,
arg.Source,
arg.RequestID,
arg.At,
)
return err
}
const listIdentities = `-- name: ListIdentities :many
SELECT id, kind, display_name, lifecycle, version, created_at, updated_at
FROM identities ORDER BY created_at, id
`
// Identity persistence. The domain owns lifecycle semantics (internal/domain/
// identity); these queries are the durable half of that contract. Aliases are
// unique on lower(alias) rather than the case-sensitive PRIMARY KEY, matching
// the SQLite schema's COLLATE NOCASE.
func (q *Queries) ListIdentities(ctx context.Context) ([]Identity, error) {
rows, err := q.db.Query(ctx, listIdentities)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Identity
for rows.Next() {
var i Identity
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.DisplayName,
&i.Lifecycle,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const resolveIdentityAlias = `-- name: ResolveIdentityAlias :one
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM identities i JOIN identity_aliases a ON a.identity_id = i.id
WHERE lower(a.alias) = lower($1)
`
func (q *Queries) ResolveIdentityAlias(ctx context.Context, lower string) (Identity, error) {
row := q.db.QueryRow(ctx, resolveIdentityAlias, lower)
var i Identity
err := row.Scan(
&i.ID,
&i.Kind,
&i.DisplayName,
&i.Lifecycle,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const resolveIdentitySubject = `-- name: ResolveIdentitySubject :one
SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at
FROM identities i JOIN identity_subjects b ON b.identity_id = i.id
WHERE b.issuer = $1 AND b.subject = $2
`
type ResolveIdentitySubjectParams struct {
Issuer string
Subject string
}
func (q *Queries) ResolveIdentitySubject(ctx context.Context, arg ResolveIdentitySubjectParams) (Identity, error) {
row := q.db.QueryRow(ctx, resolveIdentitySubject, arg.Issuer, arg.Subject)
var i Identity
err := row.Scan(
&i.ID,
&i.Kind,
&i.DisplayName,
&i.Lifecycle,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const updateIdentity = `-- name: UpdateIdentity :execrows
UPDATE identities SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5
WHERE id = $1 AND version = $6
`
type UpdateIdentityParams struct {
ID string
DisplayName string
Lifecycle string
Version int64
UpdatedAt time.Time
Version_2 int64
}
func (q *Queries) UpdateIdentity(ctx context.Context, arg UpdateIdentityParams) (int64, error) {
result, err := q.db.Exec(ctx, updateIdentity,
arg.ID,
arg.DisplayName,
arg.Lifecycle,
arg.Version,
arg.UpdatedAt,
arg.Version_2,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateTaskIdentity = `-- name: UpdateTaskIdentity :exec
UPDATE tasks SET identity = $1 WHERE identity = $2
`
type UpdateTaskIdentityParams struct {
Identity string
Identity_2 string
}
func (q *Queries) UpdateTaskIdentity(ctx context.Context, arg UpdateTaskIdentityParams) error {
_, err := q.db.Exec(ctx, updateTaskIdentity, arg.Identity, arg.Identity_2)
return err
}
const upsertIdentitySubject = `-- name: UpsertIdentitySubject :exec
INSERT INTO identity_subjects (issuer, subject, identity_id, bound_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT (issuer, subject) DO UPDATE SET identity_id = excluded.identity_id, bound_at = excluded.bound_at
`
type UpsertIdentitySubjectParams struct {
Issuer string
Subject string
IdentityID string
BoundAt time.Time
}
func (q *Queries) UpsertIdentitySubject(ctx context.Context, arg UpsertIdentitySubjectParams) error {
_, err := q.db.Exec(ctx, upsertIdentitySubject,
arg.Issuer,
arg.Subject,
arg.IdentityID,
arg.BoundAt,
)
return err
}
@@ -138,6 +138,7 @@ type Task struct {
WorkflowDefinitionYaml string
CreatedAt time.Time
UpdatedAt time.Time
ReviewCursor int64
}
type Transition struct {
@@ -0,0 +1,188 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: status.sql
package postgresdb
import (
"context"
"time"
)
const configSnapshotByID = `-- name: ConfigSnapshotByID :one
SELECT schema, document, published_at FROM config_snapshot WHERE id = 1
`
type ConfigSnapshotByIDRow struct {
Schema string
Document string
PublishedAt time.Time
}
func (q *Queries) ConfigSnapshotByID(ctx context.Context) (ConfigSnapshotByIDRow, error) {
row := q.db.QueryRow(ctx, configSnapshotByID)
var i ConfigSnapshotByIDRow
err := row.Scan(&i.Schema, &i.Document, &i.PublishedAt)
return i, err
}
const deleteChannelStatusNotIn = `-- name: DeleteChannelStatusNotIn :exec
DELETE FROM channel_status WHERE NOT (id = ANY($1::text[]))
`
func (q *Queries) DeleteChannelStatusNotIn(ctx context.Context, dollar_1 []string) error {
_, err := q.db.Exec(ctx, deleteChannelStatusNotIn, dollar_1)
return err
}
const listApplyStatus = `-- name: ListApplyStatus :many
SELECT process, kind, applied_version, error, reported_at
FROM apply_status ORDER BY process, kind
`
func (q *Queries) ListApplyStatus(ctx context.Context) ([]ApplyStatus, error) {
rows, err := q.db.Query(ctx, listApplyStatus)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ApplyStatus
for rows.Next() {
var i ApplyStatus
if err := rows.Scan(
&i.Process,
&i.Kind,
&i.AppliedVersion,
&i.Error,
&i.ReportedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listChannelStatus = `-- name: ListChannelStatus :many
SELECT id, name, state, detail, configured, reload_supported, observed_at
FROM channel_status ORDER BY id
`
func (q *Queries) ListChannelStatus(ctx context.Context) ([]ChannelStatus, error) {
rows, err := q.db.Query(ctx, listChannelStatus)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ChannelStatus
for rows.Next() {
var i ChannelStatus
if err := rows.Scan(
&i.ID,
&i.Name,
&i.State,
&i.Detail,
&i.Configured,
&i.ReloadSupported,
&i.ObservedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const upsertApplyStatus = `-- name: UpsertApplyStatus :exec
INSERT INTO apply_status (process, kind, applied_version, error, reported_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (process, kind) DO UPDATE SET
applied_version = excluded.applied_version,
error = excluded.error,
reported_at = excluded.reported_at
`
type UpsertApplyStatusParams struct {
Process string
Kind string
AppliedVersion int64
Error string
ReportedAt time.Time
}
func (q *Queries) UpsertApplyStatus(ctx context.Context, arg UpsertApplyStatusParams) error {
_, err := q.db.Exec(ctx, upsertApplyStatus,
arg.Process,
arg.Kind,
arg.AppliedVersion,
arg.Error,
arg.ReportedAt,
)
return err
}
const upsertChannelStatus = `-- name: UpsertChannelStatus :exec
INSERT INTO channel_status (id, name, state, detail, configured, reload_supported, observed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (id) DO UPDATE SET
name = excluded.name,
state = excluded.state,
detail = excluded.detail,
configured = excluded.configured,
reload_supported = excluded.reload_supported,
observed_at = excluded.observed_at
`
type UpsertChannelStatusParams struct {
ID string
Name string
State string
Detail string
Configured bool
ReloadSupported bool
ObservedAt time.Time
}
func (q *Queries) UpsertChannelStatus(ctx context.Context, arg UpsertChannelStatusParams) error {
_, err := q.db.Exec(ctx, upsertChannelStatus,
arg.ID,
arg.Name,
arg.State,
arg.Detail,
arg.Configured,
arg.ReloadSupported,
arg.ObservedAt,
)
return err
}
const upsertConfigSnapshot = `-- name: UpsertConfigSnapshot :exec
INSERT INTO config_snapshot (id, schema, document, published_at)
VALUES (1, $1, $2, $3)
ON CONFLICT (id) DO UPDATE SET
schema = excluded.schema,
document = excluded.document,
published_at = excluded.published_at
`
type UpsertConfigSnapshotParams struct {
Schema string
Document string
PublishedAt time.Time
}
// Status projection queries: the published configuration snapshot and the
// channel / apply-status runtime reports the UI reads across the State Store
// boundary.
func (q *Queries) UpsertConfigSnapshot(ctx context.Context, arg UpsertConfigSnapshotParams) error {
_, err := q.db.Exec(ctx, upsertConfigSnapshot, arg.Schema, arg.Document, arg.PublishedAt)
return err
}
@@ -10,6 +10,94 @@ import (
"time"
)
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', stage = '', park_reason = '', park_class = 'needs_human', review_payload = $2, updated_at = now()
WHERE id = $1 AND status = 'pr_open'
`
type BeginRemediationTaskParams struct {
ID int64
ReviewPayload string
}
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, 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, stage, 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
`
type ClaimByIssueParams struct {
Owner string
Repo string
IssueNumber int64
}
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.Stage,
&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,
)
return i, err
}
const claimNextTask = `-- name: ClaimNextTask :one
UPDATE tasks
SET status = 'running', attempt = attempt + 1, updated_at = now()
@@ -20,7 +108,7 @@ WHERE id = (
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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
`
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
@@ -62,6 +150,7 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
&i.ReviewCursor,
)
return i, err
}
@@ -108,6 +197,38 @@ func (q *Queries) CountTasksByStatus(ctx context.Context) ([]CountTasksByStatusR
return items, nil
}
const enqueueIssue = `-- name: EnqueueIssue :execrows
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, identity)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (owner, repo, issue_number) DO NOTHING
`
type EnqueueIssueParams struct {
Owner string
Repo string
IssueNumber int64
Title string
Body string
Labels string
Identity string
}
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
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity)
VALUES (
@@ -120,7 +241,7 @@ VALUES (
), $3) + 1,
$4, $5, 'chat', $6, 'chat', $7
)
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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
`
type InsertChatTaskParams struct {
@@ -181,6 +302,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
&i.ReviewCursor,
)
return i, err
}
@@ -207,6 +329,57 @@ func (q *Queries) InsertTransition(ctx context.Context, arg InsertTransitionPara
return err
}
const listOpenPRs = `-- name: ListOpenPRs :many
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt, review_cursor, watch_comment_id
FROM tasks WHERE status = 'pr_open'
`
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
}
func (q *Queries) ListOpenPRs(ctx context.Context) ([]ListOpenPRsRow, error) {
rows, err := q.db.Query(ctx, listOpenPRs)
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,
); 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, stage,
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
@@ -321,6 +494,67 @@ func (q *Queries) RecoverStaleTasks(ctx context.Context) (int64, error) {
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,
stage = '', 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 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,
stage = '', park_reason = '', park_class = 'needs_human', updated_at = now()
WHERE id = $2 AND status = $3
`
type RetryTaskParams struct {
Workflow string
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.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 stampTaskBinding = `-- name: StampTaskBinding :exec
UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1
`
@@ -337,7 +571,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara
}
const taskByID = `-- name: TaskByID :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE id = $1
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE id = $1
`
func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
@@ -376,12 +610,13 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
&i.ReviewCursor,
)
return i, err
}
const taskByIssue = `-- name: TaskByIssue :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
`
type TaskByIssueParams struct {
@@ -426,22 +661,32 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task,
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
&i.ReviewCursor,
)
return i, err
}
const taskByPR = `-- name: TaskByPR :one
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, stage, 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 FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
`
type TaskByPRParams struct {
Owner string
Repo string
PrNumber int64
Status string
}
// 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)
row := q.db.QueryRow(ctx, taskByPR,
arg.Owner,
arg.Repo,
arg.PrNumber,
arg.Status,
)
var i Task
err := row.Scan(
&i.ID,
@@ -476,6 +721,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error
&i.WorkflowDefinitionYaml,
&i.CreatedAt,
&i.UpdatedAt,
&i.ReviewCursor,
)
return i, err
}
@@ -513,6 +759,24 @@ func (q *Queries) TransitionTask(ctx context.Context, arg TransitionTaskParams)
return result.RowsAffected(), nil
}
const updateReviewPayloadTask = `-- name: UpdateReviewPayloadTask :execrows
UPDATE tasks SET review_payload = $2, updated_at = now()
WHERE id = $1 AND status = 'queued' AND workflow = 'remediate'
`
type UpdateReviewPayloadTaskParams struct {
ID int64
ReviewPayload string
}
func (q *Queries) UpdateReviewPayloadTask(ctx context.Context, arg UpdateReviewPayloadTaskParams) (int64, error) {
result, err := q.db.Exec(ctx, updateReviewPayloadTask, arg.ID, arg.ReviewPayload)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateTask = `-- name: UpdateTask :exec
UPDATE tasks SET workflow = $2, stage = $3, branch = $4, plan = $5, notes = $6,
pr_number = $7, tokens_used = $8, iterations = $9, park_reason = $10,