CUB-123: integrate gateway, wire PostgreSQL repositories, add SSE streaming
All checks were successful
Dev Build / build-test (pull_request) Successful in 2m23s

- Create repository/ package with pgx-backed CRUD for agents, sessions, tasks, projects
- Define AgentRepo/SessionRepo/TaskRepo/ProjectRepo interfaces
- Update handler to use repository interfaces instead of in-memory stores
- Add SSE broker with GET /api/events endpoint (text/event-stream)
- Add gateway client that polls OpenClaw for agent states
- Add GATEWAY_URL and GATEWAY_POLL_INTERVAL config fields
- Seed 5 demo agents (Otto, Rex, Dex, Hex, Pip) on empty DB
- Update router to wire SSE broker
- All 21 handler tests pass with mock repos
This commit is contained in:
2026-05-08 19:58:06 -04:00
parent 4a2e660a4a
commit e8ced74429
16 changed files with 1207 additions and 109 deletions

View File

@@ -0,0 +1,186 @@
// Package repository provides PostgreSQL-backed CRUD implementations
// for the Control Center domain entities. Each repository takes a
// *pgxpool.Pool in its constructor and uses pgx.CollectRows() for scanning.
package repository
import (
"context"
"fmt"
"time"
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// AgentRepository provides PostgreSQL-backed CRUD for agents.
type AgentRepository struct {
pool *pgxpool.Pool
}
// NewAgentRepository returns a repository wired to the given connection pool.
func NewAgentRepository(pool *pgxpool.Pool) *AgentRepository {
return &AgentRepository{pool: pool}
}
// Create inserts a new agent. It maps the models.AgentCardData fields onto
// the agents table columns (uuid id, text name, text status, text task,
// int progress, text session_key, text channel).
func (r *AgentRepository) Create(ctx context.Context, a models.AgentCardData) error {
prog := 0
if a.TaskProgress != nil {
prog = *a.TaskProgress
}
_, err := r.pool.Exec(ctx, `
INSERT INTO agents (id, name, status, task, progress, session_key, channel, last_activity)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`, a.ID, a.DisplayName, string(a.Status), a.CurrentTask, prog,
a.SessionKey, a.Channel, time.Now().UTC())
return err
}
// Get returns a single agent by its string id.
func (r *AgentRepository) Get(ctx context.Context, id string) (models.AgentCardData, error) {
var a models.AgentCardData
var task *string
var prog int
var lastActivity time.Time
err := r.pool.QueryRow(ctx, `
SELECT id, name, status, task, progress, session_key, channel, last_activity
FROM agents WHERE id = $1
`, id).Scan(&a.ID, &a.DisplayName, &a.Status, &task, &prog,
&a.SessionKey, &a.Channel, &lastActivity)
if err != nil {
return a, err
}
a.CurrentTask = task
if prog > 0 || task != nil {
p := prog
a.TaskProgress = &p
}
a.LastActivity = lastActivity.UTC().Format(time.RFC3339)
// Role is not persisted in the current schema — set a sensible default.
a.Role = "agent"
return a, nil
}
// List returns all agents, optionally filtered by status.
// Results are ordered by name (display_name).
func (r *AgentRepository) List(ctx context.Context, statusFilter models.AgentStatus) ([]models.AgentCardData, error) {
var rows pgx.Rows
var err error
if statusFilter != "" {
rows, err = r.pool.Query(ctx, `
SELECT id, name, status, task, progress, session_key, channel, last_activity
FROM agents WHERE status = $1 ORDER BY name
`, string(statusFilter))
} else {
rows, err = r.pool.Query(ctx, `
SELECT id, name, status, task, progress, session_key, channel, last_activity
FROM agents ORDER BY name
`)
}
if err != nil {
return nil, err
}
defer rows.Close()
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (models.AgentCardData, error) {
var a models.AgentCardData
var task *string
var prog int
var lastActivity time.Time
if err := row.Scan(&a.ID, &a.DisplayName, &a.Status, &task, &prog,
&a.SessionKey, &a.Channel, &lastActivity); err != nil {
return a, err
}
a.CurrentTask = task
if prog > 0 || task != nil {
p := prog
a.TaskProgress = &p
}
a.LastActivity = lastActivity.UTC().Format(time.RFC3339)
a.Role = "agent"
return a, nil
})
}
// Update applies partial updates to an agent. Returns the updated agent.
func (r *AgentRepository) Update(ctx context.Context, id string, req models.UpdateAgentRequest) (models.AgentCardData, error) {
// Build dynamic SET clause.
setClauses := []string{"last_activity = $2"}
args := []any{id, time.Now().UTC()}
argIdx := 3
if req.Status != nil {
setClauses = append(setClauses, fmt.Sprintf("status = $%d", argIdx))
args = append(args, string(*req.Status))
argIdx++
}
if req.CurrentTask != nil {
setClauses = append(setClauses, fmt.Sprintf("task = $%d", argIdx))
args = append(args, *req.CurrentTask)
argIdx++
}
if req.TaskProgress != nil {
setClauses = append(setClauses, fmt.Sprintf("progress = $%d", argIdx))
args = append(args, *req.TaskProgress)
argIdx++
}
if req.Channel != nil {
setClauses = append(setClauses, fmt.Sprintf("channel = $%d", argIdx))
args = append(args, *req.Channel)
argIdx++
}
// Build and execute
query := "UPDATE agents SET "
for i, clause := range setClauses {
if i > 0 {
query += ", "
}
query += clause
}
query += " WHERE id = $1"
ct, err := r.pool.Exec(ctx, query, args...)
if err != nil {
return models.AgentCardData{}, err
}
if ct.RowsAffected() == 0 {
return models.AgentCardData{}, fmt.Errorf("agent not found: %s", id)
}
return r.Get(ctx, id)
}
// Delete removes an agent. Returns nil even if the agent doesn't exist
// (idempotent). Returns a wrapped error only on transport failures.
func (r *AgentRepository) Delete(ctx context.Context, id string) error {
_, err := r.pool.Exec(ctx, `DELETE FROM agents WHERE id = $1`, id)
return err
}
// Count returns the total number of agents.
func (r *AgentRepository) Count(ctx context.Context) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM agents`).Scan(&n)
return n, err
}
// CountByStatus returns the number of agents with the given status.
func (r *AgentRepository) CountByStatus(ctx context.Context, status models.AgentStatus) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM agents WHERE status = $1`, string(status)).Scan(&n)
return n, err
}

View File

@@ -0,0 +1,38 @@
package repository
import (
"context"
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
)
// AgentRepo is the interface for agent persistence operations.
type AgentRepo interface {
Create(ctx context.Context, a models.AgentCardData) error
Get(ctx context.Context, id string) (models.AgentCardData, error)
List(ctx context.Context, statusFilter models.AgentStatus) ([]models.AgentCardData, error)
Update(ctx context.Context, id string, req models.UpdateAgentRequest) (models.AgentCardData, error)
Delete(ctx context.Context, id string) error
Count(ctx context.Context) (int, error)
}
// SessionRepo is the interface for session persistence operations.
type SessionRepo interface {
Create(ctx context.Context, s models.Session) (models.Session, error)
ListActive(ctx context.Context) ([]models.Session, error)
Count(ctx context.Context) (int, error)
}
// TaskRepo is the interface for task persistence operations.
type TaskRepo interface {
Create(ctx context.Context, t models.Task) (models.Task, error)
ListRecent(ctx context.Context) ([]models.Task, error)
Count(ctx context.Context) (int, error)
}
// ProjectRepo is the interface for project persistence operations.
type ProjectRepo interface {
Create(ctx context.Context, p models.Project) (models.Project, error)
List(ctx context.Context) ([]models.Project, error)
Count(ctx context.Context) (int, error)
}

View File

@@ -0,0 +1,94 @@
package repository
import (
"context"
"time"
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ProjectRepository provides PostgreSQL-backed CRUD for projects.
type ProjectRepository struct {
pool *pgxpool.Pool
}
// NewProjectRepository returns a repository wired to the given connection pool.
func NewProjectRepository(pool *pgxpool.Pool) *ProjectRepository {
return &ProjectRepository{pool: pool}
}
// Create inserts a new project. The current projects table only stores
// a single agent_id, so we use the first entry from AgentIDs if present.
func (r *ProjectRepository) Create(ctx context.Context, p models.Project) (models.Project, error) {
now := time.Now().UTC()
if p.CreatedAt.IsZero() {
p.CreatedAt = now
}
if p.UpdatedAt.IsZero() {
p.UpdatedAt = now
}
var agentID *string
if len(p.AgentIDs) > 0 {
agentID = &p.AgentIDs[0]
}
err := r.pool.QueryRow(ctx, `
INSERT INTO projects (name, description, status, agent_id, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, description, status, agent_id, created_at, updated_at
`, p.Name, p.Description, string(p.Status), agentID, p.CreatedAt, p.UpdatedAt).Scan(
&p.ID, &p.Name, &p.Description, &p.Status, &agentID,
&p.CreatedAt, &p.UpdatedAt,
)
if err != nil {
return p, err
}
if agentID != nil {
p.AgentIDs = []string{*agentID}
} else {
p.AgentIDs = []string{}
}
return p, nil
}
// List returns all projects ordered by name.
func (r *ProjectRepository) List(ctx context.Context) ([]models.Project, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, name, description, status, agent_id, created_at, updated_at
FROM projects
ORDER BY name
`)
if err != nil {
return nil, err
}
defer rows.Close()
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (models.Project, error) {
var p models.Project
var agentID *string
if err := row.Scan(&p.ID, &p.Name, &p.Description, &p.Status,
&agentID, &p.CreatedAt, &p.UpdatedAt); err != nil {
return p, err
}
if agentID != nil {
p.AgentIDs = []string{*agentID}
} else {
p.AgentIDs = []string{}
}
return p, nil
})
}
// Count returns the total number of projects.
func (r *ProjectRepository) Count(ctx context.Context) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM projects`).Scan(&n)
return n, err
}

View File

@@ -0,0 +1,78 @@
package repository
import (
"context"
"time"
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// SessionRepository provides PostgreSQL-backed CRUD for sessions.
type SessionRepository struct {
pool *pgxpool.Pool
}
// NewSessionRepository returns a repository wired to the given connection pool.
func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
return &SessionRepository{pool: pool}
}
// Create inserts a new session into the sessions table.
// Because the existing sessions table only has id, agent_id, started_at,
// ended_at, and status, we map what we can and store additional metadata
// as a fallback. AgentID is required by FK — if the session AgentID can't
// be cast to a valid UUID we store a sentinel.
func (r *SessionRepository) Create(ctx context.Context, s models.Session) (models.Session, error) {
if s.StartedAt.IsZero() {
s.StartedAt = time.Now().UTC()
}
if s.LastActivityAt.IsZero() {
s.LastActivityAt = s.StartedAt
}
err := r.pool.QueryRow(ctx, `
INSERT INTO sessions (agent_id, started_at, status)
VALUES ($1, $2, $3)
RETURNING id, agent_id, started_at, ended_at, status
`, s.AgentID, s.StartedAt, s.Status).Scan(
&s.ID, &s.AgentID, &s.StartedAt, nil, &s.Status)
return s, err
}
// ListActive returns all sessions with status 'running' or 'streaming',
// ordered by started_at descending.
func (r *SessionRepository) ListActive(ctx context.Context) ([]models.Session, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, agent_id, started_at, ended_at, status
FROM sessions
WHERE status IN ('running', 'streaming')
ORDER BY started_at DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (models.Session, error) {
var s models.Session
var endedAt *time.Time
if err := row.Scan(&s.ID, &s.AgentID, &s.StartedAt, &endedAt, &s.Status); err != nil {
return s, err
}
s.LastActivityAt = s.StartedAt
if endedAt != nil {
s.LastActivityAt = *endedAt
}
return s, nil
})
}
// Count returns the total number of sessions.
func (r *SessionRepository) Count(ctx context.Context) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM sessions`).Scan(&n)
return n, err
}

View File

@@ -0,0 +1,85 @@
package repository
import (
"context"
"time"
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// TaskRepository provides PostgreSQL-backed CRUD for task_logs.
type TaskRepository struct {
pool *pgxpool.Pool
}
// NewTaskRepository returns a repository wired to the given connection pool.
func NewTaskRepository(pool *pgxpool.Pool) *TaskRepository {
return &TaskRepository{pool: pool}
}
// Create inserts a new task into the task_logs table.
func (r *TaskRepository) Create(ctx context.Context, t models.Task) (models.Task, error) {
now := time.Now().UTC()
if t.CreatedAt.IsZero() {
t.CreatedAt = now
}
if t.UpdatedAt.IsZero() {
t.UpdatedAt = now
}
err := r.pool.QueryRow(ctx, `
INSERT INTO task_logs (agent_id, task, status, started_at)
VALUES ($1, $2, $3, $4)
RETURNING id, agent_id, task, status, started_at, completed_at, error_message
`, t.AgentID, t.Title, string(t.Status), t.CreatedAt).Scan(
&t.ID, &t.AgentID, &t.Title, &t.Status, &t.CreatedAt,
nil, nil,
)
if err != nil {
return t, err
}
// Rebuild the Description since task_logs only stores the title as "task".
t.Description = t.Title
return t, nil
}
// ListRecent returns the most recent tasks, newest first.
func (r *TaskRepository) ListRecent(ctx context.Context) ([]models.Task, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, agent_id, task, status, started_at, completed_at, error_message
FROM task_logs
ORDER BY started_at DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (models.Task, error) {
var t models.Task
var completedAt *time.Time
var errMsg *string
if err := row.Scan(&t.ID, &t.AgentID, &t.Title, &t.Status,
&t.CreatedAt, &completedAt, &errMsg); err != nil {
return t, err
}
t.Description = t.Title
t.UpdatedAt = t.CreatedAt
if completedAt != nil {
t.UpdatedAt = *completedAt
}
return t, nil
})
}
// Count returns the total number of tasks.
func (r *TaskRepository) Count(ctx context.Context) (int, error) {
var n int
err := r.pool.QueryRow(ctx, `SELECT COUNT(*) FROM task_logs`).Scan(&n)
return n, err
}