Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

160 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: agent_runtime_state.sql

package store

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const acquireAgentRuntimeAdvisoryLock = `-- name: AcquireAgentRuntimeAdvisoryLock :exec
SELECT pg_advisory_xact_lock(hashtextextended($1::text,0))
`

func (q *Queries) AcquireAgentRuntimeAdvisoryLock(ctx context.Context, lockKey string) error {
	_, err := q.db.Exec(ctx, acquireAgentRuntimeAdvisoryLock, lockKey)
	return err
}

const activateAgentExecutionContextForInput = `-- name: ActivateAgentExecutionContextForInput :one
UPDATE agent_execution_contexts
SET next_input_sequence=greatest(next_input_sequence,$1::bigint),
    target_residency='active',
    state_revision=state_revision+1,updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND terminal_reason IS NULL AND NOT task_archive_suspended
  AND (context_kind<>'alter_ego' OR EXISTS (
    SELECT 1 FROM work_items item WHERE item.id=agent_execution_contexts.task_id
      AND item.tenant_id=agent_execution_contexts.tenant_id AND item.archived_at IS NULL))
RETURNING state_revision,target_residency,next_input_sequence
`

type ActivateAgentExecutionContextForInputParams struct {
	InputSequence int64  `json:"input_sequence"`
	ContextKey    string `json:"context_key"`
}

type ActivateAgentExecutionContextForInputRow struct {
	StateRevision     int64  `json:"state_revision"`
	TargetResidency   string `json:"target_residency"`
	NextInputSequence int64  `json:"next_input_sequence"`
}

// The returned state lets the Agent Service update its Context record without
// reading it again.
func (q *Queries) ActivateAgentExecutionContextForInput(ctx context.Context, arg ActivateAgentExecutionContextForInputParams) (ActivateAgentExecutionContextForInputRow, error) {
	row := q.db.QueryRow(ctx, activateAgentExecutionContextForInput, arg.InputSequence, arg.ContextKey)
	var i ActivateAgentExecutionContextForInputRow
	err := row.Scan(&i.StateRevision, &i.TargetResidency, &i.NextInputSequence)
	return i, err
}

const advanceAgentRuntimeSessionProfileRevision = `-- name: AdvanceAgentRuntimeSessionProfileRevision :execrows
UPDATE agent_execution_contexts
SET session_profile_revision=$1::bigint,updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND session IS NOT NULL
  AND session_profile_revision<$1::bigint
`

type AdvanceAgentRuntimeSessionProfileRevisionParams struct {
	ProfileRevision int64  `json:"profile_revision"`
	ContextKey      string `json:"context_key"`
}

// A claim hands the Session a newer profile once.
func (q *Queries) AdvanceAgentRuntimeSessionProfileRevision(ctx context.Context, arg AdvanceAgentRuntimeSessionProfileRevisionParams) (int64, error) {
	result, err := q.db.Exec(ctx, advanceAgentRuntimeSessionProfileRevision, arg.ProfileRevision, arg.ContextKey)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const agentContextHasInputBefore = `-- name: AgentContextHasInputBefore :one
SELECT EXISTS(
    SELECT 1 FROM agent_runtime_inputs
    WHERE context_key=$1::text AND input_sequence<$2::bigint
)::boolean
`

type AgentContextHasInputBeforeParams struct {
	ContextKey    string `json:"context_key"`
	InputSequence int64  `json:"input_sequence"`
}

func (q *Queries) AgentContextHasInputBefore(ctx context.Context, arg AgentContextHasInputBeforeParams) (bool, error) {
	row := q.db.QueryRow(ctx, agentContextHasInputBefore, arg.ContextKey, arg.InputSequence)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const agentRuntimeContextHasPendingWork = `-- name: AgentRuntimeContextHasPendingWork :one
SELECT EXISTS(
    SELECT 1 FROM agent_runtime_inputs
    WHERE context_key=$1::text AND status='steering'
    UNION ALL
    SELECT 1 FROM agent_local_runs
    WHERE context_key=$1::text AND status IN ('queued','running')
)::boolean
`

func (q *Queries) AgentRuntimeContextHasPendingWork(ctx context.Context, contextKey string) (bool, error) {
	row := q.db.QueryRow(ctx, agentRuntimeContextHasPendingWork, contextKey)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const agentRuntimeDatabaseNow = `-- name: AgentRuntimeDatabaseNow :one
SELECT clock_timestamp()::timestamptz
`

func (q *Queries) AgentRuntimeDatabaseNow(ctx context.Context) (pgtype.Timestamptz, error) {
	row := q.db.QueryRow(ctx, agentRuntimeDatabaseNow)
	var column_1 pgtype.Timestamptz
	err := row.Scan(&column_1)
	return column_1, err
}

const assignAgentRuntimeSteerInput = `-- name: AssignAgentRuntimeSteerInput :execrows
UPDATE agent_runtime_inputs
SET local_run_id=$1::text,
    updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND input_id=$3::text
  AND status='steering'
  AND steer_group_id=$4::text
`

type AssignAgentRuntimeSteerInputParams struct {
	LocalRunID   string `json:"local_run_id"`
	ContextKey   string `json:"context_key"`
	InputID      string `json:"input_id"`
	SteerGroupID string `json:"steer_group_id"`
}

func (q *Queries) AssignAgentRuntimeSteerInput(ctx context.Context, arg AssignAgentRuntimeSteerInputParams) (int64, error) {
	result, err := q.db.Exec(ctx, assignAgentRuntimeSteerInput,
		arg.LocalRunID,
		arg.ContextKey,
		arg.InputID,
		arg.SteerGroupID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const bindAgentRuntimeLocalComputerDaemonIdentity = `-- name: BindAgentRuntimeLocalComputerDaemonIdentity :one
UPDATE local_computers
SET daemon_id=$1::text,
    daemon_public_key=$2::bytea,
    daemon_identity_version=$3::bigint,
    updated_at=clock_timestamp()
WHERE computer_id=$4::text
  AND status<>'removed'
  AND (
      daemon_id IS NULL
      OR (
          daemon_id=$1::text
          AND daemon_public_key=$2::bytea
          AND daemon_identity_version=$3::bigint
      )
  )
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

type BindAgentRuntimeLocalComputerDaemonIdentityParams struct {
	DaemonID        string `json:"daemon_id"`
	DaemonPublicKey []byte `json:"daemon_public_key"`
	IdentityVersion int64  `json:"identity_version"`
	ComputerID      string `json:"computer_id"`
}

func (q *Queries) BindAgentRuntimeLocalComputerDaemonIdentity(ctx context.Context, arg BindAgentRuntimeLocalComputerDaemonIdentityParams) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, bindAgentRuntimeLocalComputerDaemonIdentity,
		arg.DaemonID,
		arg.DaemonPublicKey,
		arg.IdentityVersion,
		arg.ComputerID,
	)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const bumpAgentExecutionContextStateRevision = `-- name: BumpAgentExecutionContextStateRevision :one
UPDATE agent_execution_contexts
SET state_revision=state_revision+1,updated_at=clock_timestamp()
WHERE context_key=$1::text
RETURNING state_revision
`

func (q *Queries) BumpAgentExecutionContextStateRevision(ctx context.Context, contextKey string) (int64, error) {
	row := q.db.QueryRow(ctx, bumpAgentExecutionContextStateRevision, contextKey)
	var state_revision int64
	err := row.Scan(&state_revision)
	return state_revision, err
}

const checkpointAgentRuntimeSession = `-- name: CheckpointAgentRuntimeSession :one
UPDATE agent_execution_contexts
SET session=$1::jsonb,
    session_provider_kind=$2::text,
    session_schema_version=$3::bigint,
    -- A new native thread starts under the profile it was checkpointed with.
    session_profile_revision=CASE
        WHEN session IS NULL OR $4::text IS DISTINCT FROM session_thread_id
        THEN $5::bigint ELSE session_profile_revision END,
    session_thread_id=$4::text,
    session_configuration_revision=$5::bigint,
    session_revision=session_revision+1,
    session_updated_at=clock_timestamp(),
    updated_at=clock_timestamp()
WHERE context_key=$6::text
  AND session_revision=$7::bigint
RETURNING context_key, session, session_provider_kind, session_schema_version,
    session_thread_id, session_configuration_revision, session_profile_revision,
    session_revision, session_updated_at
`

type CheckpointAgentRuntimeSessionParams struct {
	Session                 []byte      `json:"session"`
	ProviderKind            string      `json:"provider_kind"`
	SessionSchemaVersion    int64       `json:"session_schema_version"`
	ThreadID                pgtype.Text `json:"thread_id"`
	ConfigurationRevision   int64       `json:"configuration_revision"`
	ContextKey              string      `json:"context_key"`
	ExpectedSessionRevision int64       `json:"expected_session_revision"`
}

type CheckpointAgentRuntimeSessionRow struct {
	ContextKey                   string             `json:"context_key"`
	Session                      []byte             `json:"session"`
	SessionProviderKind          pgtype.Text        `json:"session_provider_kind"`
	SessionSchemaVersion         pgtype.Int8        `json:"session_schema_version"`
	SessionThreadID              pgtype.Text        `json:"session_thread_id"`
	SessionConfigurationRevision pgtype.Int8        `json:"session_configuration_revision"`
	SessionProfileRevision       pgtype.Int8        `json:"session_profile_revision"`
	SessionRevision              int64              `json:"session_revision"`
	SessionUpdatedAt             pgtype.Timestamptz `json:"session_updated_at"`
}

func (q *Queries) CheckpointAgentRuntimeSession(ctx context.Context, arg CheckpointAgentRuntimeSessionParams) (CheckpointAgentRuntimeSessionRow, error) {
	row := q.db.QueryRow(ctx, checkpointAgentRuntimeSession,
		arg.Session,
		arg.ProviderKind,
		arg.SessionSchemaVersion,
		arg.ThreadID,
		arg.ConfigurationRevision,
		arg.ContextKey,
		arg.ExpectedSessionRevision,
	)
	var i CheckpointAgentRuntimeSessionRow
	err := row.Scan(
		&i.ContextKey,
		&i.Session,
		&i.SessionProviderKind,
		&i.SessionSchemaVersion,
		&i.SessionThreadID,
		&i.SessionConfigurationRevision,
		&i.SessionProfileRevision,
		&i.SessionRevision,
		&i.SessionUpdatedAt,
	)
	return i, err
}

const claimAgentLocalRun = `-- name: ClaimAgentLocalRun :one
UPDATE agent_local_runs
SET status='running',epoch=$1::text,claim_id=$2::text,
    claim_configuration_revision=$3::bigint,
    attempt_count=attempt_count+1,
    started_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE run_id=$4::text
  AND context_key=$5::text
  AND status='queued'
  AND agent_document_run_claimable(agent_local_runs.run_id,agent_local_runs.context_key)
RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids
`

type ClaimAgentLocalRunParams struct {
	Epoch                      string `json:"epoch"`
	ClaimID                    string `json:"claim_id"`
	ClaimConfigurationRevision int64  `json:"claim_configuration_revision"`
	RunID                      string `json:"run_id"`
	ContextKey                 string `json:"context_key"`
}

func (q *Queries) ClaimAgentLocalRun(ctx context.Context, arg ClaimAgentLocalRunParams) (AgentLocalRun, error) {
	row := q.db.QueryRow(ctx, claimAgentLocalRun,
		arg.Epoch,
		arg.ClaimID,
		arg.ClaimConfigurationRevision,
		arg.RunID,
		arg.ContextKey,
	)
	var i AgentLocalRun
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.Terminal,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StartedAt,
		&i.FinishedAt,
		&i.AttemptCount,
		&i.CancellationRequested,
		&i.Epoch,
		&i.ClaimID,
		&i.ClaimConfigurationRevision,
		&i.Usage,
		&i.StatusRoomID,
		&i.ClaimProfileRevision,
		&i.TurnIds,
	)
	return i, err
}

const completeAgentRuntimeSteerInput = `-- name: CompleteAgentRuntimeSteerInput :execrows
UPDATE agent_runtime_inputs
SET status='handled',selection_result=$1::jsonb,
    steer_outcome=$2::text,
    local_run_id=$3::text,
    updated_at=clock_timestamp()
WHERE context_key=$4::text
  AND input_id=$5::text
  AND status='steering'
  AND steer_group_id=$6::text
`

type CompleteAgentRuntimeSteerInputParams struct {
	SelectionResult []byte      `json:"selection_result"`
	SteerOutcome    pgtype.Text `json:"steer_outcome"`
	LocalRunID      string      `json:"local_run_id"`
	ContextKey      string      `json:"context_key"`
	InputID         string      `json:"input_id"`
	SteerGroupID    string      `json:"steer_group_id"`
}

func (q *Queries) CompleteAgentRuntimeSteerInput(ctx context.Context, arg CompleteAgentRuntimeSteerInputParams) (int64, error) {
	result, err := q.db.Exec(ctx, completeAgentRuntimeSteerInput,
		arg.SelectionResult,
		arg.SteerOutcome,
		arg.LocalRunID,
		arg.ContextKey,
		arg.InputID,
		arg.SteerGroupID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const consumeAgentRuntimeLocalComputerEnrollment = `-- name: ConsumeAgentRuntimeLocalComputerEnrollment :one
UPDATE local_computer_enrollments
SET exchanged_at=clock_timestamp(),
    exchanged_generation=$1::bigint
WHERE enrollment_id=$2::text
  AND exchanged_at IS NULL
RETURNING enrollment_id, tenant_id, owner_actor_id, requested_computer_id, renews_existing_computer, display_name, redirect_uri, code_challenge, authorization_code_hash, expires_at, exchanged_at, exchanged_generation, created_at
`

type ConsumeAgentRuntimeLocalComputerEnrollmentParams struct {
	ExchangedGeneration int64  `json:"exchanged_generation"`
	EnrollmentID        string `json:"enrollment_id"`
}

func (q *Queries) ConsumeAgentRuntimeLocalComputerEnrollment(ctx context.Context, arg ConsumeAgentRuntimeLocalComputerEnrollmentParams) (LocalComputerEnrollment, error) {
	row := q.db.QueryRow(ctx, consumeAgentRuntimeLocalComputerEnrollment, arg.ExchangedGeneration, arg.EnrollmentID)
	var i LocalComputerEnrollment
	err := row.Scan(
		&i.EnrollmentID,
		&i.TenantID,
		&i.OwnerActorID,
		&i.RequestedComputerID,
		&i.RenewsExistingComputer,
		&i.DisplayName,
		&i.RedirectUri,
		&i.CodeChallenge,
		&i.AuthorizationCodeHash,
		&i.ExpiresAt,
		&i.ExchangedAt,
		&i.ExchangedGeneration,
		&i.CreatedAt,
	)
	return i, err
}

const countAgentRunStatusSegments = `-- name: CountAgentRunStatusSegments :one
SELECT count(DISTINCT segment_id)::bigint
FROM agent_runtime_status_events
WHERE local_run_id=$1::text
`

func (q *Queries) CountAgentRunStatusSegments(ctx context.Context, localRunID string) (int64, error) {
	row := q.db.QueryRow(ctx, countAgentRunStatusSegments, localRunID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const createAgentLocalRun = `-- name: CreateAgentLocalRun :one
INSERT INTO agent_local_runs(run_id,context_key,status)
VALUES($1::text,$2::text,'queued')
RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids
`

type CreateAgentLocalRunParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
}

func (q *Queries) CreateAgentLocalRun(ctx context.Context, arg CreateAgentLocalRunParams) (AgentLocalRun, error) {
	row := q.db.QueryRow(ctx, createAgentLocalRun, arg.RunID, arg.ContextKey)
	var i AgentLocalRun
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.Terminal,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StartedAt,
		&i.FinishedAt,
		&i.AttemptCount,
		&i.CancellationRequested,
		&i.Epoch,
		&i.ClaimID,
		&i.ClaimConfigurationRevision,
		&i.Usage,
		&i.StatusRoomID,
		&i.ClaimProfileRevision,
		&i.TurnIds,
	)
	return i, err
}

const deleteAgentExecutionContext = `-- name: DeleteAgentExecutionContext :execrows
DELETE FROM agent_execution_contexts context
WHERE context.context_key=$1::text
  AND context.state_revision=$2::bigint
  AND (
      context.context_kind<>'meta'
      OR NOT EXISTS (
          SELECT 1
          FROM agent_registrations registration
          WHERE registration.actor_id=context.agent_actor_id
            AND registration.tenant_id=context.tenant_id
            AND registration.agent_management_id=context.agent_management_id
            AND registration.status='active'
      )
  )
`

type DeleteAgentExecutionContextParams struct {
	ContextKey       string `json:"context_key"`
	ExpectedRevision int64  `json:"expected_revision"`
}

func (q *Queries) DeleteAgentExecutionContext(ctx context.Context, arg DeleteAgentExecutionContextParams) (int64, error) {
	result, err := q.db.Exec(ctx, deleteAgentExecutionContext, arg.ContextKey, arg.ExpectedRevision)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const deleteAgentLocalRunInputByMessage = `-- name: DeleteAgentLocalRunInputByMessage :execrows
DELETE FROM agent_local_run_inputs
WHERE context_key=$1::text
  AND input_id=$2::text
`

type DeleteAgentLocalRunInputByMessageParams struct {
	ContextKey string `json:"context_key"`
	InputID    string `json:"input_id"`
}

func (q *Queries) DeleteAgentLocalRunInputByMessage(ctx context.Context, arg DeleteAgentLocalRunInputByMessageParams) (int64, error) {
	result, err := q.db.Exec(ctx, deleteAgentLocalRunInputByMessage, arg.ContextKey, arg.InputID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const deleteAgentLocalRunInputsByContext = `-- name: DeleteAgentLocalRunInputsByContext :execrows
DELETE FROM agent_local_run_inputs
WHERE context_key=$1::text
`

func (q *Queries) DeleteAgentLocalRunInputsByContext(ctx context.Context, contextKey string) (int64, error) {
	result, err := q.db.Exec(ctx, deleteAgentLocalRunInputsByContext, contextKey)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const deleteAgentRuntimeLocalComputerEnrollment = `-- name: DeleteAgentRuntimeLocalComputerEnrollment :exec
DELETE FROM local_computer_enrollments
WHERE enrollment_id=$1::text
`

func (q *Queries) DeleteAgentRuntimeLocalComputerEnrollment(ctx context.Context, enrollmentID string) error {
	_, err := q.db.Exec(ctx, deleteAgentRuntimeLocalComputerEnrollment, enrollmentID)
	return err
}

const deleteAgentRuntimeSessionAtConfigurationRevision = `-- name: DeleteAgentRuntimeSessionAtConfigurationRevision :execrows
UPDATE agent_execution_contexts
SET session=NULL,session_provider_kind=NULL,session_schema_version=NULL,
    session_thread_id=NULL,session_configuration_revision=NULL,
    session_profile_revision=NULL,session_revision=0,session_updated_at=NULL,
    updated_at=clock_timestamp()
WHERE context_key=$1::text
  AND session IS NOT NULL
  AND session_configuration_revision=$2::bigint
`

type DeleteAgentRuntimeSessionAtConfigurationRevisionParams struct {
	ContextKey            string `json:"context_key"`
	ConfigurationRevision int64  `json:"configuration_revision"`
}

func (q *Queries) DeleteAgentRuntimeSessionAtConfigurationRevision(ctx context.Context, arg DeleteAgentRuntimeSessionAtConfigurationRevisionParams) (int64, error) {
	result, err := q.db.Exec(ctx, deleteAgentRuntimeSessionAtConfigurationRevision, arg.ContextKey, arg.ConfigurationRevision)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const deleteLocalComputerModelSnapshot = `-- name: DeleteLocalComputerModelSnapshot :exec
DELETE FROM local_computer_model_snapshots
WHERE computer_id=$1::text
`

func (q *Queries) DeleteLocalComputerModelSnapshot(ctx context.Context, computerID string) error {
	_, err := q.db.Exec(ctx, deleteLocalComputerModelSnapshot, computerID)
	return err
}

const deletePendingAgentRuntimeLocalComputerEnrollments = `-- name: DeletePendingAgentRuntimeLocalComputerEnrollments :exec
DELETE FROM local_computer_enrollments
WHERE tenant_id=$1::text
  AND owner_actor_id=$2::text
  AND exchanged_at IS NULL
`

type DeletePendingAgentRuntimeLocalComputerEnrollmentsParams struct {
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
}

func (q *Queries) DeletePendingAgentRuntimeLocalComputerEnrollments(ctx context.Context, arg DeletePendingAgentRuntimeLocalComputerEnrollmentsParams) error {
	_, err := q.db.Exec(ctx, deletePendingAgentRuntimeLocalComputerEnrollments, arg.TenantID, arg.OwnerActorID)
	return err
}

const expireRunNativeQuestions = `-- name: ExpireRunNativeQuestions :many
UPDATE decisions SET status='expired',finished_at=clock_timestamp()
WHERE request->'runtime'->>'execution_run_ref'=$1::text
  AND request ? 'runtime' AND status='pending'
  AND request->'runtime'->>'kind'='native_question'
RETURNING message_id
`

func (q *Queries) ExpireRunNativeQuestions(ctx context.Context, runID string) ([]string, error) {
	rows, err := q.db.Query(ctx, expireRunNativeQuestions, runID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var message_id string
		if err := rows.Scan(&message_id); err != nil {
			return nil, err
		}
		items = append(items, message_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getAgentExecutionContext = `-- name: GetAgentExecutionContext :one
SELECT context_key, tenant_id, agent_actor_id, agent_management_id, context_kind,
    task_id, target_residency, next_input_sequence,
    state_revision, room_id, membership_epoch_id, terminal_reason, terminated_at,
    document_id, room_kind, task_archive_suspended
FROM agent_execution_contexts
WHERE context_key=$1::text
`

type GetAgentExecutionContextRow struct {
	ContextKey           string             `json:"context_key"`
	TenantID             string             `json:"tenant_id"`
	AgentActorID         string             `json:"agent_actor_id"`
	AgentManagementID    string             `json:"agent_management_id"`
	ContextKind          string             `json:"context_kind"`
	TaskID               pgtype.Text        `json:"task_id"`
	TargetResidency      string             `json:"target_residency"`
	NextInputSequence    int64              `json:"next_input_sequence"`
	StateRevision        int64              `json:"state_revision"`
	RoomID               pgtype.Text        `json:"room_id"`
	MembershipEpochID    pgtype.Text        `json:"membership_epoch_id"`
	TerminalReason       pgtype.Text        `json:"terminal_reason"`
	TerminatedAt         pgtype.Timestamptz `json:"terminated_at"`
	DocumentID           pgtype.Text        `json:"document_id"`
	RoomKind             pgtype.Text        `json:"room_kind"`
	TaskArchiveSuspended bool               `json:"task_archive_suspended"`
}

func (q *Queries) GetAgentExecutionContext(ctx context.Context, contextKey string) (GetAgentExecutionContextRow, error) {
	row := q.db.QueryRow(ctx, getAgentExecutionContext, contextKey)
	var i GetAgentExecutionContextRow
	err := row.Scan(
		&i.ContextKey,
		&i.TenantID,
		&i.AgentActorID,
		&i.AgentManagementID,
		&i.ContextKind,
		&i.TaskID,
		&i.TargetResidency,
		&i.NextInputSequence,
		&i.StateRevision,
		&i.RoomID,
		&i.MembershipEpochID,
		&i.TerminalReason,
		&i.TerminatedAt,
		&i.DocumentID,
		&i.RoomKind,
		&i.TaskArchiveSuspended,
	)
	return i, err
}

const getAgentExecutionContextRuntimeEventCount = `-- name: GetAgentExecutionContextRuntimeEventCount :one
SELECT count(*)::bigint
FROM agent_runtime_status_events event
JOIN agent_local_runs run ON run.run_id=event.local_run_id
WHERE run.context_key=$1::text
`

func (q *Queries) GetAgentExecutionContextRuntimeEventCount(ctx context.Context, contextKey string) (int64, error) {
	row := q.db.QueryRow(ctx, getAgentExecutionContextRuntimeEventCount, contextKey)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const getAgentLocalRun = `-- name: GetAgentLocalRun :one
SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids
FROM agent_local_runs
WHERE context_key=$1::text
  AND run_id=$2::text
`

type GetAgentLocalRunParams struct {
	ContextKey string `json:"context_key"`
	RunID      string `json:"run_id"`
}

func (q *Queries) GetAgentLocalRun(ctx context.Context, arg GetAgentLocalRunParams) (AgentLocalRun, error) {
	row := q.db.QueryRow(ctx, getAgentLocalRun, arg.ContextKey, arg.RunID)
	var i AgentLocalRun
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.Terminal,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StartedAt,
		&i.FinishedAt,
		&i.AttemptCount,
		&i.CancellationRequested,
		&i.Epoch,
		&i.ClaimID,
		&i.ClaimConfigurationRevision,
		&i.Usage,
		&i.StatusRoomID,
		&i.ClaimProfileRevision,
		&i.TurnIds,
	)
	return i, err
}

const getAgentLocalRunContextKey = `-- name: GetAgentLocalRunContextKey :one
SELECT context_key FROM agent_local_runs WHERE run_id=$1::text
`

func (q *Queries) GetAgentLocalRunContextKey(ctx context.Context, runID string) (string, error) {
	row := q.db.QueryRow(ctx, getAgentLocalRunContextKey, runID)
	var context_key string
	err := row.Scan(&context_key)
	return context_key, err
}

const getAgentLocalRunReplyDelivered = `-- name: GetAgentLocalRunReplyDelivered :one
WITH target_run AS (
    SELECT run.run_id, run.started_at, run.finished_at,
           context.tenant_id, context.agent_actor_id, context.room_id
    FROM agent_local_runs run
    JOIN agent_execution_contexts context ON context.context_key=run.context_key
    WHERE run.context_key=$1::text
      AND run.run_id=$2::text
),
room_scope AS (
    SELECT target_run.room_id AS id
    FROM target_run
    WHERE target_run.room_id IS NOT NULL
    UNION ALL
    SELECT thread.id
    FROM target_run
    JOIN rooms thread
      ON thread.parent_room_id=target_run.room_id
     AND thread.deleted_at IS NULL
    WHERE target_run.room_id IS NOT NULL
)
SELECT (
    EXISTS (
        SELECT 1
        FROM messages message
        WHERE message.local_run_id=target_run.run_id
          AND message.message_kind='conversation'
    )
    OR EXISTS (
        SELECT 1
        FROM agent_presentation_sequences sequence
        WHERE sequence.local_run_id=target_run.run_id
    )
    OR (
        target_run.started_at IS NOT NULL
        AND target_run.room_id IS NOT NULL
        AND EXISTS (
            SELECT 1
            FROM messages message
            WHERE message.tenant_id=target_run.tenant_id
              AND message.author_actor_id=target_run.agent_actor_id
              AND message.message_kind='conversation'
              AND message.local_run_id IS NULL
              AND message.created_at>=target_run.started_at
              AND (target_run.finished_at IS NULL OR message.created_at<=target_run.finished_at)
              AND message.room_id IN (SELECT id FROM room_scope)
        )
    )
    OR (
        target_run.started_at IS NOT NULL
        AND target_run.room_id IS NOT NULL
        AND EXISTS (
            SELECT 1
            FROM agent_presentation_sequences sequence
            WHERE sequence.tenant_id=target_run.tenant_id
              AND sequence.agent_actor_id=target_run.agent_actor_id
              AND sequence.local_run_id IS NULL
              AND sequence.created_at>=target_run.started_at
              AND (target_run.finished_at IS NULL OR sequence.created_at<=target_run.finished_at)
              AND sequence.room_id IN (SELECT id FROM room_scope)
        )
    )
    OR (
        target_run.started_at IS NOT NULL
        AND target_run.room_id IS NOT NULL
        AND EXISTS (
            SELECT 1
            FROM message_reactions reaction
            WHERE reaction.tenant_id=target_run.tenant_id
              AND reaction.actor_id=target_run.agent_actor_id
              AND reaction.created_at>=target_run.started_at
              AND (target_run.finished_at IS NULL OR reaction.created_at<=target_run.finished_at)
              AND reaction.room_id IN (SELECT id FROM room_scope)
        )
    )
)::boolean AS replied
FROM target_run
`

type GetAgentLocalRunReplyDeliveredParams struct {
	ContextKey string `json:"context_key"`
	RunID      string `json:"run_id"`
}

// Checks whether TeamHub persisted a visible reply from the Run: a
// conversation Message or decision card attributed to the Run, a queued
// presentation sequence attributed to the Run, or an unattributed conversation
// Message, presentation sequence, or emoji Reaction written by the Agent in
// the Room or its Threads during the Run. Excluding rows attributed to another
// Run prevents delayed bubbles from an earlier sequence from satisfying this
// Run. The unattributed sequence and reaction branches have no (room_id,
// created_at) index; this query runs only on the suspected-missing-reply path
// and exits early on the indexed local_run_id checks for attributed replies.
func (q *Queries) GetAgentLocalRunReplyDelivered(ctx context.Context, arg GetAgentLocalRunReplyDeliveredParams) (bool, error) {
	row := q.db.QueryRow(ctx, getAgentLocalRunReplyDelivered, arg.ContextKey, arg.RunID)
	var replied bool
	err := row.Scan(&replied)
	return replied, err
}

const getAgentRunStatus = `-- name: GetAgentRunStatus :one
SELECT run.run_id,run.context_key,run.status,run.status_room_id::text AS status_room_id,
       run.created_at,run.updated_at,
       context.tenant_id,context.agent_actor_id,context.task_id,
       actor.kind AS agent_kind,actor.display_name AS agent_display_name,
       coalesce((SELECT max(event.event_ordinal) FROM agent_runtime_status_events event
                 WHERE event.local_run_id=run.run_id),0)::bigint AS event_ordinal,
       COALESCE(CASE WHEN run.status='canceled' THEN left(run.terminal->>'reason',1000) END,'')::text AS stop_reason,
       agent_local_run_replied(run.run_id)::boolean AS replied
FROM agent_local_runs run
JOIN agent_execution_contexts context ON context.context_key=run.context_key
JOIN actors actor ON actor.id=context.agent_actor_id AND actor.tenant_id=context.tenant_id
WHERE run.run_id=$1::text AND run.status_room_id IS NOT NULL
`

type GetAgentRunStatusRow struct {
	RunID            string             `json:"run_id"`
	ContextKey       string             `json:"context_key"`
	Status           string             `json:"status"`
	StatusRoomID     string             `json:"status_room_id"`
	CreatedAt        pgtype.Timestamptz `json:"created_at"`
	UpdatedAt        pgtype.Timestamptz `json:"updated_at"`
	TenantID         string             `json:"tenant_id"`
	AgentActorID     string             `json:"agent_actor_id"`
	TaskID           pgtype.Text        `json:"task_id"`
	AgentKind        string             `json:"agent_kind"`
	AgentDisplayName string             `json:"agent_display_name"`
	EventOrdinal     int64              `json:"event_ordinal"`
	StopReason       string             `json:"stop_reason"`
	Replied          bool               `json:"replied"`
}

// A Run with a status Room, with the Context facts its events and its
// agent_run.status_changed Room Event need.
func (q *Queries) GetAgentRunStatus(ctx context.Context, runID string) (GetAgentRunStatusRow, error) {
	row := q.db.QueryRow(ctx, getAgentRunStatus, runID)
	var i GetAgentRunStatusRow
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.StatusRoomID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TenantID,
		&i.AgentActorID,
		&i.TaskID,
		&i.AgentKind,
		&i.AgentDisplayName,
		&i.EventOrdinal,
		&i.StopReason,
		&i.Replied,
	)
	return i, err
}

const getAgentRunStatusForMessage = `-- name: GetAgentRunStatusForMessage :one
SELECT run.run_id,run.context_key,context.tenant_id,context.agent_actor_id,context.task_id,
       coalesce((SELECT max(event.event_ordinal) FROM agent_runtime_status_events event
                 WHERE event.local_run_id=run.run_id),0)::bigint AS event_ordinal
FROM messages message
JOIN agent_local_runs run ON run.run_id=message.local_run_id AND run.status_room_id IS NOT NULL
JOIN agent_execution_contexts context ON context.context_key=run.context_key
WHERE message.id=$1::text
  AND message.room_id=$2::text
  AND message.tenant_id=context.tenant_id
  AND message.author_actor_id=context.agent_actor_id
`

type GetAgentRunStatusForMessageParams struct {
	MessageID string `json:"message_id"`
	RoomID    string `json:"room_id"`
}

type GetAgentRunStatusForMessageRow struct {
	RunID        string      `json:"run_id"`
	ContextKey   string      `json:"context_key"`
	TenantID     string      `json:"tenant_id"`
	AgentActorID string      `json:"agent_actor_id"`
	TaskID       pgtype.Text `json:"task_id"`
	EventOrdinal int64       `json:"event_ordinal"`
}

func (q *Queries) GetAgentRunStatusForMessage(ctx context.Context, arg GetAgentRunStatusForMessageParams) (GetAgentRunStatusForMessageRow, error) {
	row := q.db.QueryRow(ctx, getAgentRunStatusForMessage, arg.MessageID, arg.RoomID)
	var i GetAgentRunStatusForMessageRow
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.TenantID,
		&i.AgentActorID,
		&i.TaskID,
		&i.EventOrdinal,
	)
	return i, err
}

const getAgentRunStatusTail = `-- name: GetAgentRunStatusTail :one
SELECT event_ordinal,segment_id,
       (event_type='presentation.output_created'
        OR (event_type='status.changed' AND payload->>'status'='stopped'))::boolean AS closes_segment
FROM agent_runtime_status_events
WHERE local_run_id=$1::text
ORDER BY event_ordinal DESC
LIMIT 1
`

type GetAgentRunStatusTailRow struct {
	EventOrdinal  int64  `json:"event_ordinal"`
	SegmentID     string `json:"segment_id"`
	ClosesSegment bool   `json:"closes_segment"`
}

// The last event of a Run: its ordinal and the segment it belongs to. An
// output or the stopped event closes its segment.
func (q *Queries) GetAgentRunStatusTail(ctx context.Context, localRunID string) (GetAgentRunStatusTailRow, error) {
	row := q.db.QueryRow(ctx, getAgentRunStatusTail, localRunID)
	var i GetAgentRunStatusTailRow
	err := row.Scan(&i.EventOrdinal, &i.SegmentID, &i.ClosesSegment)
	return i, err
}

const getAgentRuntimeInput = `-- name: GetAgentRuntimeInput :one
SELECT context_key, input_id, input_sequence, payload, payload_hash, source_kind, source_message_id, source_inbox_id, status, selection_result, steer_group_id, local_run_id, steer_outcome, created_at, updated_at
FROM agent_runtime_inputs
WHERE context_key=$1::text
  AND input_id=$2::text
`

type GetAgentRuntimeInputParams struct {
	ContextKey string `json:"context_key"`
	InputID    string `json:"input_id"`
}

func (q *Queries) GetAgentRuntimeInput(ctx context.Context, arg GetAgentRuntimeInputParams) (AgentRuntimeInput, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeInput, arg.ContextKey, arg.InputID)
	var i AgentRuntimeInput
	err := row.Scan(
		&i.ContextKey,
		&i.InputID,
		&i.InputSequence,
		&i.Payload,
		&i.PayloadHash,
		&i.SourceKind,
		&i.SourceMessageID,
		&i.SourceInboxID,
		&i.Status,
		&i.SelectionResult,
		&i.SteerGroupID,
		&i.LocalRunID,
		&i.SteerOutcome,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getAgentRuntimeLocalComputer = `-- name: GetAgentRuntimeLocalComputer :one
SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
FROM local_computers
WHERE computer_id=$1::text
`

func (q *Queries) GetAgentRuntimeLocalComputer(ctx context.Context, computerID string) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeLocalComputer, computerID)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const getAgentRuntimePresentationEventByCommand = `-- name: GetAgentRuntimePresentationEventByCommand :one
SELECT local_run_id, event_ordinal, command_id, event_type, payload, invocation_id, outcome, message_id, created_at, activity_id, segment_id
FROM agent_runtime_status_events
WHERE command_id=$1::text
`

func (q *Queries) GetAgentRuntimePresentationEventByCommand(ctx context.Context, commandID string) (AgentRuntimeStatusEvent, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimePresentationEventByCommand, commandID)
	var i AgentRuntimeStatusEvent
	err := row.Scan(
		&i.LocalRunID,
		&i.EventOrdinal,
		&i.CommandID,
		&i.EventType,
		&i.Payload,
		&i.InvocationID,
		&i.Outcome,
		&i.MessageID,
		&i.CreatedAt,
		&i.ActivityID,
		&i.SegmentID,
	)
	return i, err
}

const getAgentRuntimePresentationOutputEvent = `-- name: GetAgentRuntimePresentationOutputEvent :one
SELECT local_run_id, event_ordinal, command_id, event_type, payload, invocation_id, outcome, message_id, created_at, activity_id, segment_id
FROM agent_runtime_status_events
WHERE local_run_id=$1::text
  AND event_type='presentation.output_created'
  AND payload->>'output_id'=$2::text
`

type GetAgentRuntimePresentationOutputEventParams struct {
	LocalRunID string `json:"local_run_id"`
	OutputID   string `json:"output_id"`
}

func (q *Queries) GetAgentRuntimePresentationOutputEvent(ctx context.Context, arg GetAgentRuntimePresentationOutputEventParams) (AgentRuntimeStatusEvent, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimePresentationOutputEvent, arg.LocalRunID, arg.OutputID)
	var i AgentRuntimeStatusEvent
	err := row.Scan(
		&i.LocalRunID,
		&i.EventOrdinal,
		&i.CommandID,
		&i.EventType,
		&i.Payload,
		&i.InvocationID,
		&i.Outcome,
		&i.MessageID,
		&i.CreatedAt,
		&i.ActivityID,
		&i.SegmentID,
	)
	return i, err
}

const getAgentRuntimeRegistrationForRunnerByManagementID = `-- name: GetAgentRuntimeRegistrationForRunnerByManagementID :one
SELECT registration.actor_id,registration.tenant_id,registration.status,
       registration.agent_management_id,registration.configuration_revision,
       registration.runtime_configuration_revision,registration.assignment_revision,
       registration.instructions,registration.runtime_model,registration.runtime_reasoning_effort,
       registration.computer_id,
       registration.local_runtime_type,registration.workspace_grant_id,
       registration.agent_type,registration.created_by_actor_id,
       actor.display_name
FROM agent_registrations registration
JOIN actors actor
  ON actor.id=registration.actor_id
 AND actor.tenant_id=registration.tenant_id
WHERE registration.agent_management_id=$1::text
  AND registration.status IN ('active','revoked')
`

type GetAgentRuntimeRegistrationForRunnerByManagementIDRow struct {
	ActorID                      string      `json:"actor_id"`
	TenantID                     string      `json:"tenant_id"`
	Status                       string      `json:"status"`
	AgentManagementID            pgtype.Text `json:"agent_management_id"`
	ConfigurationRevision        int64       `json:"configuration_revision"`
	RuntimeConfigurationRevision int64       `json:"runtime_configuration_revision"`
	AssignmentRevision           int64       `json:"assignment_revision"`
	Instructions                 string      `json:"instructions"`
	RuntimeModel                 string      `json:"runtime_model"`
	RuntimeReasoningEffort       pgtype.Text `json:"runtime_reasoning_effort"`
	ComputerID                   pgtype.Text `json:"computer_id"`
	LocalRuntimeType             pgtype.Text `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text `json:"workspace_grant_id"`
	AgentType                    string      `json:"agent_type"`
	CreatedByActorID             string      `json:"created_by_actor_id"`
	DisplayName                  string      `json:"display_name"`
}

func (q *Queries) GetAgentRuntimeRegistrationForRunnerByManagementID(ctx context.Context, agentManagementID string) (GetAgentRuntimeRegistrationForRunnerByManagementIDRow, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeRegistrationForRunnerByManagementID, agentManagementID)
	var i GetAgentRuntimeRegistrationForRunnerByManagementIDRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.Status,
		&i.AgentManagementID,
		&i.ConfigurationRevision,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.AgentType,
		&i.CreatedByActorID,
		&i.DisplayName,
	)
	return i, err
}

const getAgentRuntimeSession = `-- name: GetAgentRuntimeSession :one
SELECT context_key, session, session_provider_kind, session_schema_version,
    session_thread_id, session_configuration_revision, session_profile_revision,
    session_revision, session_updated_at
FROM agent_execution_contexts
WHERE context_key=$1::text AND session IS NOT NULL
`

type GetAgentRuntimeSessionRow struct {
	ContextKey                   string             `json:"context_key"`
	Session                      []byte             `json:"session"`
	SessionProviderKind          pgtype.Text        `json:"session_provider_kind"`
	SessionSchemaVersion         pgtype.Int8        `json:"session_schema_version"`
	SessionThreadID              pgtype.Text        `json:"session_thread_id"`
	SessionConfigurationRevision pgtype.Int8        `json:"session_configuration_revision"`
	SessionProfileRevision       pgtype.Int8        `json:"session_profile_revision"`
	SessionRevision              int64              `json:"session_revision"`
	SessionUpdatedAt             pgtype.Timestamptz `json:"session_updated_at"`
}

func (q *Queries) GetAgentRuntimeSession(ctx context.Context, contextKey string) (GetAgentRuntimeSessionRow, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeSession, contextKey)
	var i GetAgentRuntimeSessionRow
	err := row.Scan(
		&i.ContextKey,
		&i.Session,
		&i.SessionProviderKind,
		&i.SessionSchemaVersion,
		&i.SessionThreadID,
		&i.SessionConfigurationRevision,
		&i.SessionProfileRevision,
		&i.SessionRevision,
		&i.SessionUpdatedAt,
	)
	return i, err
}

const getAgentRuntimeTaskInboxRoom = `-- name: GetAgentRuntimeTaskInboxRoom :one
SELECT link.room_id
FROM work_items item
JOIN work_item_room_links link
  ON link.work_item_id=item.id
 AND link.tenant_id=item.tenant_id
 AND link.link_type='work'
WHERE item.id=$1::text
  AND item.tenant_id=$2::text
  AND item.kind='task'
  AND item.archived_at IS NULL
  AND (
      EXISTS (
          SELECT 1 FROM work_item_assignments assignment
          WHERE assignment.work_item_id=item.id
            AND assignment.tenant_id=item.tenant_id
            AND assignment.actor_id=$3::text
      )
      OR EXISTS (
          SELECT 1 FROM task_execution_participants participant
          WHERE participant.task_id=item.id
            AND participant.tenant_id=item.tenant_id
            AND participant.actor_id=$3::text
      )
      OR EXISTS (
          SELECT 1
          FROM room_members membership
          WHERE membership.tenant_id=item.tenant_id
            AND membership.room_id=link.room_id
            AND membership.actor_id=$3::text
      )
  )
`

type GetAgentRuntimeTaskInboxRoomParams struct {
	TaskID       string `json:"task_id"`
	TenantID     string `json:"tenant_id"`
	AgentActorID string `json:"agent_actor_id"`
}

func (q *Queries) GetAgentRuntimeTaskInboxRoom(ctx context.Context, arg GetAgentRuntimeTaskInboxRoomParams) (string, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeTaskInboxRoom, arg.TaskID, arg.TenantID, arg.AgentActorID)
	var room_id string
	err := row.Scan(&room_id)
	return room_id, err
}

const getAgentRuntimeThreadInboxParentRoom = `-- name: GetAgentRuntimeThreadInboxParentRoom :one
SELECT thread.parent_room_id::text AS parent_room_id
FROM rooms thread
JOIN active_room_members membership
  ON membership.room_id=thread.parent_room_id
 AND membership.tenant_id=thread.tenant_id
JOIN actors actor
  ON actor.id=membership.actor_id
 AND actor.tenant_id=thread.tenant_id
WHERE thread.id=$1::text
  AND thread.tenant_id=$2::text
  AND thread.parent_room_id IS NOT NULL
  AND thread.deletion_started_at IS NULL
  AND thread.deleted_at IS NULL
  AND membership.actor_id=$3::text
  AND actor.kind='agent'
  AND (
      EXISTS (
          SELECT 1
          FROM messages root
          WHERE root.id=thread.root_message_id
            AND root.room_id=thread.parent_room_id
            AND root.tenant_id=thread.tenant_id
            AND root.author_actor_id=membership.actor_id
      ) OR EXISTS (
          SELECT 1
          FROM thread_room_list_actors listed
          WHERE listed.thread_room_id=thread.id
            AND listed.actor_id=membership.actor_id
            AND listed.tenant_id=thread.tenant_id
      )
  )
`

type GetAgentRuntimeThreadInboxParentRoomParams struct {
	ThreadID     string `json:"thread_id"`
	TenantID     string `json:"tenant_id"`
	AgentActorID string `json:"agent_actor_id"`
}

func (q *Queries) GetAgentRuntimeThreadInboxParentRoom(ctx context.Context, arg GetAgentRuntimeThreadInboxParentRoomParams) (string, error) {
	row := q.db.QueryRow(ctx, getAgentRuntimeThreadInboxParentRoom, arg.ThreadID, arg.TenantID, arg.AgentActorID)
	var parent_room_id string
	err := row.Scan(&parent_room_id)
	return parent_room_id, err
}

const getAgentSteerGroupRun = `-- name: GetAgentSteerGroupRun :one
SELECT local_run_id::text FROM agent_runtime_inputs
WHERE context_key=$1::text
  AND steer_group_id=$2::text
  AND status='handled' AND local_run_id IS NOT NULL
ORDER BY input_sequence
LIMIT 1
`

type GetAgentSteerGroupRunParams struct {
	ContextKey   string `json:"context_key"`
	SteerGroupID string `json:"steer_group_id"`
}

// The Run a settled steer group became or joined.
func (q *Queries) GetAgentSteerGroupRun(ctx context.Context, arg GetAgentSteerGroupRunParams) (string, error) {
	row := q.db.QueryRow(ctx, getAgentSteerGroupRun, arg.ContextKey, arg.SteerGroupID)
	var local_run_id string
	err := row.Scan(&local_run_id)
	return local_run_id, err
}

const getLatestAgentRuntimeActivityEvent = `-- name: GetLatestAgentRuntimeActivityEvent :one
SELECT event_type,outcome
FROM agent_runtime_status_events
WHERE local_run_id=$1::text
  AND activity_id=$2::text
ORDER BY event_ordinal DESC
LIMIT 1
`

type GetLatestAgentRuntimeActivityEventParams struct {
	LocalRunID string `json:"local_run_id"`
	ActivityID string `json:"activity_id"`
}

type GetLatestAgentRuntimeActivityEventRow struct {
	EventType string      `json:"event_type"`
	Outcome   pgtype.Text `json:"outcome"`
}

func (q *Queries) GetLatestAgentRuntimeActivityEvent(ctx context.Context, arg GetLatestAgentRuntimeActivityEventParams) (GetLatestAgentRuntimeActivityEventRow, error) {
	row := q.db.QueryRow(ctx, getLatestAgentRuntimeActivityEvent, arg.LocalRunID, arg.ActivityID)
	var i GetLatestAgentRuntimeActivityEventRow
	err := row.Scan(&i.EventType, &i.Outcome)
	return i, err
}

const getLocalComputerModelSnapshot = `-- name: GetLocalComputerModelSnapshot :one
SELECT snapshot,host
FROM local_computer_model_snapshots
WHERE computer_id=$1::text
`

type GetLocalComputerModelSnapshotRow struct {
	Snapshot []byte `json:"snapshot"`
	Host     []byte `json:"host"`
}

func (q *Queries) GetLocalComputerModelSnapshot(ctx context.Context, computerID string) (GetLocalComputerModelSnapshotRow, error) {
	row := q.db.QueryRow(ctx, getLocalComputerModelSnapshot, computerID)
	var i GetLocalComputerModelSnapshotRow
	err := row.Scan(&i.Snapshot, &i.Host)
	return i, err
}

const getMaterializableAgentRuntimeRegistrationByManagementID = `-- name: GetMaterializableAgentRuntimeRegistrationByManagementID :one
SELECT registration.actor_id,registration.tenant_id,registration.status,
       registration.agent_management_id,registration.configuration_revision,
       registration.runtime_configuration_revision,registration.assignment_revision,
       registration.instructions,registration.runtime_model,registration.runtime_reasoning_effort,
       registration.computer_id,
       registration.local_runtime_type,registration.workspace_grant_id,
       registration.agent_type,registration.created_by_actor_id,
       actor.display_name
FROM agent_registrations registration
JOIN actors actor
  ON actor.id=registration.actor_id
 AND actor.tenant_id=registration.tenant_id
WHERE registration.agent_management_id=$1::text
  AND registration.status='active'
`

type GetMaterializableAgentRuntimeRegistrationByManagementIDRow struct {
	ActorID                      string      `json:"actor_id"`
	TenantID                     string      `json:"tenant_id"`
	Status                       string      `json:"status"`
	AgentManagementID            pgtype.Text `json:"agent_management_id"`
	ConfigurationRevision        int64       `json:"configuration_revision"`
	RuntimeConfigurationRevision int64       `json:"runtime_configuration_revision"`
	AssignmentRevision           int64       `json:"assignment_revision"`
	Instructions                 string      `json:"instructions"`
	RuntimeModel                 string      `json:"runtime_model"`
	RuntimeReasoningEffort       pgtype.Text `json:"runtime_reasoning_effort"`
	ComputerID                   pgtype.Text `json:"computer_id"`
	LocalRuntimeType             pgtype.Text `json:"local_runtime_type"`
	WorkspaceGrantID             pgtype.Text `json:"workspace_grant_id"`
	AgentType                    string      `json:"agent_type"`
	CreatedByActorID             string      `json:"created_by_actor_id"`
	DisplayName                  string      `json:"display_name"`
}

func (q *Queries) GetMaterializableAgentRuntimeRegistrationByManagementID(ctx context.Context, agentManagementID string) (GetMaterializableAgentRuntimeRegistrationByManagementIDRow, error) {
	row := q.db.QueryRow(ctx, getMaterializableAgentRuntimeRegistrationByManagementID, agentManagementID)
	var i GetMaterializableAgentRuntimeRegistrationByManagementIDRow
	err := row.Scan(
		&i.ActorID,
		&i.TenantID,
		&i.Status,
		&i.AgentManagementID,
		&i.ConfigurationRevision,
		&i.RuntimeConfigurationRevision,
		&i.AssignmentRevision,
		&i.Instructions,
		&i.RuntimeModel,
		&i.RuntimeReasoningEffort,
		&i.ComputerID,
		&i.LocalRuntimeType,
		&i.WorkspaceGrantID,
		&i.AgentType,
		&i.CreatedByActorID,
		&i.DisplayName,
	)
	return i, err
}

const getRoomRunStatusForAccount = `-- name: GetRoomRunStatusForAccount :one
SELECT run.run_id,run.context_key,run.status,run.created_at,run.updated_at,
       context.tenant_id,context.agent_actor_id,context.task_id,
       actor.kind AS agent_kind,actor.display_name AS agent_display_name,
       coalesce((SELECT max(event.event_ordinal) FROM agent_runtime_status_events event
                 WHERE event.local_run_id=run.run_id),0)::bigint AS event_ordinal,
       COALESCE(CASE WHEN run.status='canceled' THEN left(run.terminal->>'reason',1000) END,'')::text AS stop_reason,
       agent_local_run_replied(run.run_id)::boolean AS replied
FROM rooms room
JOIN actors caller ON caller.tenant_id=room.tenant_id
 AND caller.account_id=$1::text AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=collaboration_membership_room_id(room.id) AND membership.actor_id=caller.id
 AND room_actor_participating(room.id,caller.id)
JOIN agent_local_runs run ON run.status_room_id=room.id
JOIN agent_execution_contexts context ON context.context_key=run.context_key AND context.tenant_id=room.tenant_id
JOIN actors actor ON actor.id=context.agent_actor_id AND actor.tenant_id=context.tenant_id
WHERE room.id=$2::text AND run.run_id=$3::text
`

type GetRoomRunStatusForAccountParams struct {
	AccountID string `json:"account_id"`
	RoomID    string `json:"room_id"`
	RunID     string `json:"run_id"`
}

type GetRoomRunStatusForAccountRow struct {
	RunID            string             `json:"run_id"`
	ContextKey       string             `json:"context_key"`
	Status           string             `json:"status"`
	CreatedAt        pgtype.Timestamptz `json:"created_at"`
	UpdatedAt        pgtype.Timestamptz `json:"updated_at"`
	TenantID         string             `json:"tenant_id"`
	AgentActorID     string             `json:"agent_actor_id"`
	TaskID           pgtype.Text        `json:"task_id"`
	AgentKind        string             `json:"agent_kind"`
	AgentDisplayName string             `json:"agent_display_name"`
	EventOrdinal     int64              `json:"event_ordinal"`
	StopReason       string             `json:"stop_reason"`
	Replied          bool               `json:"replied"`
}

func (q *Queries) GetRoomRunStatusForAccount(ctx context.Context, arg GetRoomRunStatusForAccountParams) (GetRoomRunStatusForAccountRow, error) {
	row := q.db.QueryRow(ctx, getRoomRunStatusForAccount, arg.AccountID, arg.RoomID, arg.RunID)
	var i GetRoomRunStatusForAccountRow
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TenantID,
		&i.AgentActorID,
		&i.TaskID,
		&i.AgentKind,
		&i.AgentDisplayName,
		&i.EventOrdinal,
		&i.StopReason,
		&i.Replied,
	)
	return i, err
}

const getRunningAgentLocalRun = `-- name: GetRunningAgentLocalRun :one
SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids FROM agent_local_runs
WHERE context_key=$1::text AND status='running'
LIMIT 1
`

func (q *Queries) GetRunningAgentLocalRun(ctx context.Context, contextKey string) (AgentLocalRun, error) {
	row := q.db.QueryRow(ctx, getRunningAgentLocalRun, contextKey)
	var i AgentLocalRun
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.Terminal,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StartedAt,
		&i.FinishedAt,
		&i.AttemptCount,
		&i.CancellationRequested,
		&i.Epoch,
		&i.ClaimID,
		&i.ClaimConfigurationRevision,
		&i.Usage,
		&i.StatusRoomID,
		&i.ClaimProfileRevision,
		&i.TurnIds,
	)
	return i, err
}

const insertAgentExecutionContext = `-- name: InsertAgentExecutionContext :execrows
INSERT INTO agent_execution_contexts(
    context_key,tenant_id,agent_actor_id,agent_management_id,
    context_kind,task_id,room_id,room_kind,membership_epoch_id,document_id,target_residency
)
SELECT
    $1::text,registration.tenant_id,registration.actor_id,
    registration.agent_management_id,$2::text,
    $3::text,$4::text,
    CASE
        WHEN $2::text='meta' AND $4::text IS NOT NULL THEN
            CASE WHEN EXISTS (
                SELECT 1 FROM rooms direct
                WHERE direct.id=$4::text
                  AND direct.tenant_id=registration.tenant_id
                  AND direct.direct_agent_actor_id IS NOT NULL
            ) THEN 'direct' ELSE 'collaboration' END
        ELSE NULL
    END,
    membership.membership_epoch_id,$5::text,
    $6::text
FROM agent_registrations registration
LEFT JOIN active_room_members membership
  ON membership.actor_id=registration.actor_id
 AND membership.tenant_id=registration.tenant_id
 AND membership.room_id=$4::text
WHERE registration.agent_management_id=$7::text
  AND registration.status='active'
  AND (
      (
          $2::text='meta'
          AND $3::text IS NULL
          AND $5::text IS NULL
          AND $4::text IS NOT NULL
          AND membership.membership_epoch_id IS NOT NULL
          AND NOT EXISTS (
              SELECT 1 FROM work_item_room_links link
              JOIN work_items item ON item.id=link.work_item_id AND item.tenant_id=link.tenant_id
              WHERE link.tenant_id=registration.tenant_id
                AND link.room_id=$4::text
                AND link.link_type='work' AND item.kind='task'
          )
      )
      OR (
          $2::text='alter_ego'
          AND $3::text IS NOT NULL
          AND $4::text IS NULL
          AND $5::text IS NULL
          AND EXISTS (
              SELECT 1
              FROM work_items item
              JOIN task_execution_generations generation
                ON generation.task_id=item.id
               AND generation.tenant_id=item.tenant_id
               AND generation.generation=item.task_execution_generation
               AND generation.terminal_at IS NULL
              JOIN task_execution_participants participant
                ON participant.task_id=item.id
               AND participant.tenant_id=item.tenant_id
               AND participant.generation=item.task_execution_generation
               AND participant.actor_id=registration.actor_id
               AND participant.agent_management_id=registration.agent_management_id
              LEFT JOIN work_item_room_links work_room
                ON work_room.work_item_id=item.id
               AND work_room.tenant_id=item.tenant_id
               AND work_room.link_type='work'
              LEFT JOIN rooms room
                ON room.id=work_room.room_id
               AND room.tenant_id=work_room.tenant_id
               AND room.deleted_at IS NULL AND room.deletion_started_at IS NULL
              WHERE item.id=$3::text
                AND item.tenant_id=registration.tenant_id
                AND item.kind='task'
 AND (work_room.room_id IS NULL OR room.id IS NOT NULL)
                AND item.archived_at IS NULL
                AND item.state<>'resolved'
                AND item.task_execution_generation IS NOT NULL
          )
      )
      OR (
          $2::text='document'
          AND $3::text IS NULL
          AND $4::text IS NULL
          AND $5::text IS NOT NULL
          AND (
              document_comment_agent_readable(
                  registration.tenant_id,$5::text,registration.actor_id
              )
          )
      )
  )
ON CONFLICT DO NOTHING
`

type InsertAgentExecutionContextParams struct {
	ContextKey        string      `json:"context_key"`
	ContextKind       string      `json:"context_kind"`
	TaskID            pgtype.Text `json:"task_id"`
	RoomID            pgtype.Text `json:"room_id"`
	DocumentID        pgtype.Text `json:"document_id"`
	TargetResidency   string      `json:"target_residency"`
	AgentManagementID string      `json:"agent_management_id"`
}

func (q *Queries) InsertAgentExecutionContext(ctx context.Context, arg InsertAgentExecutionContextParams) (int64, error) {
	result, err := q.db.Exec(ctx, insertAgentExecutionContext,
		arg.ContextKey,
		arg.ContextKind,
		arg.TaskID,
		arg.RoomID,
		arg.DocumentID,
		arg.TargetResidency,
		arg.AgentManagementID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const insertAgentLocalRunInput = `-- name: InsertAgentLocalRunInput :exec
INSERT INTO agent_local_run_inputs(run_id,context_key,input_id,relation,ordinal)
VALUES(
    $1::text,$2::text,
    $3::text,$4::text,$5::bigint
)
`

type InsertAgentLocalRunInputParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
	InputID    string `json:"input_id"`
	Relation   string `json:"relation"`
	Ordinal    int64  `json:"ordinal"`
}

func (q *Queries) InsertAgentLocalRunInput(ctx context.Context, arg InsertAgentLocalRunInputParams) error {
	_, err := q.db.Exec(ctx, insertAgentLocalRunInput,
		arg.RunID,
		arg.ContextKey,
		arg.InputID,
		arg.Relation,
		arg.Ordinal,
	)
	return err
}

const insertAgentLocalRunSteerInput = `-- name: InsertAgentLocalRunSteerInput :execrows
INSERT INTO agent_local_run_inputs(run_id,context_key,input_id,relation,ordinal)
VALUES(
    $1::text,$2::text,
    $3::text,'steer',$4::bigint
)
ON CONFLICT(run_id,input_id) DO NOTHING
`

type InsertAgentLocalRunSteerInputParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
	InputID    string `json:"input_id"`
	Ordinal    int64  `json:"ordinal"`
}

func (q *Queries) InsertAgentLocalRunSteerInput(ctx context.Context, arg InsertAgentLocalRunSteerInputParams) (int64, error) {
	result, err := q.db.Exec(ctx, insertAgentLocalRunSteerInput,
		arg.RunID,
		arg.ContextKey,
		arg.InputID,
		arg.Ordinal,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const insertAgentRuntimeInput = `-- name: InsertAgentRuntimeInput :one
INSERT INTO agent_runtime_inputs(
    context_key,input_id,payload,payload_hash,source_kind,
    source_message_id,source_inbox_id,status,selection_result,
    steer_group_id,local_run_id,steer_outcome
) VALUES(
    $1::text,$2::text,
    $3::jsonb,
    $4::bytea,$5::text,
    $6::text,$7::text,
    $8::text,$9::jsonb,
    $10::text,$11::text,
    $12::text
)
RETURNING input_sequence
`

type InsertAgentRuntimeInputParams struct {
	ContextKey      string      `json:"context_key"`
	InputID         string      `json:"input_id"`
	Payload         []byte      `json:"payload"`
	PayloadHash     []byte      `json:"payload_hash"`
	SourceKind      string      `json:"source_kind"`
	SourceMessageID pgtype.Text `json:"source_message_id"`
	SourceInboxID   pgtype.Text `json:"source_inbox_id"`
	Status          string      `json:"status"`
	SelectionResult []byte      `json:"selection_result"`
	SteerGroupID    pgtype.Text `json:"steer_group_id"`
	LocalRunID      pgtype.Text `json:"local_run_id"`
	SteerOutcome    pgtype.Text `json:"steer_outcome"`
}

// The global input sequence orders a Context's inputs without a per-Context
// counter, so Message transactions queue inputs without the Context lock.
func (q *Queries) InsertAgentRuntimeInput(ctx context.Context, arg InsertAgentRuntimeInputParams) (int64, error) {
	row := q.db.QueryRow(ctx, insertAgentRuntimeInput,
		arg.ContextKey,
		arg.InputID,
		arg.Payload,
		arg.PayloadHash,
		arg.SourceKind,
		arg.SourceMessageID,
		arg.SourceInboxID,
		arg.Status,
		arg.SelectionResult,
		arg.SteerGroupID,
		arg.LocalRunID,
		arg.SteerOutcome,
	)
	var input_sequence int64
	err := row.Scan(&input_sequence)
	return input_sequence, err
}

const insertAgentRuntimeLocalComputer = `-- name: InsertAgentRuntimeLocalComputer :one
INSERT INTO local_computers(
    computer_id,display_name,status,capacity,owner_tenant_id,owner_actor_id
) VALUES(
    $1::text,$2::text,'offline',1,
    $3::text,$4::text
)
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

type InsertAgentRuntimeLocalComputerParams struct {
	ComputerID    string `json:"computer_id"`
	DisplayName   string `json:"display_name"`
	OwnerTenantID string `json:"owner_tenant_id"`
	OwnerActorID  string `json:"owner_actor_id"`
}

func (q *Queries) InsertAgentRuntimeLocalComputer(ctx context.Context, arg InsertAgentRuntimeLocalComputerParams) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, insertAgentRuntimeLocalComputer,
		arg.ComputerID,
		arg.DisplayName,
		arg.OwnerTenantID,
		arg.OwnerActorID,
	)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const insertAgentRuntimeLocalComputerEnrollment = `-- name: InsertAgentRuntimeLocalComputerEnrollment :one
INSERT INTO local_computer_enrollments(
    enrollment_id,tenant_id,owner_actor_id,requested_computer_id,
    renews_existing_computer,display_name,redirect_uri,code_challenge,
    authorization_code_hash,expires_at
) VALUES(
    $1::text,$2::text,
    $3::text,$4::text,
    $5::boolean,$6::text,
    $7::text,$8::text,
    $9::bytea,$10::timestamptz
)
RETURNING enrollment_id, tenant_id, owner_actor_id, requested_computer_id, renews_existing_computer, display_name, redirect_uri, code_challenge, authorization_code_hash, expires_at, exchanged_at, exchanged_generation, created_at
`

type InsertAgentRuntimeLocalComputerEnrollmentParams struct {
	EnrollmentID           string             `json:"enrollment_id"`
	TenantID               string             `json:"tenant_id"`
	OwnerActorID           string             `json:"owner_actor_id"`
	ComputerID             string             `json:"computer_id"`
	RenewsExistingComputer bool               `json:"renews_existing_computer"`
	DisplayName            string             `json:"display_name"`
	RedirectUri            string             `json:"redirect_uri"`
	CodeChallenge          string             `json:"code_challenge"`
	AuthorizationCodeHash  []byte             `json:"authorization_code_hash"`
	ExpiresAt              pgtype.Timestamptz `json:"expires_at"`
}

func (q *Queries) InsertAgentRuntimeLocalComputerEnrollment(ctx context.Context, arg InsertAgentRuntimeLocalComputerEnrollmentParams) (LocalComputerEnrollment, error) {
	row := q.db.QueryRow(ctx, insertAgentRuntimeLocalComputerEnrollment,
		arg.EnrollmentID,
		arg.TenantID,
		arg.OwnerActorID,
		arg.ComputerID,
		arg.RenewsExistingComputer,
		arg.DisplayName,
		arg.RedirectUri,
		arg.CodeChallenge,
		arg.AuthorizationCodeHash,
		arg.ExpiresAt,
	)
	var i LocalComputerEnrollment
	err := row.Scan(
		&i.EnrollmentID,
		&i.TenantID,
		&i.OwnerActorID,
		&i.RequestedComputerID,
		&i.RenewsExistingComputer,
		&i.DisplayName,
		&i.RedirectUri,
		&i.CodeChallenge,
		&i.AuthorizationCodeHash,
		&i.ExpiresAt,
		&i.ExchangedAt,
		&i.ExchangedGeneration,
		&i.CreatedAt,
	)
	return i, err
}

const insertAgentRuntimePresentationEvent = `-- name: InsertAgentRuntimePresentationEvent :one
INSERT INTO agent_runtime_status_events(
    local_run_id,event_ordinal,segment_id,command_id,event_type,payload,
    invocation_id,outcome,message_id,activity_id
) VALUES(
    $1::text,$2::bigint,
    $3::text,$4::text,$5::text,
    $6::jsonb,$7::text,
    $8::text,$9::text,
    $10::text
)
RETURNING local_run_id, event_ordinal, command_id, event_type, payload, invocation_id, outcome, message_id, created_at, activity_id, segment_id
`

type InsertAgentRuntimePresentationEventParams struct {
	LocalRunID   string      `json:"local_run_id"`
	EventOrdinal int64       `json:"event_ordinal"`
	SegmentID    string      `json:"segment_id"`
	CommandID    string      `json:"command_id"`
	EventType    string      `json:"event_type"`
	Payload      []byte      `json:"payload"`
	InvocationID pgtype.Text `json:"invocation_id"`
	Outcome      pgtype.Text `json:"outcome"`
	MessageID    pgtype.Text `json:"message_id"`
	ActivityID   pgtype.Text `json:"activity_id"`
}

func (q *Queries) InsertAgentRuntimePresentationEvent(ctx context.Context, arg InsertAgentRuntimePresentationEventParams) (AgentRuntimeStatusEvent, error) {
	row := q.db.QueryRow(ctx, insertAgentRuntimePresentationEvent,
		arg.LocalRunID,
		arg.EventOrdinal,
		arg.SegmentID,
		arg.CommandID,
		arg.EventType,
		arg.Payload,
		arg.InvocationID,
		arg.Outcome,
		arg.MessageID,
		arg.ActivityID,
	)
	var i AgentRuntimeStatusEvent
	err := row.Scan(
		&i.LocalRunID,
		&i.EventOrdinal,
		&i.CommandID,
		&i.EventType,
		&i.Payload,
		&i.InvocationID,
		&i.Outcome,
		&i.MessageID,
		&i.CreatedAt,
		&i.ActivityID,
		&i.SegmentID,
	)
	return i, err
}

const insertAgentServiceEpoch = `-- name: InsertAgentServiceEpoch :exec
INSERT INTO agent_service_epochs(epoch) VALUES($1::text)
`

func (q *Queries) InsertAgentServiceEpoch(ctx context.Context, epoch string) error {
	_, err := q.db.Exec(ctx, insertAgentServiceEpoch, epoch)
	return err
}

const isAgentContextInboxAuthorized = `-- name: IsAgentContextInboxAuthorized :one
SELECT agent_context_can_receive_inbox($1::text,$2::text)::boolean
`

type IsAgentContextInboxAuthorizedParams struct {
	ContextKey string `json:"context_key"`
	InboxID    string `json:"inbox_id"`
}

func (q *Queries) IsAgentContextInboxAuthorized(ctx context.Context, arg IsAgentContextInboxAuthorizedParams) (bool, error) {
	row := q.db.QueryRow(ctx, isAgentContextInboxAuthorized, arg.ContextKey, arg.InboxID)
	var column_1 bool
	err := row.Scan(&column_1)
	return column_1, err
}

const isAgentExecutionContextRoomAuthorized = `-- name: IsAgentExecutionContextRoomAuthorized :one
SELECT EXISTS (
    SELECT 1
    FROM room_members membership
    WHERE membership.tenant_id=$1::text
      AND membership.room_id=$2::text
      AND membership.actor_id=$3::text
      AND membership.membership_epoch_id=$4::text
)
`

type IsAgentExecutionContextRoomAuthorizedParams struct {
	TenantID          string `json:"tenant_id"`
	RoomID            string `json:"room_id"`
	AgentActorID      string `json:"agent_actor_id"`
	MembershipEpochID string `json:"membership_epoch_id"`
}

func (q *Queries) IsAgentExecutionContextRoomAuthorized(ctx context.Context, arg IsAgentExecutionContextRoomAuthorizedParams) (bool, error) {
	row := q.db.QueryRow(ctx, isAgentExecutionContextRoomAuthorized,
		arg.TenantID,
		arg.RoomID,
		arg.AgentActorID,
		arg.MembershipEpochID,
	)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const listAgentContextMessageSteers = `-- name: ListAgentContextMessageSteers :many
SELECT context_key, input_id, input_sequence, payload, payload_hash, source_kind, source_message_id, source_inbox_id, status, selection_result, steer_group_id, local_run_id, steer_outcome, created_at, updated_at FROM agent_runtime_inputs
WHERE context_key=$1::text AND status='steering'
  AND selection_result->>'selected' IN ('trusted_inbox_notification','runtime_response')
ORDER BY input_sequence
`

// Steers TeamHub queued from Messages for this Context that the Agent
// Service has not settled yet, in input order.
func (q *Queries) ListAgentContextMessageSteers(ctx context.Context, contextKey string) ([]AgentRuntimeInput, error) {
	rows, err := q.db.Query(ctx, listAgentContextMessageSteers, contextKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []AgentRuntimeInput{}
	for rows.Next() {
		var i AgentRuntimeInput
		if err := rows.Scan(
			&i.ContextKey,
			&i.InputID,
			&i.InputSequence,
			&i.Payload,
			&i.PayloadHash,
			&i.SourceKind,
			&i.SourceMessageID,
			&i.SourceInboxID,
			&i.Status,
			&i.SelectionResult,
			&i.SteerGroupID,
			&i.LocalRunID,
			&i.SteerOutcome,
			&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 listAgentContextRunsOfEarlierEpoch = `-- name: ListAgentContextRunsOfEarlierEpoch :many
SELECT run_id FROM agent_local_runs
WHERE context_key=$1::text AND status='running'
  AND epoch IS DISTINCT FROM $2::text
ORDER BY run_id
`

type ListAgentContextRunsOfEarlierEpochParams struct {
	ContextKey string `json:"context_key"`
	Epoch      string `json:"epoch"`
}

func (q *Queries) ListAgentContextRunsOfEarlierEpoch(ctx context.Context, arg ListAgentContextRunsOfEarlierEpochParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentContextRunsOfEarlierEpoch, arg.ContextKey, arg.Epoch)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var run_id string
		if err := rows.Scan(&run_id); err != nil {
			return nil, err
		}
		items = append(items, run_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentContextsWithQueuedWork = `-- name: ListAgentContextsWithQueuedWork :many
SELECT DISTINCT waiting.context_key::text AS context_key
FROM (
    SELECT run.context_key FROM agent_local_runs run WHERE run.status='queued'
    UNION ALL
    SELECT input.context_key FROM agent_runtime_inputs input
    WHERE input.status='steering'
      AND input.selection_result->>'selected' IN ('trusted_inbox_notification','runtime_response')
) waiting
JOIN agent_execution_contexts context ON context.context_key=waiting.context_key AND context.terminal_reason IS NULL
ORDER BY 1
LIMIT 1000
`

// Contexts a newly started process takes up at once: queued Runs and Message
// steers, however recent.
func (q *Queries) ListAgentContextsWithQueuedWork(ctx context.Context) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentContextsWithQueuedWork)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentExecutionContextsByManagementID = `-- name: ListAgentExecutionContextsByManagementID :many
SELECT context_key, tenant_id, agent_actor_id, agent_management_id, context_kind,
    task_id, target_residency, next_input_sequence,
    state_revision, room_id, membership_epoch_id, terminal_reason, terminated_at,
    document_id, room_kind, task_archive_suspended
FROM agent_execution_contexts
WHERE agent_management_id=$1::text
ORDER BY context_key
`

type ListAgentExecutionContextsByManagementIDRow struct {
	ContextKey           string             `json:"context_key"`
	TenantID             string             `json:"tenant_id"`
	AgentActorID         string             `json:"agent_actor_id"`
	AgentManagementID    string             `json:"agent_management_id"`
	ContextKind          string             `json:"context_kind"`
	TaskID               pgtype.Text        `json:"task_id"`
	TargetResidency      string             `json:"target_residency"`
	NextInputSequence    int64              `json:"next_input_sequence"`
	StateRevision        int64              `json:"state_revision"`
	RoomID               pgtype.Text        `json:"room_id"`
	MembershipEpochID    pgtype.Text        `json:"membership_epoch_id"`
	TerminalReason       pgtype.Text        `json:"terminal_reason"`
	TerminatedAt         pgtype.Timestamptz `json:"terminated_at"`
	DocumentID           pgtype.Text        `json:"document_id"`
	RoomKind             pgtype.Text        `json:"room_kind"`
	TaskArchiveSuspended bool               `json:"task_archive_suspended"`
}

func (q *Queries) ListAgentExecutionContextsByManagementID(ctx context.Context, agentManagementID string) ([]ListAgentExecutionContextsByManagementIDRow, error) {
	rows, err := q.db.Query(ctx, listAgentExecutionContextsByManagementID, agentManagementID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAgentExecutionContextsByManagementIDRow{}
	for rows.Next() {
		var i ListAgentExecutionContextsByManagementIDRow
		if err := rows.Scan(
			&i.ContextKey,
			&i.TenantID,
			&i.AgentActorID,
			&i.AgentManagementID,
			&i.ContextKind,
			&i.TaskID,
			&i.TargetResidency,
			&i.NextInputSequence,
			&i.StateRevision,
			&i.RoomID,
			&i.MembershipEpochID,
			&i.TerminalReason,
			&i.TerminatedAt,
			&i.DocumentID,
			&i.RoomKind,
			&i.TaskArchiveSuspended,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentLocalRunInputs = `-- name: ListAgentLocalRunInputs :many
SELECT input.context_key, input.input_id, input.input_sequence, input.payload, input.payload_hash, input.source_kind, input.source_message_id, input.source_inbox_id, input.status, input.selection_result, input.steer_group_id, input.local_run_id, input.steer_outcome, input.created_at, input.updated_at,
       relation.relation AS run_relation,relation.ordinal AS run_ordinal
FROM agent_local_run_inputs relation
JOIN agent_runtime_inputs input
  ON input.context_key=relation.context_key AND input.input_id=relation.input_id
WHERE relation.run_id=$1::text
ORDER BY relation.relation,relation.ordinal
`

type ListAgentLocalRunInputsRow struct {
	ContextKey      string             `json:"context_key"`
	InputID         string             `json:"input_id"`
	InputSequence   int64              `json:"input_sequence"`
	Payload         []byte             `json:"payload"`
	PayloadHash     []byte             `json:"payload_hash"`
	SourceKind      string             `json:"source_kind"`
	SourceMessageID pgtype.Text        `json:"source_message_id"`
	SourceInboxID   pgtype.Text        `json:"source_inbox_id"`
	Status          string             `json:"status"`
	SelectionResult []byte             `json:"selection_result"`
	SteerGroupID    pgtype.Text        `json:"steer_group_id"`
	LocalRunID      pgtype.Text        `json:"local_run_id"`
	SteerOutcome    pgtype.Text        `json:"steer_outcome"`
	CreatedAt       pgtype.Timestamptz `json:"created_at"`
	UpdatedAt       pgtype.Timestamptz `json:"updated_at"`
	RunRelation     string             `json:"run_relation"`
	RunOrdinal      int64              `json:"run_ordinal"`
}

func (q *Queries) ListAgentLocalRunInputs(ctx context.Context, runID string) ([]ListAgentLocalRunInputsRow, error) {
	rows, err := q.db.Query(ctx, listAgentLocalRunInputs, runID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAgentLocalRunInputsRow{}
	for rows.Next() {
		var i ListAgentLocalRunInputsRow
		if err := rows.Scan(
			&i.ContextKey,
			&i.InputID,
			&i.InputSequence,
			&i.Payload,
			&i.PayloadHash,
			&i.SourceKind,
			&i.SourceMessageID,
			&i.SourceInboxID,
			&i.Status,
			&i.SelectionResult,
			&i.SteerGroupID,
			&i.LocalRunID,
			&i.SteerOutcome,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.RunRelation,
			&i.RunOrdinal,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentPerRoomMetaContextCandidates = `-- name: ListAgentPerRoomMetaContextCandidates :many
SELECT registration.tenant_id,registration.actor_id AS agent_actor_id,
       registration.agent_management_id,membership.room_id,
       membership.membership_epoch_id
FROM agent_registrations registration
JOIN active_room_members membership
  ON membership.actor_id=registration.actor_id
 AND membership.tenant_id=registration.tenant_id
WHERE registration.actor_id=$1::text
  AND registration.agent_management_id IS NOT NULL
  AND registration.status='active'
  AND NOT EXISTS (
      SELECT 1
      FROM work_item_room_links work_link
      JOIN work_items task
        ON task.id=work_link.work_item_id
       AND task.tenant_id=work_link.tenant_id
       AND task.kind='task'
      WHERE work_link.room_id=membership.room_id
        AND work_link.tenant_id=membership.tenant_id
        AND work_link.link_type='work'
  )
ORDER BY membership.room_id
`

type ListAgentPerRoomMetaContextCandidatesRow struct {
	TenantID          string      `json:"tenant_id"`
	AgentActorID      string      `json:"agent_actor_id"`
	AgentManagementID pgtype.Text `json:"agent_management_id"`
	RoomID            string      `json:"room_id"`
	MembershipEpochID string      `json:"membership_epoch_id"`
}

func (q *Queries) ListAgentPerRoomMetaContextCandidates(ctx context.Context, agentActorID string) ([]ListAgentPerRoomMetaContextCandidatesRow, error) {
	rows, err := q.db.Query(ctx, listAgentPerRoomMetaContextCandidates, agentActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAgentPerRoomMetaContextCandidatesRow{}
	for rows.Next() {
		var i ListAgentPerRoomMetaContextCandidatesRow
		if err := rows.Scan(
			&i.TenantID,
			&i.AgentActorID,
			&i.AgentManagementID,
			&i.RoomID,
			&i.MembershipEpochID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRunnerPlacementsOnComputer = `-- name: ListAgentRunnerPlacementsOnComputer :many
SELECT COALESCE(registration.agent_management_id,'')::text AS agent_management_id,
       registration.actor_id,registration.tenant_id,registration.created_by_actor_id,
       COALESCE(registration.local_runtime_type,'')::text AS local_runtime_type,
       registration.runtime_model,registration.runtime_reasoning_effort,
       COALESCE(registration.workspace_grant_id,'')::text AS workspace_grant_id,
       registration.assignment_revision
FROM agent_registrations registration
JOIN local_computers computer ON computer.computer_id=registration.computer_id
  AND computer.owner_tenant_id=registration.tenant_id
  AND computer.owner_actor_id=registration.created_by_actor_id
WHERE registration.computer_id=$1::text
  AND registration.status='active'
ORDER BY registration.agent_management_id
`

type ListAgentRunnerPlacementsOnComputerRow struct {
	AgentManagementID      string      `json:"agent_management_id"`
	ActorID                string      `json:"actor_id"`
	TenantID               string      `json:"tenant_id"`
	CreatedByActorID       string      `json:"created_by_actor_id"`
	LocalRuntimeType       string      `json:"local_runtime_type"`
	RuntimeModel           string      `json:"runtime_model"`
	RuntimeReasoningEffort pgtype.Text `json:"runtime_reasoning_effort"`
	WorkspaceGrantID       string      `json:"workspace_grant_id"`
	AssignmentRevision     int64       `json:"assignment_revision"`
}

// The Agent Runners a Computer should hold: every active Agent its owner placed on it.
func (q *Queries) ListAgentRunnerPlacementsOnComputer(ctx context.Context, computerID string) ([]ListAgentRunnerPlacementsOnComputerRow, error) {
	rows, err := q.db.Query(ctx, listAgentRunnerPlacementsOnComputer, computerID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListAgentRunnerPlacementsOnComputerRow{}
	for rows.Next() {
		var i ListAgentRunnerPlacementsOnComputerRow
		if err := rows.Scan(
			&i.AgentManagementID,
			&i.ActorID,
			&i.TenantID,
			&i.CreatedByActorID,
			&i.LocalRuntimeType,
			&i.RuntimeModel,
			&i.RuntimeReasoningEffort,
			&i.WorkspaceGrantID,
			&i.AssignmentRevision,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRuntimeLocalComputers = `-- name: ListAgentRuntimeLocalComputers :many
SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
FROM local_computers
WHERE status<>'removed'
ORDER BY display_name,computer_id
`

func (q *Queries) ListAgentRuntimeLocalComputers(ctx context.Context) ([]LocalComputer, error) {
	rows, err := q.db.Query(ctx, listAgentRuntimeLocalComputers)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []LocalComputer{}
	for rows.Next() {
		var i LocalComputer
		if err := rows.Scan(
			&i.ComputerID,
			&i.DisplayName,
			&i.Status,
			&i.CredentialGeneration,
			&i.Capacity,
			&i.ActiveOperations,
			&i.RuntimeInventory,
			&i.WorkspaceGrants,
			&i.RuntimeDiagnostics,
			&i.LastSeenAt,
			&i.RemovedAt,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DaemonID,
			&i.DaemonPublicKey,
			&i.DaemonIdentityVersion,
			&i.Platform,
			&i.DaemonVersion,
			&i.RecommendedVersion,
			&i.OwnerTenantID,
			&i.OwnerActorID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRuntimeNativeOperationIDs = `-- name: ListAgentRuntimeNativeOperationIDs :many
SELECT operation.operation_id::text AS operation_id
FROM agent_local_runs run
CROSS JOIN LATERAL jsonb_object_keys(coalesce(run.usage,'{}'::jsonb)) AS operation(operation_id)
WHERE run.run_id=$1::text
ORDER BY operation.operation_id
`

func (q *Queries) ListAgentRuntimeNativeOperationIDs(ctx context.Context, localRunID string) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentRuntimeNativeOperationIDs, localRunID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var operation_id string
		if err := rows.Scan(&operation_id); err != nil {
			return nil, err
		}
		items = append(items, operation_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRuntimeNativeTurnIDs = `-- name: ListAgentRuntimeNativeTurnIDs :many
SELECT turn.turn_id::text AS turn_id
FROM agent_local_runs run
CROSS JOIN LATERAL unnest(run.turn_ids) AS turn(turn_id)
WHERE run.run_id=$1::text
ORDER BY turn.turn_id
`

func (q *Queries) ListAgentRuntimeNativeTurnIDs(ctx context.Context, localRunID string) ([]string, error) {
	rows, err := q.db.Query(ctx, listAgentRuntimeNativeTurnIDs, localRunID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var turn_id string
		if err := rows.Scan(&turn_id); err != nil {
			return nil, err
		}
		items = append(items, turn_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listAgentRuntimeSteeringInputs = `-- name: ListAgentRuntimeSteeringInputs :many
SELECT context_key, input_id, input_sequence, payload, payload_hash, source_kind, source_message_id, source_inbox_id, status, selection_result, steer_group_id, local_run_id, steer_outcome, created_at, updated_at
FROM agent_runtime_inputs
WHERE context_key=$1::text
  AND status='steering'
ORDER BY input_sequence
FOR UPDATE
`

func (q *Queries) ListAgentRuntimeSteeringInputs(ctx context.Context, contextKey string) ([]AgentRuntimeInput, error) {
	rows, err := q.db.Query(ctx, listAgentRuntimeSteeringInputs, contextKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []AgentRuntimeInput{}
	for rows.Next() {
		var i AgentRuntimeInput
		if err := rows.Scan(
			&i.ContextKey,
			&i.InputID,
			&i.InputSequence,
			&i.Payload,
			&i.PayloadHash,
			&i.SourceKind,
			&i.SourceMessageID,
			&i.SourceInboxID,
			&i.Status,
			&i.SelectionResult,
			&i.SteerGroupID,
			&i.LocalRunID,
			&i.SteerOutcome,
			&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 listLocalModelUsersOnComputer = `-- name: ListLocalModelUsersOnComputer :many
SELECT registration.agent_management_id::text AS agent_id,
       agent.display_name,registration.runtime_model
FROM agent_registrations registration
JOIN actors agent
  ON agent.id=registration.actor_id AND agent.tenant_id=registration.tenant_id
WHERE registration.tenant_id=$1::text
  AND registration.computer_id=$2::text
  AND registration.status='active'
  AND registration.local_runtime_type='pi'
  AND (
    registration.visibility_scope='workspace' OR
    registration.created_by_actor_id=$3::text OR
    EXISTS (
      SELECT 1
      FROM active_room_members viewer_membership
      JOIN active_room_members agent_membership
        ON agent_membership.room_id=viewer_membership.room_id
       AND agent_membership.actor_id=registration.actor_id
      WHERE viewer_membership.actor_id=$3::text
    )
  )
ORDER BY agent.display_name,registration.agent_management_id
`

type ListLocalModelUsersOnComputerParams struct {
	TenantID      string `json:"tenant_id"`
	ComputerID    string `json:"computer_id"`
	ViewerActorID string `json:"viewer_actor_id"`
}

type ListLocalModelUsersOnComputerRow struct {
	AgentID      string `json:"agent_id"`
	DisplayName  string `json:"display_name"`
	RuntimeModel string `json:"runtime_model"`
}

// Active Agents on runtime pi placed on a Computer, limited to those the
// viewer sees in the Tenant Agent directory (ListTenantAgentsForAccount).
func (q *Queries) ListLocalModelUsersOnComputer(ctx context.Context, arg ListLocalModelUsersOnComputerParams) ([]ListLocalModelUsersOnComputerRow, error) {
	rows, err := q.db.Query(ctx, listLocalModelUsersOnComputer, arg.TenantID, arg.ComputerID, arg.ViewerActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListLocalModelUsersOnComputerRow{}
	for rows.Next() {
		var i ListLocalModelUsersOnComputerRow
		if err := rows.Scan(&i.AgentID, &i.DisplayName, &i.RuntimeModel); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listMaterializableAgentRuntimeRegistrationsAfter = `-- name: ListMaterializableAgentRuntimeRegistrationsAfter :many
SELECT COALESCE(registration.agent_management_id,'')::text AS agent_management_id
FROM agent_registrations registration
WHERE registration.agent_management_id IS NOT NULL
  AND registration.agent_management_id>$1::text
  AND registration.status='active'
ORDER BY registration.agent_management_id
LIMIT $2::integer
`

type ListMaterializableAgentRuntimeRegistrationsAfterParams struct {
	AfterManagementID string `json:"after_management_id"`
	RowLimit          int32  `json:"row_limit"`
}

func (q *Queries) ListMaterializableAgentRuntimeRegistrationsAfter(ctx context.Context, arg ListMaterializableAgentRuntimeRegistrationsAfterParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listMaterializableAgentRuntimeRegistrationsAfter, arg.AfterManagementID, arg.RowLimit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var agent_management_id string
		if err := rows.Scan(&agent_management_id); err != nil {
			return nil, err
		}
		items = append(items, agent_management_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listOwnedLocalComputers = `-- name: ListOwnedLocalComputers :many
SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
FROM local_computers
WHERE owner_tenant_id=$1::text
  AND owner_actor_id=$2::text
  AND status<>'removed'
ORDER BY computer_id
`

type ListOwnedLocalComputersParams struct {
	TenantID     string `json:"tenant_id"`
	OwnerActorID string `json:"owner_actor_id"`
}

func (q *Queries) ListOwnedLocalComputers(ctx context.Context, arg ListOwnedLocalComputersParams) ([]LocalComputer, error) {
	rows, err := q.db.Query(ctx, listOwnedLocalComputers, arg.TenantID, arg.OwnerActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []LocalComputer{}
	for rows.Next() {
		var i LocalComputer
		if err := rows.Scan(
			&i.ComputerID,
			&i.DisplayName,
			&i.Status,
			&i.CredentialGeneration,
			&i.Capacity,
			&i.ActiveOperations,
			&i.RuntimeInventory,
			&i.WorkspaceGrants,
			&i.RuntimeDiagnostics,
			&i.LastSeenAt,
			&i.RemovedAt,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DaemonID,
			&i.DaemonPublicKey,
			&i.DaemonIdentityVersion,
			&i.Platform,
			&i.DaemonVersion,
			&i.RecommendedVersion,
			&i.OwnerTenantID,
			&i.OwnerActorID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPublishedAgentRuntimePresentationEvents = `-- name: ListPublishedAgentRuntimePresentationEvents :many
SELECT local_run_id, event_ordinal, command_id, event_type, payload, invocation_id, outcome, message_id, created_at, activity_id, segment_id
FROM agent_runtime_status_events
WHERE local_run_id=$1::text
  AND event_ordinal>$2::bigint
  AND event_ordinal<=$3::bigint
ORDER BY event_ordinal
LIMIT $4::integer
`

type ListPublishedAgentRuntimePresentationEventsParams struct {
	LocalRunID              string `json:"local_run_id"`
	AfterOrdinal            int64  `json:"after_ordinal"`
	PublishedThroughOrdinal int64  `json:"published_through_ordinal"`
	ResultLimit             int32  `json:"result_limit"`
}

func (q *Queries) ListPublishedAgentRuntimePresentationEvents(ctx context.Context, arg ListPublishedAgentRuntimePresentationEventsParams) ([]AgentRuntimeStatusEvent, error) {
	rows, err := q.db.Query(ctx, listPublishedAgentRuntimePresentationEvents,
		arg.LocalRunID,
		arg.AfterOrdinal,
		arg.PublishedThroughOrdinal,
		arg.ResultLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []AgentRuntimeStatusEvent{}
	for rows.Next() {
		var i AgentRuntimeStatusEvent
		if err := rows.Scan(
			&i.LocalRunID,
			&i.EventOrdinal,
			&i.CommandID,
			&i.EventType,
			&i.Payload,
			&i.InvocationID,
			&i.Outcome,
			&i.MessageID,
			&i.CreatedAt,
			&i.ActivityID,
			&i.SegmentID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listPublishedRuntimeActivityIDs = `-- name: ListPublishedRuntimeActivityIDs :many
SELECT event.event_ordinal,event.activity_id::text AS activity_id
FROM agent_runtime_status_events event
WHERE event.local_run_id=$1::text
  AND event.event_ordinal>$2::bigint
  AND event.event_ordinal<=$3::bigint
  AND event.activity_id IS NOT NULL
ORDER BY event.event_ordinal
LIMIT $4::integer
`

type ListPublishedRuntimeActivityIDsParams struct {
	LocalRunID              string `json:"local_run_id"`
	AfterOrdinal            int64  `json:"after_ordinal"`
	PublishedThroughOrdinal int64  `json:"published_through_ordinal"`
	ResultLimit             int32  `json:"result_limit"`
}

type ListPublishedRuntimeActivityIDsRow struct {
	EventOrdinal int64  `json:"event_ordinal"`
	ActivityID   string `json:"activity_id"`
}

func (q *Queries) ListPublishedRuntimeActivityIDs(ctx context.Context, arg ListPublishedRuntimeActivityIDsParams) ([]ListPublishedRuntimeActivityIDsRow, error) {
	rows, err := q.db.Query(ctx, listPublishedRuntimeActivityIDs,
		arg.LocalRunID,
		arg.AfterOrdinal,
		arg.PublishedThroughOrdinal,
		arg.ResultLimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListPublishedRuntimeActivityIDsRow{}
	for rows.Next() {
		var i ListPublishedRuntimeActivityIDsRow
		if err := rows.Scan(&i.EventOrdinal, &i.ActivityID); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRecentlyUsedAgentExecutionContexts = `-- name: ListRecentlyUsedAgentExecutionContexts :many
SELECT context.context_key
FROM agent_execution_contexts context
JOIN agent_registrations registration ON registration.agent_management_id=context.agent_management_id
    AND registration.status='active'
CROSS JOIN LATERAL (
    SELECT run.created_at FROM agent_local_runs run
    WHERE run.context_key=context.context_key
    ORDER BY run.created_at DESC, run.run_id DESC
    LIMIT 1
) last
WHERE context.terminal_reason IS NULL
  AND last.created_at > clock_timestamp() - make_interval(secs => $1::integer)
  -- A Room-bound Context whose Agent has left that Room, or was readmitted, is not active.
  AND (context.room_id IS NULL OR EXISTS(SELECT 1 FROM active_room_members membership
    WHERE membership.tenant_id=context.tenant_id AND membership.actor_id=context.agent_actor_id
      AND membership.room_id=context.room_id AND membership.membership_epoch_id=context.membership_epoch_id))
ORDER BY last.created_at DESC, context.context_key
LIMIT $2::integer
`

type ListRecentlyUsedAgentExecutionContextsParams struct {
	WindowSeconds int32 `json:"window_seconds"`
	RowLimit      int32 `json:"row_limit"`
}

// Restart restore candidates. An active registration always runs on a Local
// Computer (agent_registrations_placement_check), the same predicate as
// ListPresencePreparableContextKeys, so the limit is not spent on Contexts the
// Agent Service would discard.
func (q *Queries) ListRecentlyUsedAgentExecutionContexts(ctx context.Context, arg ListRecentlyUsedAgentExecutionContextsParams) ([]string, error) {
	rows, err := q.db.Query(ctx, listRecentlyUsedAgentExecutionContexts, arg.WindowSeconds, arg.RowLimit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRetirableWorkRoomPerRoomMetaContexts = `-- name: ListRetirableWorkRoomPerRoomMetaContexts :many
SELECT context.context_key
FROM agent_execution_contexts context
WHERE context.agent_actor_id=$1::text
  AND context.context_kind='meta'
  AND context.room_id IS NOT NULL
  AND context.terminal_reason IS NULL
  AND EXISTS (
      SELECT 1
      FROM work_item_room_links work_link
      JOIN work_items task
        ON task.id=work_link.work_item_id
       AND task.tenant_id=work_link.tenant_id
       AND task.kind='task'
      WHERE work_link.room_id=context.room_id
        AND work_link.tenant_id=context.tenant_id
        AND work_link.link_type='work'
  )
ORDER BY context.context_key
`

func (q *Queries) ListRetirableWorkRoomPerRoomMetaContexts(ctx context.Context, agentActorID string) ([]string, error) {
	rows, err := q.db.Query(ctx, listRetirableWorkRoomPerRoomMetaContexts, agentActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRuntimeAgentExecutionContexts = `-- name: ListRuntimeAgentExecutionContexts :many
SELECT context.context_key, context.tenant_id, context.agent_actor_id,
    context.agent_management_id, context.context_kind, context.task_id,
    context.target_residency, context.next_input_sequence,
    context.state_revision, context.room_id,
    context.membership_epoch_id, context.terminal_reason, context.terminated_at,
    context.document_id, context.room_kind, context.task_archive_suspended
FROM agent_execution_contexts context
WHERE NOT EXISTS (
    SELECT 1
    FROM agent_registrations registration
    WHERE registration.tenant_id=context.tenant_id
      AND registration.actor_id=context.agent_actor_id
      AND registration.status='revoked'
)
ORDER BY context.context_key
`

type ListRuntimeAgentExecutionContextsRow struct {
	ContextKey           string             `json:"context_key"`
	TenantID             string             `json:"tenant_id"`
	AgentActorID         string             `json:"agent_actor_id"`
	AgentManagementID    string             `json:"agent_management_id"`
	ContextKind          string             `json:"context_kind"`
	TaskID               pgtype.Text        `json:"task_id"`
	TargetResidency      string             `json:"target_residency"`
	NextInputSequence    int64              `json:"next_input_sequence"`
	StateRevision        int64              `json:"state_revision"`
	RoomID               pgtype.Text        `json:"room_id"`
	MembershipEpochID    pgtype.Text        `json:"membership_epoch_id"`
	TerminalReason       pgtype.Text        `json:"terminal_reason"`
	TerminatedAt         pgtype.Timestamptz `json:"terminated_at"`
	DocumentID           pgtype.Text        `json:"document_id"`
	RoomKind             pgtype.Text        `json:"room_kind"`
	TaskArchiveSuspended bool               `json:"task_archive_suspended"`
}

func (q *Queries) ListRuntimeAgentExecutionContexts(ctx context.Context) ([]ListRuntimeAgentExecutionContextsRow, error) {
	rows, err := q.db.Query(ctx, listRuntimeAgentExecutionContexts)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRuntimeAgentExecutionContextsRow{}
	for rows.Next() {
		var i ListRuntimeAgentExecutionContextsRow
		if err := rows.Scan(
			&i.ContextKey,
			&i.TenantID,
			&i.AgentActorID,
			&i.AgentManagementID,
			&i.ContextKind,
			&i.TaskID,
			&i.TargetResidency,
			&i.NextInputSequence,
			&i.StateRevision,
			&i.RoomID,
			&i.MembershipEpochID,
			&i.TerminalReason,
			&i.TerminatedAt,
			&i.DocumentID,
			&i.RoomKind,
			&i.TaskArchiveSuspended,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRuntimeAgentExecutionContextsByManagementID = `-- name: ListRuntimeAgentExecutionContextsByManagementID :many
SELECT context.context_key, context.tenant_id, context.agent_actor_id,
    context.agent_management_id, context.context_kind, context.task_id,
    context.target_residency, context.next_input_sequence,
    context.state_revision, context.room_id,
    context.membership_epoch_id, context.terminal_reason, context.terminated_at,
    context.document_id, context.room_kind, context.task_archive_suspended
FROM agent_execution_contexts context
WHERE context.agent_management_id=$1::text
ORDER BY context.context_key
`

type ListRuntimeAgentExecutionContextsByManagementIDRow struct {
	ContextKey           string             `json:"context_key"`
	TenantID             string             `json:"tenant_id"`
	AgentActorID         string             `json:"agent_actor_id"`
	AgentManagementID    string             `json:"agent_management_id"`
	ContextKind          string             `json:"context_kind"`
	TaskID               pgtype.Text        `json:"task_id"`
	TargetResidency      string             `json:"target_residency"`
	NextInputSequence    int64              `json:"next_input_sequence"`
	StateRevision        int64              `json:"state_revision"`
	RoomID               pgtype.Text        `json:"room_id"`
	MembershipEpochID    pgtype.Text        `json:"membership_epoch_id"`
	TerminalReason       pgtype.Text        `json:"terminal_reason"`
	TerminatedAt         pgtype.Timestamptz `json:"terminated_at"`
	DocumentID           pgtype.Text        `json:"document_id"`
	RoomKind             pgtype.Text        `json:"room_kind"`
	TaskArchiveSuspended bool               `json:"task_archive_suspended"`
}

// A revoked Agent's Contexts stay listed: Agent Service enumerates them to
// stop and remove them after TeamHub revoked the Agent.
func (q *Queries) ListRuntimeAgentExecutionContextsByManagementID(ctx context.Context, agentManagementID string) ([]ListRuntimeAgentExecutionContextsByManagementIDRow, error) {
	rows, err := q.db.Query(ctx, listRuntimeAgentExecutionContextsByManagementID, agentManagementID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRuntimeAgentExecutionContextsByManagementIDRow{}
	for rows.Next() {
		var i ListRuntimeAgentExecutionContextsByManagementIDRow
		if err := rows.Scan(
			&i.ContextKey,
			&i.TenantID,
			&i.AgentActorID,
			&i.AgentManagementID,
			&i.ContextKind,
			&i.TaskID,
			&i.TargetResidency,
			&i.NextInputSequence,
			&i.StateRevision,
			&i.RoomID,
			&i.MembershipEpochID,
			&i.TerminalReason,
			&i.TerminatedAt,
			&i.DocumentID,
			&i.RoomKind,
			&i.TaskArchiveSuspended,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRuntimePresentationRunsForAccountByRoom = `-- name: ListRuntimePresentationRunsForAccountByRoom :many
WITH latest AS (
  SELECT run.run_id,run.status,run.created_at,run.updated_at,
         context.tenant_id,context.agent_actor_id,
         COALESCE(CASE WHEN run.status='canceled' THEN left(run.terminal->>'reason',1000) END,'')::text AS stop_reason
  FROM rooms room
  JOIN actors caller ON caller.tenant_id=room.tenant_id
   AND caller.account_id=$1::text AND caller.kind='human'
  JOIN active_room_members membership
    ON membership.room_id=collaboration_membership_room_id(room.id) AND membership.actor_id=caller.id
   AND room_actor_participating(room.id,caller.id)
  JOIN agent_local_runs run ON run.status_room_id=room.id
  JOIN agent_execution_contexts context ON context.context_key=run.context_key AND context.tenant_id=room.tenant_id
  WHERE room.id=$2::text
    AND ($3::text='' OR run.run_id=$3::text)
    AND (
      $3::text<>''
      OR run.status IN ('queued','running')
      OR EXISTS (
        SELECT 1 FROM agent_local_run_inputs relation
        JOIN agent_runtime_inputs input
          ON input.context_key=relation.context_key AND input.input_id=relation.input_id
        JOIN messages source
          ON (source.id=input.source_message_id
              OR (input.source_kind='inbox' AND (input.payload->'invocationMessageIds') ? source.id))
         AND source.room_id=room.id
         AND source.tenant_id=room.tenant_id
        WHERE relation.run_id=run.run_id
          AND source.id=ANY($4::text[])
      )
      OR EXISTS (
        SELECT 1
        FROM messages message
        WHERE message.local_run_id=run.run_id
          AND message.tenant_id=room.tenant_id
          AND message.room_id=room.id
          AND message.author_actor_id=context.agent_actor_id
          AND message.id=ANY($4::text[])
      )
    )
  ORDER BY (run.status IN ('queued','running')) DESC,run.created_at DESC,run.run_id DESC
  LIMIT 100
)
SELECT latest.run_id,latest.status,latest.created_at,latest.updated_at,latest.agent_actor_id,latest.stop_reason,
       actor.kind AS agent_kind,actor.display_name AS agent_display_name,
       coalesce((SELECT max(event.event_ordinal) FROM agent_runtime_status_events event
                 WHERE event.local_run_id=latest.run_id),0)::bigint AS event_ordinal,
       agent_local_run_replied(latest.run_id)::boolean AS replied
FROM latest
JOIN actors actor ON actor.id=latest.agent_actor_id AND actor.tenant_id=latest.tenant_id
ORDER BY latest.created_at,latest.run_id
`

type ListRuntimePresentationRunsForAccountByRoomParams struct {
	AccountID  string   `json:"account_id"`
	RoomID     string   `json:"room_id"`
	RunID      string   `json:"run_id"`
	MessageIds []string `json:"message_ids"`
}

type ListRuntimePresentationRunsForAccountByRoomRow struct {
	RunID            string             `json:"run_id"`
	Status           string             `json:"status"`
	CreatedAt        pgtype.Timestamptz `json:"created_at"`
	UpdatedAt        pgtype.Timestamptz `json:"updated_at"`
	AgentActorID     string             `json:"agent_actor_id"`
	StopReason       string             `json:"stop_reason"`
	AgentKind        string             `json:"agent_kind"`
	AgentDisplayName string             `json:"agent_display_name"`
	EventOrdinal     int64              `json:"event_ordinal"`
	Replied          bool               `json:"replied"`
}

// At most 100 Runs shown in the Room: unfinished ones first, then finished
// ones whose sources or published Messages are among the given Messages.
// With a Run ID, only that Run in any state.
func (q *Queries) ListRuntimePresentationRunsForAccountByRoom(ctx context.Context, arg ListRuntimePresentationRunsForAccountByRoomParams) ([]ListRuntimePresentationRunsForAccountByRoomRow, error) {
	rows, err := q.db.Query(ctx, listRuntimePresentationRunsForAccountByRoom,
		arg.AccountID,
		arg.RoomID,
		arg.RunID,
		arg.MessageIds,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListRuntimePresentationRunsForAccountByRoomRow{}
	for rows.Next() {
		var i ListRuntimePresentationRunsForAccountByRoomRow
		if err := rows.Scan(
			&i.RunID,
			&i.Status,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.AgentActorID,
			&i.StopReason,
			&i.AgentKind,
			&i.AgentDisplayName,
			&i.EventOrdinal,
			&i.Replied,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listTaskCoordinatorContextKeys = `-- name: ListTaskCoordinatorContextKeys :many
SELECT item.id AS task_id, item.tenant_id, generation.coordinator_context_key
FROM work_items item
JOIN task_execution_generations generation
  ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
 AND generation.generation=item.task_execution_generation
WHERE item.id = ANY($1::text[])
  AND generation.coordinator_context_key IS NOT NULL
`

type ListTaskCoordinatorContextKeysRow struct {
	TaskID                string      `json:"task_id"`
	TenantID              string      `json:"tenant_id"`
	CoordinatorContextKey pgtype.Text `json:"coordinator_context_key"`
}

// Shared Task directories key on the frozen coordinator of the current
// generation; one batched read serves a Context list.
func (q *Queries) ListTaskCoordinatorContextKeys(ctx context.Context, taskIds []string) ([]ListTaskCoordinatorContextKeysRow, error) {
	rows, err := q.db.Query(ctx, listTaskCoordinatorContextKeys, taskIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListTaskCoordinatorContextKeysRow{}
	for rows.Next() {
		var i ListTaskCoordinatorContextKeysRow
		if err := rows.Scan(&i.TaskID, &i.TenantID, &i.CoordinatorContextKey); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listUnconfirmedAgentRuntimeRunInputs = `-- name: ListUnconfirmedAgentRuntimeRunInputs :many
SELECT input_id FROM agent_runtime_inputs
WHERE local_run_id=$1::text AND steer_outcome='uncertain'
ORDER BY input_sequence
`

func (q *Queries) ListUnconfirmedAgentRuntimeRunInputs(ctx context.Context, localRunID string) ([]string, error) {
	rows, err := q.db.Query(ctx, listUnconfirmedAgentRuntimeRunInputs, localRunID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var input_id string
		if err := rows.Scan(&input_id); err != nil {
			return nil, err
		}
		items = append(items, input_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listUnfinishedAgentContextLocalRuns = `-- name: ListUnfinishedAgentContextLocalRuns :many
SELECT run_id FROM agent_local_runs
WHERE context_key=$1::text
  AND status IN ('queued','running')
ORDER BY run_id
`

func (q *Queries) ListUnfinishedAgentContextLocalRuns(ctx context.Context, contextKey string) ([]string, error) {
	rows, err := q.db.Query(ctx, listUnfinishedAgentContextLocalRuns, contextKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var run_id string
		if err := rows.Scan(&run_id); err != nil {
			return nil, err
		}
		items = append(items, run_id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVisibleRoomRunStatusesForAccount = `-- name: ListVisibleRoomRunStatusesForAccount :many
SELECT run.run_id,run.status,run.created_at,run.updated_at,
       context.agent_actor_id,actor.kind AS agent_kind,actor.display_name AS agent_display_name,
       coalesce((SELECT max(event.event_ordinal) FROM agent_runtime_status_events event
                 WHERE event.local_run_id=run.run_id),0)::bigint AS event_ordinal,
       COALESCE(CASE WHEN run.status='canceled' THEN left(run.terminal->>'reason',1000) END,'')::text AS stop_reason,
       agent_local_run_replied(run.run_id)::boolean AS replied
FROM rooms room
JOIN actors caller ON caller.tenant_id=room.tenant_id
 AND caller.account_id=$1::text AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=collaboration_membership_room_id(room.id) AND membership.actor_id=caller.id
 AND room_actor_participating(room.id,caller.id)
JOIN agent_local_runs run ON run.status_room_id=room.id
JOIN agent_execution_contexts context ON context.context_key=run.context_key AND context.tenant_id=room.tenant_id
JOIN actors actor ON actor.id=context.agent_actor_id AND actor.tenant_id=context.tenant_id
WHERE room.id=$2::text
  AND (run.status IN ('queued','running')
    OR (run.status IN ('failed','canceled')
      AND run.finished_at>clock_timestamp()-interval '24 hours'
      AND NOT EXISTS (
        SELECT 1 FROM agent_local_runs newer
        JOIN agent_execution_contexts newer_context ON newer_context.context_key=newer.context_key
        WHERE newer.status_room_id=run.status_room_id
          AND newer_context.agent_actor_id=context.agent_actor_id
          AND (newer.created_at,newer.run_id)>(run.created_at,run.run_id))))
ORDER BY run.created_at,run.run_id
`

type ListVisibleRoomRunStatusesForAccountParams struct {
	AccountID string `json:"account_id"`
	RoomID    string `json:"room_id"`
}

type ListVisibleRoomRunStatusesForAccountRow struct {
	RunID            string             `json:"run_id"`
	Status           string             `json:"status"`
	CreatedAt        pgtype.Timestamptz `json:"created_at"`
	UpdatedAt        pgtype.Timestamptz `json:"updated_at"`
	AgentActorID     string             `json:"agent_actor_id"`
	AgentKind        string             `json:"agent_kind"`
	AgentDisplayName string             `json:"agent_display_name"`
	EventOrdinal     int64              `json:"event_ordinal"`
	StopReason       string             `json:"stop_reason"`
	Replied          bool               `json:"replied"`
}

// Unfinished Runs shown in the Room, and failed or canceled ones for a day
// until the same Agent has a newer Run there. Succeeded Runs leave.
func (q *Queries) ListVisibleRoomRunStatusesForAccount(ctx context.Context, arg ListVisibleRoomRunStatusesForAccountParams) ([]ListVisibleRoomRunStatusesForAccountRow, error) {
	rows, err := q.db.Query(ctx, listVisibleRoomRunStatusesForAccount, arg.AccountID, arg.RoomID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVisibleRoomRunStatusesForAccountRow{}
	for rows.Next() {
		var i ListVisibleRoomRunStatusesForAccountRow
		if err := rows.Scan(
			&i.RunID,
			&i.Status,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.AgentActorID,
			&i.AgentKind,
			&i.AgentDisplayName,
			&i.EventOrdinal,
			&i.StopReason,
			&i.Replied,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockAgentContextsForEpochStart = `-- name: LockAgentContextsForEpochStart :many
SELECT context.context_key
FROM agent_execution_contexts context
WHERE EXISTS (
    SELECT 1 FROM agent_local_runs run
    WHERE run.context_key=context.context_key AND run.status='running'
      AND run.epoch IS DISTINCT FROM $1::text
) OR EXISTS (
    SELECT 1 FROM agent_runtime_inputs input
    WHERE input.context_key=context.context_key AND input.status='steering'
)
ORDER BY context.context_key
FOR NO KEY UPDATE
`

// Contexts holding a Run of an earlier epoch or an unsettled steer, in
// context_key order, before their Runs.
func (q *Queries) LockAgentContextsForEpochStart(ctx context.Context, epoch string) ([]string, error) {
	rows, err := q.db.Query(ctx, lockAgentContextsForEpochStart, epoch)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockAgentExecutionContext = `-- name: LockAgentExecutionContext :one
SELECT context_key, tenant_id, agent_actor_id, agent_management_id, context_kind,
    task_id, target_residency, next_input_sequence,
    state_revision, room_id, membership_epoch_id, terminal_reason, terminated_at,
    document_id, room_kind, task_archive_suspended
FROM agent_execution_contexts
WHERE context_key=$1::text
FOR NO KEY UPDATE
`

type LockAgentExecutionContextRow struct {
	ContextKey           string             `json:"context_key"`
	TenantID             string             `json:"tenant_id"`
	AgentActorID         string             `json:"agent_actor_id"`
	AgentManagementID    string             `json:"agent_management_id"`
	ContextKind          string             `json:"context_kind"`
	TaskID               pgtype.Text        `json:"task_id"`
	TargetResidency      string             `json:"target_residency"`
	NextInputSequence    int64              `json:"next_input_sequence"`
	StateRevision        int64              `json:"state_revision"`
	RoomID               pgtype.Text        `json:"room_id"`
	MembershipEpochID    pgtype.Text        `json:"membership_epoch_id"`
	TerminalReason       pgtype.Text        `json:"terminal_reason"`
	TerminatedAt         pgtype.Timestamptz `json:"terminated_at"`
	DocumentID           pgtype.Text        `json:"document_id"`
	RoomKind             pgtype.Text        `json:"room_kind"`
	TaskArchiveSuspended bool               `json:"task_archive_suspended"`
}

// Context identity never changes. NO KEY UPDATE serializes state commands
// without blocking foreign-key KEY SHARE checks during Task Inbox binding.
func (q *Queries) LockAgentExecutionContext(ctx context.Context, contextKey string) (LockAgentExecutionContextRow, error) {
	row := q.db.QueryRow(ctx, lockAgentExecutionContext, contextKey)
	var i LockAgentExecutionContextRow
	err := row.Scan(
		&i.ContextKey,
		&i.TenantID,
		&i.AgentActorID,
		&i.AgentManagementID,
		&i.ContextKind,
		&i.TaskID,
		&i.TargetResidency,
		&i.NextInputSequence,
		&i.StateRevision,
		&i.RoomID,
		&i.MembershipEpochID,
		&i.TerminalReason,
		&i.TerminatedAt,
		&i.DocumentID,
		&i.RoomKind,
		&i.TaskArchiveSuspended,
	)
	return i, err
}

const lockAgentLocalRunConfiguration = `-- name: LockAgentLocalRunConfiguration :one
SELECT registration.status
FROM agent_registrations registration
JOIN agent_execution_contexts context
  ON context.agent_actor_id=registration.actor_id AND context.tenant_id=registration.tenant_id
WHERE context.context_key=$1
FOR SHARE OF registration
`

func (q *Queries) LockAgentLocalRunConfiguration(ctx context.Context, contextKey string) (string, error) {
	row := q.db.QueryRow(ctx, lockAgentLocalRunConfiguration, contextKey)
	var status string
	err := row.Scan(&status)
	return status, err
}

const lockAgentRunStatusRoom = `-- name: LockAgentRunStatusRoom :one
SELECT (deletion_started_at IS NULL AND deleted_at IS NULL)::boolean AS publishable
FROM rooms
WHERE id=$1::text
FOR NO KEY UPDATE
`

// Every writer of a Run's events holds its status Room row, so event ordinals
// and the Room Events announcing them are allocated in one order.
func (q *Queries) LockAgentRunStatusRoom(ctx context.Context, roomID string) (bool, error) {
	row := q.db.QueryRow(ctx, lockAgentRunStatusRoom, roomID)
	var publishable bool
	err := row.Scan(&publishable)
	return publishable, err
}

const lockAgentRuntimeLocalComputer = `-- name: LockAgentRuntimeLocalComputer :one
SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
FROM local_computers
WHERE computer_id=$1::text
FOR UPDATE
`

func (q *Queries) LockAgentRuntimeLocalComputer(ctx context.Context, computerID string) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, lockAgentRuntimeLocalComputer, computerID)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const lockAgentRuntimeLocalComputerByDaemonID = `-- name: LockAgentRuntimeLocalComputerByDaemonID :one
SELECT computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
FROM local_computers
WHERE daemon_id=$1::text
  AND status<>'removed'
FOR UPDATE
`

func (q *Queries) LockAgentRuntimeLocalComputerByDaemonID(ctx context.Context, daemonID string) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, lockAgentRuntimeLocalComputerByDaemonID, daemonID)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const lockAgentRuntimeLocalComputerEnrollment = `-- name: LockAgentRuntimeLocalComputerEnrollment :one
SELECT enrollment_id, tenant_id, owner_actor_id, requested_computer_id, renews_existing_computer, display_name, redirect_uri, code_challenge, authorization_code_hash, expires_at, exchanged_at, exchanged_generation, created_at
FROM local_computer_enrollments
WHERE enrollment_id=$1::text
FOR UPDATE
`

func (q *Queries) LockAgentRuntimeLocalComputerEnrollment(ctx context.Context, enrollmentID string) (LocalComputerEnrollment, error) {
	row := q.db.QueryRow(ctx, lockAgentRuntimeLocalComputerEnrollment, enrollmentID)
	var i LocalComputerEnrollment
	err := row.Scan(
		&i.EnrollmentID,
		&i.TenantID,
		&i.OwnerActorID,
		&i.RequestedComputerID,
		&i.RenewsExistingComputer,
		&i.DisplayName,
		&i.RedirectUri,
		&i.CodeChallenge,
		&i.AuthorizationCodeHash,
		&i.ExpiresAt,
		&i.ExchangedAt,
		&i.ExchangedGeneration,
		&i.CreatedAt,
	)
	return i, err
}

const lockAgentRuntimeSteerInputs = `-- name: LockAgentRuntimeSteerInputs :many
SELECT context_key, input_id, input_sequence, payload, payload_hash, source_kind, source_message_id, source_inbox_id, status, selection_result, steer_group_id, local_run_id, steer_outcome, created_at, updated_at
FROM agent_runtime_inputs
WHERE context_key=$1::text
  AND steer_group_id=$2::text
  AND status='steering'
ORDER BY input_sequence
FOR UPDATE
`

type LockAgentRuntimeSteerInputsParams struct {
	ContextKey   string `json:"context_key"`
	SteerGroupID string `json:"steer_group_id"`
}

func (q *Queries) LockAgentRuntimeSteerInputs(ctx context.Context, arg LockAgentRuntimeSteerInputsParams) ([]AgentRuntimeInput, error) {
	rows, err := q.db.Query(ctx, lockAgentRuntimeSteerInputs, arg.ContextKey, arg.SteerGroupID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []AgentRuntimeInput{}
	for rows.Next() {
		var i AgentRuntimeInput
		if err := rows.Scan(
			&i.ContextKey,
			&i.InputID,
			&i.InputSequence,
			&i.Payload,
			&i.PayloadHash,
			&i.SourceKind,
			&i.SourceMessageID,
			&i.SourceInboxID,
			&i.Status,
			&i.SelectionResult,
			&i.SteerGroupID,
			&i.LocalRunID,
			&i.SteerOutcome,
			&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 lockAgentServiceEpoch = `-- name: LockAgentServiceEpoch :one
SELECT epoch FROM agent_service_epochs
WHERE epoch=$1::text
FOR KEY SHARE
`

// Every Runtime write holds the current epoch for its transaction, so a new
// process start waits for it and then interrupts what it claimed.
func (q *Queries) LockAgentServiceEpoch(ctx context.Context, epoch string) (string, error) {
	row := q.db.QueryRow(ctx, lockAgentServiceEpoch, epoch)
	err := row.Scan(&epoch)
	return epoch, err
}

const lockMetaContextsForRoomMemberships = `-- name: LockMetaContextsForRoomMemberships :exec
SELECT context.context_key FROM agent_execution_contexts context
WHERE context.context_kind='meta'
  AND context.agent_actor_id=ANY($1::text[])
  AND context.room_id=ANY($2::text[])
ORDER BY context.context_key FOR NO KEY UPDATE
`

type LockMetaContextsForRoomMembershipsParams struct {
	AgentActorIds []string `json:"agent_actor_ids"`
	RoomIds       []string `json:"room_ids"`
}

// Meta Contexts are locked in context_key order before any membership write
// or Room lock.
func (q *Queries) LockMetaContextsForRoomMemberships(ctx context.Context, arg LockMetaContextsForRoomMembershipsParams) error {
	_, err := q.db.Exec(ctx, lockMetaContextsForRoomMemberships, arg.AgentActorIds, arg.RoomIds)
	return err
}

const lockNextQueuedAgentLocalRun = `-- name: LockNextQueuedAgentLocalRun :one
SELECT run.run_id, run.context_key, run.status, run.terminal, run.created_at, run.updated_at, run.started_at, run.finished_at, run.attempt_count, run.cancellation_requested, run.epoch, run.claim_id, run.claim_configuration_revision, run.usage, run.status_room_id, run.claim_profile_revision, run.turn_ids
FROM agent_local_runs run
WHERE run.context_key=$1::text AND run.status='queued'
  AND agent_document_run_claimable(run.run_id,run.context_key)
ORDER BY created_at,run_id
LIMIT 1
FOR UPDATE
`

func (q *Queries) LockNextQueuedAgentLocalRun(ctx context.Context, contextKey string) (AgentLocalRun, error) {
	row := q.db.QueryRow(ctx, lockNextQueuedAgentLocalRun, contextKey)
	var i AgentLocalRun
	err := row.Scan(
		&i.RunID,
		&i.ContextKey,
		&i.Status,
		&i.Terminal,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StartedAt,
		&i.FinishedAt,
		&i.AttemptCount,
		&i.CancellationRequested,
		&i.Epoch,
		&i.ClaimID,
		&i.ClaimConfigurationRevision,
		&i.Usage,
		&i.StatusRoomID,
		&i.ClaimProfileRevision,
		&i.TurnIds,
	)
	return i, err
}

const lockOpenAgentExecutionContextsForAgentRevocation = `-- name: LockOpenAgentExecutionContextsForAgentRevocation :many
SELECT context.context_key
FROM agent_execution_contexts context
WHERE context.tenant_id=$1::text
  AND context.agent_actor_id=$2::text
  AND (
    context.terminal_reason IS NULL
    OR (context.context_kind='meta'
        AND context.room_id=ANY($3::text[]))
  )
ORDER BY context.context_key
FOR UPDATE
`

type LockOpenAgentExecutionContextsForAgentRevocationParams struct {
	TenantID     string   `json:"tenant_id"`
	AgentActorID string   `json:"agent_actor_id"`
	RoomIds      []string `json:"room_ids"`
}

// One ordered pass over every Context the deletion touches: open Contexts it
// terminates, plus the meta Contexts membership revocation suspends in its
// Rooms (LockMetaContextsForRoomMemberships), terminal or not.
func (q *Queries) LockOpenAgentExecutionContextsForAgentRevocation(ctx context.Context, arg LockOpenAgentExecutionContextsForAgentRevocationParams) ([]string, error) {
	rows, err := q.db.Query(ctx, lockOpenAgentExecutionContextsForAgentRevocation, arg.TenantID, arg.AgentActorID, arg.RoomIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const markAgentRuntimeLocalComputersOffline = `-- name: MarkAgentRuntimeLocalComputersOffline :many
UPDATE local_computers
SET status='offline',active_operations=0,updated_at=clock_timestamp()
WHERE status IN ('online','upgrade_required')
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

func (q *Queries) MarkAgentRuntimeLocalComputersOffline(ctx context.Context) ([]LocalComputer, error) {
	rows, err := q.db.Query(ctx, markAgentRuntimeLocalComputersOffline)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []LocalComputer{}
	for rows.Next() {
		var i LocalComputer
		if err := rows.Scan(
			&i.ComputerID,
			&i.DisplayName,
			&i.Status,
			&i.CredentialGeneration,
			&i.Capacity,
			&i.ActiveOperations,
			&i.RuntimeInventory,
			&i.WorkspaceGrants,
			&i.RuntimeDiagnostics,
			&i.LastSeenAt,
			&i.RemovedAt,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DaemonID,
			&i.DaemonPublicKey,
			&i.DaemonIdentityVersion,
			&i.Platform,
			&i.DaemonVersion,
			&i.RecommendedVersion,
			&i.OwnerTenantID,
			&i.OwnerActorID,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const nextAgentLocalRunSteerOrdinal = `-- name: NextAgentLocalRunSteerOrdinal :one
SELECT COALESCE(max(ordinal)+1,0)::bigint
FROM agent_local_run_inputs
WHERE run_id=$1::text AND relation='steer'
`

func (q *Queries) NextAgentLocalRunSteerOrdinal(ctx context.Context, runID string) (int64, error) {
	row := q.db.QueryRow(ctx, nextAgentLocalRunSteerOrdinal, runID)
	var column_1 int64
	err := row.Scan(&column_1)
	return column_1, err
}

const nextAgentRunInputOrigins = `-- name: NextAgentRunInputOrigins :many
WITH next_run AS (
    SELECT run.run_id FROM agent_local_runs run
    WHERE run.context_key=$1::text AND run.status='queued'
      AND agent_document_run_claimable(run.run_id,run.context_key)
    ORDER BY run.created_at, run.run_id LIMIT 1
)
SELECT DISTINCT (input.payload ? 'acceptedNotification')::boolean AS notification,
       coalesce(input.payload->'acceptedNotification'->>'inboxId' LIKE 'taskmeta:%', false)::boolean AS task_inbox,
       coalesce(msg.value->>'authorType', '')::text AS author_type,
       coalesce(msg.value->>'messageKind', '')::text AS message_kind,
       coalesce(msg.value->>'firedRoutine' = 'true', false)::boolean AS fired_routine
FROM next_run
JOIN agent_local_run_inputs relation ON relation.run_id=next_run.run_id AND relation.relation='initial'
JOIN agent_runtime_inputs input ON input.context_key=relation.context_key AND input.input_id=relation.input_id
LEFT JOIN LATERAL jsonb_array_elements(input.payload->'acceptedNotification'->'messages') AS msg(value) ON true
`

type NextAgentRunInputOriginsRow struct {
	Notification bool   `json:"notification"`
	TaskInbox    bool   `json:"task_inbox"`
	AuthorType   string `json:"author_type"`
	MessageKind  string `json:"message_kind"`
	FiredRoutine bool   `json:"fired_routine"`
}

// Match claim order without locking the Run or returning message bodies.
func (q *Queries) NextAgentRunInputOrigins(ctx context.Context, contextKey string) ([]NextAgentRunInputOriginsRow, error) {
	rows, err := q.db.Query(ctx, nextAgentRunInputOrigins, contextKey)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []NextAgentRunInputOriginsRow{}
	for rows.Next() {
		var i NextAgentRunInputOriginsRow
		if err := rows.Scan(
			&i.Notification,
			&i.TaskInbox,
			&i.AuthorType,
			&i.MessageKind,
			&i.FiredRoutine,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const observeAgentRuntimeLocalComputer = `-- name: ObserveAgentRuntimeLocalComputer :one
UPDATE local_computers
SET display_name=$1::text,
    status=$2::text,
    capacity=$3::integer,
    platform=COALESCE($4::text,platform),
    runtime_inventory=$5::jsonb,
    runtime_diagnostics=$6::jsonb,
    workspace_grants=$7::jsonb,
    daemon_version=COALESCE($8::text,daemon_version),
    recommended_version=COALESCE($9::text,recommended_version),
    last_seen_at=$10::timestamptz,
    updated_at=clock_timestamp()
WHERE computer_id=$11::text AND status<>'removed'
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

type ObserveAgentRuntimeLocalComputerParams struct {
	DisplayName        string             `json:"display_name"`
	Status             string             `json:"status"`
	Capacity           pgtype.Int4        `json:"capacity"`
	Platform           pgtype.Text        `json:"platform"`
	RuntimeInventory   []byte             `json:"runtime_inventory"`
	RuntimeDiagnostics []byte             `json:"runtime_diagnostics"`
	WorkspaceGrants    []byte             `json:"workspace_grants"`
	DaemonVersion      pgtype.Text        `json:"daemon_version"`
	RecommendedVersion pgtype.Text        `json:"recommended_version"`
	LastSeenAt         pgtype.Timestamptz `json:"last_seen_at"`
	ComputerID         string             `json:"computer_id"`
}

func (q *Queries) ObserveAgentRuntimeLocalComputer(ctx context.Context, arg ObserveAgentRuntimeLocalComputerParams) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, observeAgentRuntimeLocalComputer,
		arg.DisplayName,
		arg.Status,
		arg.Capacity,
		arg.Platform,
		arg.RuntimeInventory,
		arg.RuntimeDiagnostics,
		arg.WorkspaceGrants,
		arg.DaemonVersion,
		arg.RecommendedVersion,
		arg.LastSeenAt,
		arg.ComputerID,
	)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const purgeAgentRuntimeLocalComputerEnrollmentsByComputer = `-- name: PurgeAgentRuntimeLocalComputerEnrollmentsByComputer :exec
DELETE FROM local_computer_enrollments
WHERE requested_computer_id=$1::text
`

func (q *Queries) PurgeAgentRuntimeLocalComputerEnrollmentsByComputer(ctx context.Context, computerID string) error {
	_, err := q.db.Exec(ctx, purgeAgentRuntimeLocalComputerEnrollmentsByComputer, computerID)
	return err
}

const recordAgentDocumentCommentContextInput = `-- name: RecordAgentDocumentCommentContextInput :exec
UPDATE agent_execution_contexts
SET next_input_sequence=greatest(next_input_sequence,$1::bigint),
    state_revision=state_revision+1,updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND context_kind='document'
`

type RecordAgentDocumentCommentContextInputParams struct {
	InputSequence int64  `json:"input_sequence"`
	ContextKey    string `json:"context_key"`
}

// Document Comment enqueue must not wake the Agent until the comment
// generation is active. Room/Meta use ActivateAgentExecutionContextForInput.
func (q *Queries) RecordAgentDocumentCommentContextInput(ctx context.Context, arg RecordAgentDocumentCommentContextInputParams) error {
	_, err := q.db.Exec(ctx, recordAgentDocumentCommentContextInput, arg.InputSequence, arg.ContextKey)
	return err
}

const recordAgentExecutionContextClaimedRun = `-- name: RecordAgentExecutionContextClaimedRun :exec
UPDATE agent_execution_contexts
SET next_input_sequence=greatest(next_input_sequence,coalesce((
        SELECT max(input.input_sequence) FROM agent_local_run_inputs relation
        JOIN agent_runtime_inputs input ON input.context_key=relation.context_key AND input.input_id=relation.input_id
        WHERE relation.run_id=$1::text),0)),
    state_revision=state_revision+1,updated_at=clock_timestamp()
WHERE context_key=$2::text
`

type RecordAgentExecutionContextClaimedRunParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
}

// A claim advances the Context revision and records the latest input the
// Context has taken up.
func (q *Queries) RecordAgentExecutionContextClaimedRun(ctx context.Context, arg RecordAgentExecutionContextClaimedRunParams) error {
	_, err := q.db.Exec(ctx, recordAgentExecutionContextClaimedRun, arg.RunID, arg.ContextKey)
	return err
}

const recordAgentLocalRunClaimProfileRevision = `-- name: RecordAgentLocalRunClaimProfileRevision :exec
UPDATE agent_local_runs SET claim_profile_revision=$1::bigint
WHERE run_id=$2::text
`

type RecordAgentLocalRunClaimProfileRevisionParams struct {
	ProfileRevision int64  `json:"profile_revision"`
	RunID           string `json:"run_id"`
}

func (q *Queries) RecordAgentLocalRunClaimProfileRevision(ctx context.Context, arg RecordAgentLocalRunClaimProfileRevisionParams) error {
	_, err := q.db.Exec(ctx, recordAgentLocalRunClaimProfileRevision, arg.ProfileRevision, arg.RunID)
	return err
}

const redeliverAgentRuntimeInput = `-- name: RedeliverAgentRuntimeInput :one
SELECT coalesce(redeliver_agent_runtime_input($1::text,$2::text),'')::text AS input_id
`

type RedeliverAgentRuntimeInputParams struct {
	ContextKey string `json:"context_key"`
	InputID    string `json:"input_id"`
}

// An empty input ID means the input was not placed again.
func (q *Queries) RedeliverAgentRuntimeInput(ctx context.Context, arg RedeliverAgentRuntimeInputParams) (string, error) {
	row := q.db.QueryRow(ctx, redeliverAgentRuntimeInput, arg.ContextKey, arg.InputID)
	var input_id string
	err := row.Scan(&input_id)
	return input_id, err
}

const removeAgentRuntimeLocalComputer = `-- name: RemoveAgentRuntimeLocalComputer :one
UPDATE local_computers
SET status='removed',removed_at=clock_timestamp(),updated_at=clock_timestamp(),
    daemon_id=NULL,daemon_public_key=NULL
WHERE computer_id=$1::text AND status<>'removed'
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

// A Daemon keeps its identity key across pairings, so the removed Computer
// frees its Daemon Identity for the next Computer that machine pairs as.
func (q *Queries) RemoveAgentRuntimeLocalComputer(ctx context.Context, computerID string) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, removeAgentRuntimeLocalComputer, computerID)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const replaceAgentServiceEpoch = `-- name: ReplaceAgentServiceEpoch :exec
DELETE FROM agent_service_epochs
`

// Waits for every Runtime write of the previous epoch to commit.
func (q *Queries) ReplaceAgentServiceEpoch(ctx context.Context) error {
	_, err := q.db.Exec(ctx, replaceAgentServiceEpoch)
	return err
}

const requestAgentLocalRunCancellation = `-- name: RequestAgentLocalRunCancellation :exec
UPDATE agent_local_runs SET cancellation_requested=true,updated_at=clock_timestamp()
WHERE context_key=$1::text AND run_id=$2::text AND status='running'
`

type RequestAgentLocalRunCancellationParams struct {
	ContextKey string `json:"context_key"`
	RunID      string `json:"run_id"`
}

func (q *Queries) RequestAgentLocalRunCancellation(ctx context.Context, arg RequestAgentLocalRunCancellationParams) error {
	_, err := q.db.Exec(ctx, requestAgentLocalRunCancellation, arg.ContextKey, arg.RunID)
	return err
}

const requeueAgentLocalRun = `-- name: RequeueAgentLocalRun :execrows
UPDATE agent_local_runs
SET status='queued',epoch=NULL,claim_id=NULL,claim_configuration_revision=NULL,
    started_at=NULL,updated_at=clock_timestamp()
WHERE run_id=$1::text
  AND context_key=$2::text
  AND status='running'
  AND epoch=$3::text
`

type RequeueAgentLocalRunParams struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
	Epoch      string `json:"epoch"`
}

func (q *Queries) RequeueAgentLocalRun(ctx context.Context, arg RequeueAgentLocalRunParams) (int64, error) {
	result, err := q.db.Exec(ctx, requeueAgentLocalRun, arg.RunID, arg.ContextKey, arg.Epoch)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const restoreAlterEgoContextsAfterTaskArchive = `-- name: RestoreAlterEgoContextsAfterTaskArchive :many
UPDATE agent_execution_contexts context
SET target_residency='active', task_archive_suspended=false,
    state_revision=state_revision+1, updated_at=clock_timestamp()
WHERE context.task_id=$1::text AND context.context_kind='alter_ego'
  AND context.task_archive_suspended AND context.target_residency='suspended'
  AND context.terminal_reason IS NULL
  AND EXISTS (
    SELECT 1 FROM work_items item
    JOIN task_execution_generations generation ON generation.task_id=item.id
      AND generation.tenant_id=item.tenant_id AND generation.generation=item.task_execution_generation
      AND generation.terminal_at IS NULL
    JOIN task_execution_participants participant ON participant.task_id=item.id
      AND participant.tenant_id=item.tenant_id AND participant.generation=item.task_execution_generation
      AND participant.actor_id=context.agent_actor_id AND participant.agent_management_id=context.agent_management_id
    JOIN agent_registrations registration ON registration.actor_id=context.agent_actor_id
      AND registration.tenant_id=context.tenant_id AND registration.agent_management_id=context.agent_management_id
      AND registration.status='active'
    LEFT JOIN work_item_room_links link ON link.work_item_id=item.id AND link.tenant_id=item.tenant_id AND link.link_type='work'
    LEFT JOIN rooms room ON room.id=link.room_id AND room.tenant_id=link.tenant_id
      AND room.deleted_at IS NULL AND room.deletion_started_at IS NULL
    WHERE item.id=context.task_id AND item.tenant_id=context.tenant_id AND item.archived_at IS NULL
      AND item.state<>'resolved'
      AND (link.room_id IS NULL OR room.id IS NOT NULL)
  )
RETURNING context.context_key
`

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

const rotateAgentRuntimeLocalComputerCredential = `-- name: RotateAgentRuntimeLocalComputerCredential :one
UPDATE local_computers
SET display_name=$1::text,
    credential_generation=credential_generation+1,
    status='offline',updated_at=clock_timestamp()
WHERE computer_id=$2::text
  AND status<>'removed'
  AND credential_generation<9007199254740991
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

type RotateAgentRuntimeLocalComputerCredentialParams struct {
	DisplayName string `json:"display_name"`
	ComputerID  string `json:"computer_id"`
}

func (q *Queries) RotateAgentRuntimeLocalComputerCredential(ctx context.Context, arg RotateAgentRuntimeLocalComputerCredentialParams) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, rotateAgentRuntimeLocalComputerCredential, arg.DisplayName, arg.ComputerID)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const setAgentExecutionContextResidency = `-- name: SetAgentExecutionContextResidency :execrows
UPDATE agent_execution_contexts
SET target_residency=$1::text,
    task_archive_suspended=false,
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND state_revision=$3::bigint
  AND (
      $1::text<>'active'
      OR terminal_reason IS NULL
  )
  AND (
      $1::text<>'active'
      OR context_kind<>'alter_ego'
      OR EXISTS (
          SELECT 1
          FROM work_items item
          JOIN task_execution_generations generation
            ON generation.task_id=item.id
           AND generation.tenant_id=item.tenant_id
           AND generation.generation=item.task_execution_generation
           AND generation.terminal_at IS NULL
          JOIN task_execution_participants participant
            ON participant.task_id=item.id
           AND participant.tenant_id=item.tenant_id
           AND participant.generation=item.task_execution_generation
           AND participant.actor_id=agent_execution_contexts.agent_actor_id
           AND participant.agent_management_id=agent_execution_contexts.agent_management_id
          JOIN work_item_room_links work_room
            ON work_room.work_item_id=item.id
           AND work_room.tenant_id=item.tenant_id
           AND work_room.link_type='work'
          JOIN rooms room
            ON room.id=work_room.room_id
           AND room.tenant_id=work_room.tenant_id
           AND room.deleted_at IS NULL
          WHERE item.id=agent_execution_contexts.task_id
            AND item.tenant_id=agent_execution_contexts.tenant_id
            AND item.kind='task'
            AND item.archived_at IS NULL
            AND item.state<>'resolved'
            AND item.task_execution_generation IS NOT NULL
      )
  )
  AND (
      $1::text<>'active'
      OR context_kind<>'document'
      OR document_comment_agent_readable(
          agent_execution_contexts.tenant_id,
          agent_execution_contexts.document_id,
          agent_execution_contexts.agent_actor_id
      )
  )
`

type SetAgentExecutionContextResidencyParams struct {
	TargetResidency  string `json:"target_residency"`
	ContextKey       string `json:"context_key"`
	ExpectedRevision int64  `json:"expected_revision"`
}

func (q *Queries) SetAgentExecutionContextResidency(ctx context.Context, arg SetAgentExecutionContextResidencyParams) (int64, error) {
	result, err := q.db.Exec(ctx, setAgentExecutionContextResidency, arg.TargetResidency, arg.ContextKey, arg.ExpectedRevision)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const setAgentRunStatusRoom = `-- name: SetAgentRunStatusRoom :execrows
UPDATE agent_local_runs
SET status_room_id=$1::text
WHERE run_id=$2::text AND status_room_id IS NULL
`

type SetAgentRunStatusRoomParams struct {
	RoomID string `json:"room_id"`
	RunID  string `json:"run_id"`
}

func (q *Queries) SetAgentRunStatusRoom(ctx context.Context, arg SetAgentRunStatusRoomParams) (int64, error) {
	result, err := q.db.Exec(ctx, setAgentRunStatusRoom, arg.RoomID, arg.RunID)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const settleAgentContextInputsForContextDeletion = `-- name: SettleAgentContextInputsForContextDeletion :execrows
UPDATE agent_runtime_inputs
SET status='handled',
    selection_result=jsonb_build_object(
        'selected','discard','reason','context_deleted'
    ),
    steer_outcome='uncertain',
    updated_at=clock_timestamp()
WHERE context_key=$1::text
  AND status='steering'
`

func (q *Queries) SettleAgentContextInputsForContextDeletion(ctx context.Context, contextKey string) (int64, error) {
	result, err := q.db.Exec(ctx, settleAgentContextInputsForContextDeletion, contextKey)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const settleAgentContextInputsForTaskArchive = `-- name: SettleAgentContextInputsForTaskArchive :execrows
UPDATE agent_runtime_inputs
SET status='handled',selection_result=jsonb_build_object('selected','discard','reason','task_archived'),
    steer_outcome='uncertain',
    updated_at=clock_timestamp()
WHERE context_key=$1::text AND status='steering'
`

func (q *Queries) SettleAgentContextInputsForTaskArchive(ctx context.Context, contextKey string) (int64, error) {
	result, err := q.db.Exec(ctx, settleAgentContextInputsForTaskArchive, contextKey)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const settleAgentContextInputsForTaskTerminal = `-- name: SettleAgentContextInputsForTaskTerminal :execrows
UPDATE agent_runtime_inputs
SET status='handled',
    selection_result=jsonb_build_object(
        'selected','discard','reason','task_terminal'
    ),
    steer_outcome='uncertain',
    updated_at=clock_timestamp()
WHERE context_key=$1::text
  AND status='steering'
`

func (q *Queries) SettleAgentContextInputsForTaskTerminal(ctx context.Context, contextKey string) (int64, error) {
	result, err := q.db.Exec(ctx, settleAgentContextInputsForTaskTerminal, contextKey)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const settleUncertainAgentRuntimeSteerInput = `-- name: SettleUncertainAgentRuntimeSteerInput :execrows
UPDATE agent_runtime_inputs
SET status='handled',selection_result=$1::jsonb,
    steer_outcome='uncertain',updated_at=clock_timestamp()
WHERE context_key=$2::text
  AND input_id=$3::text
  AND status='steering'
  AND steer_group_id=$4::text
`

type SettleUncertainAgentRuntimeSteerInputParams struct {
	SelectionResult []byte `json:"selection_result"`
	ContextKey      string `json:"context_key"`
	InputID         string `json:"input_id"`
	SteerGroupID    string `json:"steer_group_id"`
}

func (q *Queries) SettleUncertainAgentRuntimeSteerInput(ctx context.Context, arg SettleUncertainAgentRuntimeSteerInputParams) (int64, error) {
	result, err := q.db.Exec(ctx, settleUncertainAgentRuntimeSteerInput,
		arg.SelectionResult,
		arg.ContextKey,
		arg.InputID,
		arg.SteerGroupID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const suspendAlterEgoContextsForTaskArchive = `-- name: SuspendAlterEgoContextsForTaskArchive :many
UPDATE agent_execution_contexts
SET task_archive_suspended=(target_residency='active' OR task_archive_suspended),
    target_residency='suspended',
    state_revision=state_revision+1, updated_at=clock_timestamp()
WHERE context_kind='alter_ego' AND task_id=$1::text
  AND terminal_reason IS NULL
RETURNING context_key
`

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

const suspendAlterEgoContextsForTaskTerminal = `-- name: SuspendAlterEgoContextsForTaskTerminal :many
UPDATE agent_execution_contexts
SET target_residency='suspended',
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE context_kind='alter_ego'
  AND task_id=$1::text
  AND target_residency='active'
RETURNING context_key
`

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

const suspendPerRoomMetaContextForMembershipRevocation = `-- name: SuspendPerRoomMetaContextForMembershipRevocation :one
UPDATE agent_execution_contexts
SET target_residency='suspended',
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE agent_actor_id=$1::text
  AND context_kind='meta'
  AND room_id=$2::text
  AND membership_epoch_id=$3::text
RETURNING context_key
`

type SuspendPerRoomMetaContextForMembershipRevocationParams struct {
	AgentActorID      string `json:"agent_actor_id"`
	RoomID            string `json:"room_id"`
	MembershipEpochID string `json:"membership_epoch_id"`
}

func (q *Queries) SuspendPerRoomMetaContextForMembershipRevocation(ctx context.Context, arg SuspendPerRoomMetaContextForMembershipRevocationParams) (string, error) {
	row := q.db.QueryRow(ctx, suspendPerRoomMetaContextForMembershipRevocation, arg.AgentActorID, arg.RoomID, arg.MembershipEpochID)
	var context_key string
	err := row.Scan(&context_key)
	return context_key, err
}

const terminateAgentExecutionContextForDeletion = `-- name: TerminateAgentExecutionContextForDeletion :one
UPDATE agent_execution_contexts
SET target_residency='suspended',
    terminal_reason='context_deleted',
    terminated_at=clock_timestamp(),
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE context_key=$1::text
  AND state_revision=$2::bigint
  AND terminal_reason IS NULL
RETURNING context_key
`

type TerminateAgentExecutionContextForDeletionParams struct {
	ContextKey       string `json:"context_key"`
	ExpectedRevision int64  `json:"expected_revision"`
}

func (q *Queries) TerminateAgentExecutionContextForDeletion(ctx context.Context, arg TerminateAgentExecutionContextForDeletionParams) (string, error) {
	row := q.db.QueryRow(ctx, terminateAgentExecutionContextForDeletion, arg.ContextKey, arg.ExpectedRevision)
	var context_key string
	err := row.Scan(&context_key)
	return context_key, err
}

const terminateAgentLocalRuns = `-- name: TerminateAgentLocalRuns :many
UPDATE agent_local_runs
SET status=$1::text,terminal=$2::jsonb,
    finished_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE run_id=ANY($3::text[])
  AND status IN ('queued','running')
RETURNING run_id,context_key
`

type TerminateAgentLocalRunsParams struct {
	Status   string   `json:"status"`
	Terminal []byte   `json:"terminal"`
	RunIds   []string `json:"run_ids"`
}

type TerminateAgentLocalRunsRow struct {
	RunID      string `json:"run_id"`
	ContextKey string `json:"context_key"`
}

func (q *Queries) TerminateAgentLocalRuns(ctx context.Context, arg TerminateAgentLocalRunsParams) ([]TerminateAgentLocalRunsRow, error) {
	rows, err := q.db.Query(ctx, terminateAgentLocalRuns, arg.Status, arg.Terminal, arg.RunIds)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []TerminateAgentLocalRunsRow{}
	for rows.Next() {
		var i TerminateAgentLocalRunsRow
		if err := rows.Scan(&i.RunID, &i.ContextKey); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const terminateOpenAgentExecutionContextsForAgentRevocation = `-- name: TerminateOpenAgentExecutionContextsForAgentRevocation :many
UPDATE agent_execution_contexts
SET target_residency='suspended',
    terminal_reason='context_deleted',
    terminated_at=clock_timestamp(),
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE tenant_id=$1::text
  AND agent_actor_id=$2::text
  AND terminal_reason IS NULL
RETURNING context_key
`

type TerminateOpenAgentExecutionContextsForAgentRevocationParams struct {
	TenantID     string `json:"tenant_id"`
	AgentActorID string `json:"agent_actor_id"`
}

func (q *Queries) TerminateOpenAgentExecutionContextsForAgentRevocation(ctx context.Context, arg TerminateOpenAgentExecutionContextsForAgentRevocationParams) ([]string, error) {
	rows, err := q.db.Query(ctx, terminateOpenAgentExecutionContextsForAgentRevocation, arg.TenantID, arg.AgentActorID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []string{}
	for rows.Next() {
		var context_key string
		if err := rows.Scan(&context_key); err != nil {
			return nil, err
		}
		items = append(items, context_key)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const terminatePerRoomMetaContextForRoomDeletion = `-- name: TerminatePerRoomMetaContextForRoomDeletion :one
UPDATE agent_execution_contexts
SET target_residency='suspended',
    terminal_reason='room_deleted',
    terminated_at=clock_timestamp(),
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE agent_actor_id=$1::text
  AND context_kind='meta'
  AND room_id=$2::text
  AND membership_epoch_id=$3::text
  AND terminal_reason IS NULL
RETURNING context_key
`

type TerminatePerRoomMetaContextForRoomDeletionParams struct {
	AgentActorID      string `json:"agent_actor_id"`
	RoomID            string `json:"room_id"`
	MembershipEpochID string `json:"membership_epoch_id"`
}

func (q *Queries) TerminatePerRoomMetaContextForRoomDeletion(ctx context.Context, arg TerminatePerRoomMetaContextForRoomDeletionParams) (string, error) {
	row := q.db.QueryRow(ctx, terminatePerRoomMetaContextForRoomDeletion, arg.AgentActorID, arg.RoomID, arg.MembershipEpochID)
	var context_key string
	err := row.Scan(&context_key)
	return context_key, err
}

const terminateWorkRoomPerRoomMetaContext = `-- name: TerminateWorkRoomPerRoomMetaContext :one
UPDATE agent_execution_contexts
SET target_residency='suspended',
    terminal_reason='context_deleted',
    terminated_at=clock_timestamp(),
    state_revision=state_revision+1,
    updated_at=clock_timestamp()
WHERE context_key=$1::text
  AND context_kind='meta'
  AND terminal_reason IS NULL
RETURNING context_key
`

func (q *Queries) TerminateWorkRoomPerRoomMetaContext(ctx context.Context, contextKey string) (string, error) {
	row := q.db.QueryRow(ctx, terminateWorkRoomPerRoomMetaContext, contextKey)
	var context_key string
	err := row.Scan(&context_key)
	return context_key, err
}

const touchAgentRuntimeLocalComputer = `-- name: TouchAgentRuntimeLocalComputer :one
UPDATE local_computers
SET status=$1::text,
    runtime_inventory=COALESCE($2::jsonb,runtime_inventory),
    runtime_diagnostics=COALESCE($3::jsonb,runtime_diagnostics),
    daemon_version=COALESCE($4::text,daemon_version),
    recommended_version=COALESCE($5::text,recommended_version),
    active_operations=CASE WHEN $1::text='online'
        THEN COALESCE($6::integer,active_operations) ELSE 0 END,
    last_seen_at=$7::timestamptz,
    updated_at=clock_timestamp()
WHERE computer_id=$8::text AND status<>'removed'
RETURNING computer_id, display_name, status, credential_generation, capacity, active_operations, runtime_inventory, workspace_grants, runtime_diagnostics, last_seen_at, removed_at, created_at, updated_at, daemon_id, daemon_public_key, daemon_identity_version, platform, daemon_version, recommended_version, owner_tenant_id, owner_actor_id
`

type TouchAgentRuntimeLocalComputerParams struct {
	Status             string             `json:"status"`
	RuntimeInventory   []byte             `json:"runtime_inventory"`
	RuntimeDiagnostics []byte             `json:"runtime_diagnostics"`
	DaemonVersion      pgtype.Text        `json:"daemon_version"`
	RecommendedVersion pgtype.Text        `json:"recommended_version"`
	ActiveOperations   pgtype.Int4        `json:"active_operations"`
	LastSeenAt         pgtype.Timestamptz `json:"last_seen_at"`
	ComputerID         string             `json:"computer_id"`
}

func (q *Queries) TouchAgentRuntimeLocalComputer(ctx context.Context, arg TouchAgentRuntimeLocalComputerParams) (LocalComputer, error) {
	row := q.db.QueryRow(ctx, touchAgentRuntimeLocalComputer,
		arg.Status,
		arg.RuntimeInventory,
		arg.RuntimeDiagnostics,
		arg.DaemonVersion,
		arg.RecommendedVersion,
		arg.ActiveOperations,
		arg.LastSeenAt,
		arg.ComputerID,
	)
	var i LocalComputer
	err := row.Scan(
		&i.ComputerID,
		&i.DisplayName,
		&i.Status,
		&i.CredentialGeneration,
		&i.Capacity,
		&i.ActiveOperations,
		&i.RuntimeInventory,
		&i.WorkspaceGrants,
		&i.RuntimeDiagnostics,
		&i.LastSeenAt,
		&i.RemovedAt,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DaemonID,
		&i.DaemonPublicKey,
		&i.DaemonIdentityVersion,
		&i.Platform,
		&i.DaemonVersion,
		&i.RecommendedVersion,
		&i.OwnerTenantID,
		&i.OwnerActorID,
	)
	return i, err
}

const upsertAgentPerRoomMetaContext = `-- name: UpsertAgentPerRoomMetaContext :execrows
INSERT INTO agent_execution_contexts(
    context_key,tenant_id,agent_actor_id,agent_management_id,
    context_kind,room_id,membership_epoch_id,target_residency
) VALUES(
    $1::text,$2::text,
    $3::text,$4::text,
    'meta',$5::text,$6::text,
    'suspended'
)
ON CONFLICT(context_key) DO UPDATE SET
    membership_epoch_id=excluded.membership_epoch_id,
    target_residency='active',
    terminal_reason=NULL,terminated_at=NULL,
    state_revision=agent_execution_contexts.state_revision+1,
    updated_at=clock_timestamp()
WHERE agent_execution_contexts.tenant_id=excluded.tenant_id
  AND agent_execution_contexts.agent_actor_id=excluded.agent_actor_id
  AND agent_execution_contexts.agent_management_id=excluded.agent_management_id
  AND agent_execution_contexts.context_kind='meta'
  AND agent_execution_contexts.task_id IS NULL
  AND agent_execution_contexts.room_id=excluded.room_id
  AND (agent_execution_contexts.terminal_reason IS NULL OR agent_execution_contexts.terminal_reason='context_deleted')
  AND agent_execution_contexts.membership_epoch_id IS DISTINCT FROM excluded.membership_epoch_id
  AND EXISTS (
      SELECT 1 FROM room_members membership
      WHERE membership.room_id=excluded.room_id
        AND membership.actor_id=excluded.agent_actor_id
        AND membership.membership_epoch_id=excluded.membership_epoch_id
  )
`

type UpsertAgentPerRoomMetaContextParams struct {
	ContextKey        string `json:"context_key"`
	TenantID          string `json:"tenant_id"`
	AgentActorID      string `json:"agent_actor_id"`
	AgentManagementID string `json:"agent_management_id"`
	RoomID            string `json:"room_id"`
	MembershipEpochID string `json:"membership_epoch_id"`
}

func (q *Queries) UpsertAgentPerRoomMetaContext(ctx context.Context, arg UpsertAgentPerRoomMetaContextParams) (int64, error) {
	result, err := q.db.Exec(ctx, upsertAgentPerRoomMetaContext,
		arg.ContextKey,
		arg.TenantID,
		arg.AgentActorID,
		arg.AgentManagementID,
		arg.RoomID,
		arg.MembershipEpochID,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const upsertLocalComputerModelSnapshot = `-- name: UpsertLocalComputerModelSnapshot :exec
INSERT INTO local_computer_model_snapshots(computer_id,snapshot,host,observed_at,updated_at)
VALUES($1::text,$2::jsonb,$3::jsonb,
       $4::timestamptz,clock_timestamp())
ON CONFLICT (computer_id) DO UPDATE
SET snapshot=EXCLUDED.snapshot,
    host=COALESCE(EXCLUDED.host,local_computer_model_snapshots.host),
    observed_at=EXCLUDED.observed_at,updated_at=EXCLUDED.updated_at
`

type UpsertLocalComputerModelSnapshotParams struct {
	ComputerID string             `json:"computer_id"`
	Snapshot   []byte             `json:"snapshot"`
	Host       []byte             `json:"host"`
	ObservedAt pgtype.Timestamptz `json:"observed_at"`
}

func (q *Queries) UpsertLocalComputerModelSnapshot(ctx context.Context, arg UpsertLocalComputerModelSnapshotParams) error {
	_, err := q.db.Exec(ctx, upsertLocalComputerModelSnapshot,
		arg.ComputerID,
		arg.Snapshot,
		arg.Host,
		arg.ObservedAt,
	)
	return err
}