step 5 (partial): strip dropped packages from production code
Removed all references to dropped packages in non-test code.
Zero dropped imports, store refs, or model types remaining.
Major removals:
- scheduler/ package (entire dir) — tasks moved to extension track
- taskutil/ package (entire dir)
- health/ package (entire dir) — provider/tool health
- sandbox/provider_module.go — provider.complete module
- handlers: workflow_entry, workflow_instances, workflow_forms,
workflow_assignments, workflow_monitor, health_admin (6 files)
- auth/session.go, middleware/session_auth.go
- store/{postgres,sqlite}/sessions.go, tasks.go
Rewrites:
- store/{postgres,sqlite}/health.go — kernel-only Prune
(ws_tickets, rate_limit_counters, stale presence)
- handlers/admin.go: 847→467 lines (stripped provider CRUD)
- handlers/teams.go: 520→411 lines (stripped model listing)
- sandbox/runner.go: removed ProviderResolver
- sandbox/workflow_module.go: 216→83 lines (definition-only)
- main.go: 1579→1325 lines (stripped dropped package init)
- pages/pages.go: stripped channel/session lookups
- events/types.go: stripped chat/channel/workspace event routes
- models: stripped stale types, constants, notification types
Store interface cleanup:
- Removed SessionStore, TaskStore from Stores struct
- Stripped workflow assignment methods from WorkflowStore iface
- Stripped assignment methods from PG+SQLite workflow stores
- Updated testhelper.go table list to kernel-only
Migrations: removed 008_tasks.sql (both dialects)
-9665/+69 lines across 51 files.
This commit is contained in:
@@ -33,14 +33,12 @@ type Stores struct {
|
||||
ResourceGrants ResourceGrantStore
|
||||
Notifications NotificationStore
|
||||
NotifPrefs NotificationPreferenceStore
|
||||
Sessions SessionStore
|
||||
Presence PresenceStore // v0.29.0: User online/offline status
|
||||
Health HealthStore // v0.29.0: Provider health window management
|
||||
Connections ConnectionStore // v0.38.1: Extension connection credentials
|
||||
Dependencies DependencyStore // v0.38.2: Library package dependency graph
|
||||
Packages PackageStore // v0.28.7: Unified package registry (surfaces + extensions)
|
||||
Workflows WorkflowStore // v0.26.1: Workflow definitions + stages
|
||||
Tasks TaskStore // v0.27.1: Task scheduling + run history
|
||||
ExtPermissions ExtensionPermissionStore // v0.29.0: Extension declared/granted capabilities
|
||||
ExtData ExtDataStore // v0.29.2: Extension namespaced table catalog
|
||||
Tickets TicketStore // v0.32.0: WS auth tickets (PG-backed for cross-pod)
|
||||
@@ -312,19 +310,6 @@ type NotificationPreferenceStore interface {
|
||||
// SESSION STORE (v0.24.3)
|
||||
// =========================================
|
||||
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, s *models.SessionParticipant) error
|
||||
GetByToken(ctx context.Context, token string) (*models.SessionParticipant, error)
|
||||
GetByID(ctx context.Context, id string) (*models.SessionParticipant, error)
|
||||
ListForChannel(ctx context.Context, channelID string) ([]models.SessionParticipant, error)
|
||||
CountForChannel(ctx context.Context, channelID string) (int, error)
|
||||
Delete(ctx context.Context, id string) error
|
||||
|
||||
// DeleteExpired removes sessions older than the given time that have
|
||||
// no associated messages. Returns the number of deleted rows.
|
||||
// Used by the background session cleanup job (v0.26.0).
|
||||
DeleteExpired(ctx context.Context, olderThan time.Time) (int64, error)
|
||||
}
|
||||
|
||||
// =========================================
|
||||
// HEALTH STORE (v0.29.0)
|
||||
|
||||
@@ -2,191 +2,42 @@ package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"switchboard-core/models"
|
||||
"switchboard-core/database"
|
||||
)
|
||||
|
||||
// HealthStore implements health.Store for Postgres.
|
||||
type HealthStore struct {
|
||||
db *sql.DB
|
||||
}
|
||||
// ── HealthStore ─────────────────────────────
|
||||
|
||||
func NewHealthStore(db *sql.DB) *HealthStore {
|
||||
return &HealthStore{db: db}
|
||||
}
|
||||
type HealthStore struct{}
|
||||
|
||||
func (s *HealthStore) UpsertWindow(ctx context.Context, w *models.ProviderHealthWindow) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO provider_health (provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
|
||||
ON CONFLICT (provider_config_id, window_start) DO UPDATE SET
|
||||
request_count = provider_health.request_count + EXCLUDED.request_count,
|
||||
error_count = provider_health.error_count + EXCLUDED.error_count,
|
||||
timeout_count = provider_health.timeout_count + EXCLUDED.timeout_count,
|
||||
rate_limit_count = provider_health.rate_limit_count + EXCLUDED.rate_limit_count,
|
||||
total_latency_ms = provider_health.total_latency_ms + EXCLUDED.total_latency_ms,
|
||||
max_latency_ms = GREATEST(provider_health.max_latency_ms, EXCLUDED.max_latency_ms),
|
||||
last_error = COALESCE(EXCLUDED.last_error, provider_health.last_error),
|
||||
last_error_at = COALESCE(EXCLUDED.last_error_at, provider_health.last_error_at),
|
||||
updated_at = now()
|
||||
`, w.ProviderConfigID, w.WindowStart,
|
||||
w.RequestCount, w.ErrorCount, w.TimeoutCount, w.RateLimitCount,
|
||||
w.TotalLatencyMs, w.MaxLatencyMs, w.LastError, w.LastErrorAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *HealthStore) GetCurrentWindow(ctx context.Context, providerConfigID string) (*models.ProviderHealthWindow, error) {
|
||||
windowStart := time.Now().UTC().Truncate(time.Hour)
|
||||
var w models.ProviderHealthWindow
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE provider_config_id = $1 AND window_start = $2
|
||||
`, providerConfigID, windowStart).Scan(
|
||||
&w.ID, &w.ProviderConfigID, &w.WindowStart,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TimeoutCount, &w.RateLimitCount,
|
||||
&w.TotalLatencyMs, &w.MaxLatencyMs, &w.LastError, &w.LastErrorAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &w, err
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListWindows(ctx context.Context, providerConfigID string, hours int) ([]models.ProviderHealthWindow, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE provider_config_id = $1
|
||||
ORDER BY window_start DESC
|
||||
LIMIT $2
|
||||
`, providerConfigID, hours)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.ProviderHealthWindow
|
||||
for rows.Next() {
|
||||
var w models.ProviderHealthWindow
|
||||
if err := rows.Scan(
|
||||
&w.ID, &w.ProviderConfigID, &w.WindowStart,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TimeoutCount, &w.RateLimitCount,
|
||||
&w.TotalLatencyMs, &w.MaxLatencyMs, &w.LastError, &w.LastErrorAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, w)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListAllCurrent(ctx context.Context) ([]models.ProviderHealthWindow, error) {
|
||||
windowStart := time.Now().UTC().Truncate(time.Hour)
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE window_start = $1
|
||||
ORDER BY provider_config_id
|
||||
`, windowStart)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.ProviderHealthWindow
|
||||
for rows.Next() {
|
||||
var w models.ProviderHealthWindow
|
||||
if err := rows.Scan(
|
||||
&w.ID, &w.ProviderConfigID, &w.WindowStart,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TimeoutCount, &w.RateLimitCount,
|
||||
&w.TotalLatencyMs, &w.MaxLatencyMs, &w.LastError, &w.LastErrorAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, w)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
func NewHealthStore() *HealthStore { return &HealthStore{} }
|
||||
|
||||
// Prune deletes stale kernel data older than the given time.
|
||||
// Cleans: expired ws_tickets, old rate_limit_counters, stale presence.
|
||||
func (s *HealthStore) Prune(ctx context.Context, before time.Time) (int64, error) {
|
||||
result, err := s.db.ExecContext(ctx, `
|
||||
DELETE FROM provider_health WHERE window_start < $1
|
||||
`, before)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
var total int64
|
||||
|
||||
res, _ := database.DB.ExecContext(ctx,
|
||||
`DELETE FROM ws_tickets WHERE expires_at < $1`, before)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
// Also prune tool health
|
||||
s.db.ExecContext(ctx, `DELETE FROM tool_health WHERE window_start < $1`, before)
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
// ── Tool Health (v0.22.4) ────────────────────
|
||||
|
||||
func (s *HealthStore) UpsertToolWindow(ctx context.Context, w *models.ToolHealthWindow) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO tool_health (tool_name, window_start,
|
||||
request_count, error_count, total_latency_ms, max_latency_ms,
|
||||
last_error, last_error_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now())
|
||||
ON CONFLICT (tool_name, window_start) DO UPDATE SET
|
||||
request_count = tool_health.request_count + EXCLUDED.request_count,
|
||||
error_count = tool_health.error_count + EXCLUDED.error_count,
|
||||
total_latency_ms = tool_health.total_latency_ms + EXCLUDED.total_latency_ms,
|
||||
max_latency_ms = GREATEST(tool_health.max_latency_ms, EXCLUDED.max_latency_ms),
|
||||
last_error = COALESCE(EXCLUDED.last_error, tool_health.last_error),
|
||||
last_error_at = COALESCE(EXCLUDED.last_error_at, tool_health.last_error_at),
|
||||
updated_at = now()
|
||||
`, w.ToolName, w.WindowStart,
|
||||
w.RequestCount, w.ErrorCount, w.TotalLatencyMs, w.MaxLatencyMs,
|
||||
w.LastError, w.LastErrorAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListAllToolCurrent(ctx context.Context) ([]models.ToolHealthWindow, error) {
|
||||
windowStart := time.Now().UTC().Truncate(time.Hour)
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, tool_name, window_start,
|
||||
request_count, error_count, total_latency_ms, max_latency_ms,
|
||||
last_error, last_error_at
|
||||
FROM tool_health
|
||||
WHERE window_start = $1
|
||||
ORDER BY tool_name
|
||||
`, windowStart)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
res, _ = database.DB.ExecContext(ctx,
|
||||
`DELETE FROM rate_limit_counters WHERE window_start < $1`, before)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.ToolHealthWindow
|
||||
for rows.Next() {
|
||||
var w models.ToolHealthWindow
|
||||
if err := rows.Scan(
|
||||
&w.ID, &w.ToolName, &w.WindowStart,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TotalLatencyMs, &w.MaxLatencyMs,
|
||||
&w.LastError, &w.LastErrorAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, w)
|
||||
res, _ = database.DB.ExecContext(ctx,
|
||||
`DELETE FROM user_presence WHERE last_seen < $1 AND status = 'offline'`, before)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// DeactivateProvider marks a provider config as inactive (for auto-disable).
|
||||
func (s *HealthStore) DeactivateProvider(ctx context.Context, configID string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE provider_configs SET is_active = false WHERE id = $1`, configID)
|
||||
return err
|
||||
return total, nil
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"switchboard-core/models"
|
||||
)
|
||||
|
||||
// ── SessionStore ───────────────────────────
|
||||
|
||||
type SessionStore struct{}
|
||||
|
||||
func NewSessionStore() *SessionStore { return &SessionStore{} }
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, sp *models.SessionParticipant) error {
|
||||
return DB.QueryRowContext(ctx, `
|
||||
INSERT INTO session_participants (session_token, channel_id, display_name, fingerprint)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, created_at`,
|
||||
sp.SessionToken, sp.ChannelID, sp.DisplayName, nullText(sp.Fingerprint),
|
||||
).Scan(&sp.ID, &sp.CreatedAt)
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByToken(ctx context.Context, token string) (*models.SessionParticipant, error) {
|
||||
sp := &models.SessionParticipant{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE session_token = $1`, token,
|
||||
).Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, &sp.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByID(ctx context.Context, id string) (*models.SessionParticipant, error) {
|
||||
sp := &models.SessionParticipant{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE id = $1`, id,
|
||||
).Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, &sp.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) ListForChannel(ctx context.Context, channelID string) ([]models.SessionParticipant, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE channel_id = $1
|
||||
ORDER BY created_at ASC`, channelID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.SessionParticipant
|
||||
for rows.Next() {
|
||||
var sp models.SessionParticipant
|
||||
if err := rows.Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, &sp.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, sp)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) CountForChannel(ctx context.Context, channelID string) (int, error) {
|
||||
var count int
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM session_participants WHERE channel_id = $1`, channelID,
|
||||
).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (s *SessionStore) Delete(ctx context.Context, id string) error {
|
||||
res, err := DB.ExecContext(ctx, `DELETE FROM session_participants WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteExpired removes sessions created before olderThan whose channel
|
||||
// has no messages. Returns the count of deleted rows.
|
||||
func (s *SessionStore) DeleteExpired(ctx context.Context, olderThan time.Time) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
DELETE FROM session_participants sp
|
||||
WHERE sp.created_at < $1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM messages m WHERE m.channel_id = sp.channel_id
|
||||
)`, olderThan)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// nullText returns nil for empty strings.
|
||||
func nullText(s string) interface{} {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -19,14 +19,12 @@ func NewStores(db *sql.DB) store.Stores {
|
||||
ResourceGrants: NewResourceGrantStore(),
|
||||
Notifications: NewNotificationStore(),
|
||||
NotifPrefs: NewNotificationPreferenceStore(),
|
||||
Sessions: NewSessionStore(),
|
||||
Presence: NewPresenceStore(),
|
||||
Health: NewHealthStore(db),
|
||||
Connections: NewConnectionStore(),
|
||||
Dependencies: NewDependencyStore(),
|
||||
Packages: NewPackageStore(),
|
||||
Workflows: NewWorkflowStore(),
|
||||
Tasks: NewTaskStore(),
|
||||
ExtPermissions: NewExtensionPermissionStore(db),
|
||||
ExtData: NewExtDataStore(db),
|
||||
Tickets: NewTicketStore(),
|
||||
|
||||
@@ -1,325 +0,0 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"switchboard-core/models"
|
||||
)
|
||||
|
||||
type TaskStore struct{}
|
||||
|
||||
func NewTaskStore() *TaskStore { return &TaskStore{} }
|
||||
|
||||
// ── Full column list (single source of truth) ──────────────────
|
||||
// Used by GetByID, GetByTriggerToken, and list(). Every query must
|
||||
// SELECT and Scan the same columns in the same order to prevent drift.
|
||||
//
|
||||
// scanTask is the ONLY function that maps columns → struct fields.
|
||||
// If a column is added or reordered, update taskColumns + scanTask.
|
||||
|
||||
// taskColumns is the canonical SELECT list for tasks.
|
||||
// COALESCE wraps nullable columns that scan into non-pointer Go types
|
||||
// (string, json.RawMessage). database/sql returns "unsupported Scan,
|
||||
// storing driver.Value type <nil>" for these without COALESCE.
|
||||
const taskColumns = `id, owner_id, team_id, name, description, scope,
|
||||
task_type, COALESCE(system_function, '') AS system_function,
|
||||
persona_id, model_id, system_prompt, user_prompt,
|
||||
workflow_id, COALESCE(tool_grants, '[]'::jsonb) AS tool_grants,
|
||||
schedule, timezone, is_active,
|
||||
COALESCE(trigger_token, '') AS trigger_token,
|
||||
max_tokens, max_tool_calls, max_wall_clock, output_mode,
|
||||
output_channel_id,
|
||||
COALESCE(webhook_url, '') AS webhook_url,
|
||||
COALESCE(webhook_secret, '') AS webhook_secret,
|
||||
provider_config_id,
|
||||
notify_on_complete, notify_on_failure,
|
||||
last_run_at, next_run_at, run_count, created_at, updated_at`
|
||||
|
||||
// scanTask maps one row from taskColumns into a Task struct.
|
||||
// Single source of truth — used by GetByID, GetByTriggerToken, and list().
|
||||
func scanTask(scanner interface{ Scan(...interface{}) error }, t *models.Task) error {
|
||||
return scanner.Scan(
|
||||
&t.ID, &t.OwnerID, &t.TeamID, &t.Name, &t.Description, &t.Scope,
|
||||
&t.TaskType, &t.SystemFunction,
|
||||
&t.PersonaID, &t.ModelID, &t.SystemPrompt, &t.UserPrompt,
|
||||
&t.WorkflowID, &t.ToolGrants, &t.Schedule, &t.Timezone, &t.IsActive,
|
||||
&t.TriggerToken,
|
||||
&t.MaxTokens, &t.MaxToolCalls, &t.MaxWallClock, &t.OutputMode,
|
||||
&t.OutputChannelID, &t.WebhookURL, &t.WebhookSecret, &t.ProviderConfigID,
|
||||
&t.NotifyOnComplete, &t.NotifyOnFailure,
|
||||
&t.LastRunAt, &t.NextRunAt, &t.RunCount, &t.CreatedAt, &t.UpdatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
// ── CRUD ───────────────────────────────────────
|
||||
|
||||
func (s *TaskStore) Create(ctx context.Context, t *models.Task) error {
|
||||
toolGrants := jsonOrNull(t.ToolGrants)
|
||||
return DB.QueryRowContext(ctx, `
|
||||
INSERT INTO tasks (owner_id, team_id, name, description, scope,
|
||||
task_type, system_function,
|
||||
persona_id, model_id, system_prompt, user_prompt,
|
||||
workflow_id, tool_grants, schedule, timezone, is_active,
|
||||
trigger_token,
|
||||
max_tokens, max_tool_calls, max_wall_clock, output_mode,
|
||||
output_channel_id, webhook_url, webhook_secret, provider_config_id,
|
||||
notify_on_complete, notify_on_failure, next_run_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28)
|
||||
RETURNING id, created_at, updated_at`,
|
||||
t.OwnerID, t.TeamID, t.Name, t.Description, t.Scope,
|
||||
t.TaskType, t.SystemFunction,
|
||||
t.PersonaID, t.ModelID, t.SystemPrompt, t.UserPrompt,
|
||||
t.WorkflowID, toolGrants, t.Schedule, t.Timezone, t.IsActive,
|
||||
nilIfEmpty(t.TriggerToken),
|
||||
t.MaxTokens, t.MaxToolCalls, t.MaxWallClock, t.OutputMode,
|
||||
t.OutputChannelID, t.WebhookURL, t.WebhookSecret, t.ProviderConfigID,
|
||||
t.NotifyOnComplete, t.NotifyOnFailure, t.NextRunAt,
|
||||
).Scan(&t.ID, &t.CreatedAt, &t.UpdatedAt)
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetByID(ctx context.Context, id string) (*models.Task, error) {
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx,
|
||||
`SELECT `+taskColumns+` FROM tasks WHERE id = $1`, id,
|
||||
)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetByTriggerToken(ctx context.Context, token string) (*models.Task, error) {
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx,
|
||||
`SELECT `+taskColumns+` FROM tasks WHERE trigger_token = $1`, token,
|
||||
)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) Update(ctx context.Context, id string, p models.TaskPatch) error {
|
||||
// Dynamic PATCH: only update non-nil fields
|
||||
q := "UPDATE tasks SET updated_at = NOW()"
|
||||
args := []interface{}{}
|
||||
i := 1
|
||||
if p.Name != nil { q += comma(i, "name"); args = append(args, *p.Name); i++ }
|
||||
if p.Description != nil { q += comma(i, "description"); args = append(args, *p.Description); i++ }
|
||||
if p.PersonaID != nil { q += comma(i, "persona_id"); args = append(args, *p.PersonaID); i++ }
|
||||
if p.ModelID != nil { q += comma(i, "model_id"); args = append(args, *p.ModelID); i++ }
|
||||
if p.SystemPrompt != nil { q += comma(i, "system_prompt"); args = append(args, *p.SystemPrompt); i++ }
|
||||
if p.UserPrompt != nil { q += comma(i, "user_prompt"); args = append(args, *p.UserPrompt); i++ }
|
||||
if p.WorkflowID != nil { q += comma(i, "workflow_id"); args = append(args, *p.WorkflowID); i++ }
|
||||
if p.ToolGrants != nil { q += comma(i, "tool_grants"); args = append(args, jsonOrNull(*p.ToolGrants)); i++ }
|
||||
if p.Schedule != nil { q += comma(i, "schedule"); args = append(args, *p.Schedule); i++ }
|
||||
if p.Timezone != nil { q += comma(i, "timezone"); args = append(args, *p.Timezone); i++ }
|
||||
if p.IsActive != nil { q += comma(i, "is_active"); args = append(args, *p.IsActive); i++ }
|
||||
if p.MaxTokens != nil { q += comma(i, "max_tokens"); args = append(args, *p.MaxTokens); i++ }
|
||||
if p.MaxToolCalls != nil { q += comma(i, "max_tool_calls"); args = append(args, *p.MaxToolCalls); i++ }
|
||||
if p.MaxWallClock != nil { q += comma(i, "max_wall_clock"); args = append(args, *p.MaxWallClock); i++ }
|
||||
if p.OutputMode != nil { q += comma(i, "output_mode"); args = append(args, *p.OutputMode); i++ }
|
||||
if p.OutputChannelID != nil { q += comma(i, "output_channel_id"); args = append(args, *p.OutputChannelID); i++ }
|
||||
if p.WebhookURL != nil { q += comma(i, "webhook_url"); args = append(args, *p.WebhookURL); i++ }
|
||||
if p.ProviderConfigID != nil { q += comma(i, "provider_config_id"); args = append(args, *p.ProviderConfigID); i++ }
|
||||
if p.NotifyOnComplete != nil { q += comma(i, "notify_on_complete"); args = append(args, *p.NotifyOnComplete); i++ }
|
||||
if p.NotifyOnFailure != nil { q += comma(i, "notify_on_failure"); args = append(args, *p.NotifyOnFailure); i++ }
|
||||
|
||||
q += pgWhere(i, "id")
|
||||
args = append(args, id)
|
||||
_, err := DB.ExecContext(ctx, q, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) Delete(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `DELETE FROM tasks WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListByOwner(ctx context.Context, ownerID string) ([]models.Task, error) {
|
||||
return s.list(ctx, `WHERE owner_id = $1 ORDER BY created_at DESC`, ownerID)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListByTeam(ctx context.Context, teamID string) ([]models.Task, error) {
|
||||
return s.list(ctx, `WHERE team_id = $1 ORDER BY created_at DESC`, teamID)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListAll(ctx context.Context) ([]models.Task, error) {
|
||||
return s.list(ctx, `ORDER BY created_at DESC`)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ClaimDueTask(ctx context.Context) (*models.Task, error) {
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx, `
|
||||
UPDATE tasks SET next_run_at = NULL
|
||||
WHERE id = (
|
||||
SELECT id FROM tasks
|
||||
WHERE is_active = true AND next_run_at <= NOW()
|
||||
ORDER BY next_run_at ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING `+taskColumns)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// ── Scheduler bookkeeping ──────────────────────
|
||||
|
||||
func (s *TaskStore) SetNextRun(ctx context.Context, id string, nextRun interface{}) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET next_run_at = $1, updated_at = NOW() WHERE id = $2`, nextRun, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) SetLastRun(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET last_run_at = NOW(), updated_at = NOW() WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) IncrementRunCount(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET run_count = run_count + 1, updated_at = NOW() WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ── Run History ─────────────────────────────────
|
||||
|
||||
func (s *TaskStore) CreateRun(ctx context.Context, r *models.TaskRun) error {
|
||||
triggerPayload := nilIfEmpty(r.TriggerPayload)
|
||||
return DB.QueryRowContext(ctx, `
|
||||
INSERT INTO task_runs (task_id, channel_id, status, trigger_payload)
|
||||
VALUES ($1, $2, $3, $4) RETURNING id, started_at`,
|
||||
r.TaskID, r.ChannelID, r.Status, triggerPayload,
|
||||
).Scan(&r.ID, &r.StartedAt)
|
||||
}
|
||||
|
||||
func (s *TaskStore) CreateRunExclusive(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
r := &models.TaskRun{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
INSERT INTO task_runs (task_id, status)
|
||||
SELECT $1, 'running'
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM task_runs
|
||||
WHERE task_id = $1 AND status IN ('running', 'queued')
|
||||
)
|
||||
RETURNING id, started_at`, taskID,
|
||||
).Scan(&r.ID, &r.StartedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.TaskID = taskID
|
||||
r.Status = "running"
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) UpdateRun(ctx context.Context, id, status string, tokensUsed, toolCalls, wallClock int, errMsg string) error {
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
UPDATE task_runs SET status = $1, tokens_used = $2, tool_calls = $3,
|
||||
wall_clock = $4, error = $5, completed_at = NOW()
|
||||
WHERE id = $6`, status, tokensUsed, toolCalls, wallClock, errMsg, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) TransitionRunStatus(ctx context.Context, id string, status string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE task_runs SET status = $1 WHERE id = $2`, status, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetActiveRun(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
r := &models.TaskRun{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''), started_at
|
||||
FROM task_runs WHERE task_id = $1 AND status = 'running'
|
||||
LIMIT 1`, taskID,
|
||||
).Scan(&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload, &r.StartedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetQueuedRun(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
r := &models.TaskRun{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''), started_at
|
||||
FROM task_runs WHERE task_id = $1 AND status = 'queued'
|
||||
ORDER BY started_at ASC LIMIT 1`, taskID,
|
||||
).Scan(&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload, &r.StartedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListRuns(ctx context.Context, taskID string, limit int) ([]models.TaskRun, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''),
|
||||
started_at, completed_at, tokens_used, tool_calls, wall_clock,
|
||||
COALESCE(error, '')
|
||||
FROM task_runs WHERE task_id = $1
|
||||
ORDER BY started_at DESC LIMIT $2`, taskID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var runs []models.TaskRun
|
||||
for rows.Next() {
|
||||
var r models.TaskRun
|
||||
if err := rows.Scan(&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload,
|
||||
&r.StartedAt, &r.CompletedAt, &r.TokensUsed, &r.ToolCalls, &r.WallClock,
|
||||
&r.Error); err != nil {
|
||||
continue
|
||||
}
|
||||
runs = append(runs, r)
|
||||
}
|
||||
return runs, nil
|
||||
}
|
||||
|
||||
// ── list helper (single source of truth for SELECT + Scan) ─────
|
||||
|
||||
func (s *TaskStore) list(ctx context.Context, where string, args ...interface{}) ([]models.Task, error) {
|
||||
q := `SELECT ` + taskColumns + ` FROM tasks ` + where
|
||||
|
||||
rows, err := DB.QueryContext(ctx, q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var tasks []models.Task
|
||||
for rows.Next() {
|
||||
var t models.Task
|
||||
if err := scanTask(rows, &t); err != nil {
|
||||
continue
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
return tasks, nil
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────
|
||||
|
||||
// comma builds ", column = $N"
|
||||
func comma(i int, col string) string {
|
||||
return ", " + col + " = " + pgArg(i)
|
||||
}
|
||||
|
||||
// pgArg returns "$N"
|
||||
func pgArg(i int) string {
|
||||
return fmt.Sprintf("$%d", i)
|
||||
}
|
||||
|
||||
// pgWhere returns " WHERE col = $N"
|
||||
func pgWhere(i int, col string) string {
|
||||
return " WHERE " + col + " = " + pgArg(i)
|
||||
}
|
||||
|
||||
// nilIfEmpty returns nil for empty strings (prevents empty-string vs NULL issues).
|
||||
func nilIfEmpty(s string) interface{} {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -220,7 +220,7 @@ func (s *WorkflowStore) CreateStage(ctx context.Context, st *models.WorkflowStag
|
||||
transRules := jsonOrEmpty(st.TransitionRules)
|
||||
stageMode := st.StageMode
|
||||
if stageMode == "" {
|
||||
stageMode = models.StageModeChatOnly
|
||||
stageMode = models.StageModeCustom
|
||||
}
|
||||
return DB.QueryRowContext(ctx, `
|
||||
INSERT INTO workflow_stages (workflow_id, ordinal, name, persona_id, assignment_team_id,
|
||||
@@ -267,7 +267,7 @@ func (s *WorkflowStore) UpdateStage(ctx context.Context, st *models.WorkflowStag
|
||||
transRules := jsonOrEmpty(st.TransitionRules)
|
||||
stageMode := st.StageMode
|
||||
if stageMode == "" {
|
||||
stageMode = models.StageModeChatOnly
|
||||
stageMode = models.StageModeCustom
|
||||
}
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_stages
|
||||
@@ -377,207 +377,6 @@ func nullIfEmpty(s string) interface{} {
|
||||
|
||||
// ── Assignments (v0.29.0-cs3) ───────────────────────────────────────────
|
||||
|
||||
func (s *WorkflowStore) CreateAssignment(ctx context.Context, a *store.WorkflowAssignment) error {
|
||||
a.ID = store.NewID()
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO workflow_assignments (id, channel_id, stage, team_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`, a.ID, a.ChannelID, a.Stage, a.TeamID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ListAssignmentsForTeam(ctx context.Context, teamID, status string) ([]store.WorkflowAssignment, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, channel_id, stage, team_id, assigned_to, status,
|
||||
created_at, claimed_at, completed_at
|
||||
FROM workflow_assignments
|
||||
WHERE team_id = $1 AND status = $2
|
||||
ORDER BY created_at DESC
|
||||
`, teamID, status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ListAssignmentsMine(ctx context.Context, userID string) ([]store.WorkflowAssignment, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT DISTINCT wa.id, wa.channel_id, wa.stage, wa.team_id, wa.assigned_to, wa.status,
|
||||
wa.created_at, wa.claimed_at, wa.completed_at
|
||||
FROM workflow_assignments wa
|
||||
LEFT JOIN team_members tm ON tm.team_id = wa.team_id AND tm.user_id = $1
|
||||
WHERE (wa.assigned_to = $2 AND wa.status = 'claimed')
|
||||
OR (wa.status = 'unassigned' AND tm.user_id IS NOT NULL)
|
||||
ORDER BY wa.created_at DESC
|
||||
`, userID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ClaimAssignment(ctx context.Context, assignmentID, userID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = $1, status = 'claimed', claimed_at = $2
|
||||
WHERE id = $3 AND status = 'unassigned'
|
||||
`, userID, time.Now().UTC(), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) CompleteAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'completed', completed_at = $1
|
||||
WHERE id = $2 AND status = 'claimed'
|
||||
`, time.Now().UTC(), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) GetAssignmentChannelID(ctx context.Context, assignmentID string) (string, error) {
|
||||
var channelID string
|
||||
err := DB.QueryRowContext(ctx,
|
||||
`SELECT channel_id FROM workflow_assignments WHERE id = $1`, assignmentID).Scan(&channelID)
|
||||
return channelID, err
|
||||
}
|
||||
|
||||
// ── Lifecycle operations (v0.37.15) ──
|
||||
|
||||
func (s *WorkflowStore) CancelAssignmentsForChannel(ctx context.Context, channelID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'cancelled'
|
||||
WHERE channel_id = $1 AND status IN ('unassigned', 'claimed')
|
||||
`, channelID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) UnclaimAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'unassigned', assigned_to = NULL, claimed_at = NULL
|
||||
WHERE id = $1 AND status = 'claimed'
|
||||
`, assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ReassignAssignment(ctx context.Context, assignmentID, newUserID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = $1, claimed_at = $2
|
||||
WHERE id = $3 AND status = 'claimed'
|
||||
`, newUserID, time.Now().UTC(), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) CancelAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'cancelled'
|
||||
WHERE id = $1 AND status IN ('unassigned', 'claimed')
|
||||
`, assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) TryRoundRobin(ctx context.Context, teamID, assignmentID string) (string, error) {
|
||||
// Find least-recently-assigned team member
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT m.user_id, COALESCE(MAX(wa.claimed_at), '1970-01-01T00:00:00Z') as last_claim
|
||||
FROM team_members m
|
||||
LEFT JOIN workflow_assignments wa ON wa.assigned_to = m.user_id AND wa.team_id = $1
|
||||
WHERE m.team_id = $2
|
||||
GROUP BY m.user_id
|
||||
ORDER BY last_claim ASC
|
||||
LIMIT 1
|
||||
`, teamID, teamID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return "", nil // no team members
|
||||
}
|
||||
var userID, lastClaim string
|
||||
if err := rows.Scan(&userID, &lastClaim); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Claim for that user
|
||||
_, err = DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = $1, status = 'claimed', claimed_at = $2
|
||||
WHERE id = $3 AND status = 'unassigned'
|
||||
`, userID, time.Now().UTC(), assignmentID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func scanAssignments(rows *sql.Rows) ([]store.WorkflowAssignment, error) {
|
||||
var result []store.WorkflowAssignment
|
||||
for rows.Next() {
|
||||
var a store.WorkflowAssignment
|
||||
if err := rows.Scan(&a.ID, &a.ChannelID, &a.Stage, &a.TeamID,
|
||||
&a.AssignedTo, &a.Status, &a.CreatedAt, &a.ClaimedAt, &a.CompletedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
if result == nil {
|
||||
result = []store.WorkflowAssignment{}
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// ── Review Comments (v0.35.0) ───────────────────────────
|
||||
|
||||
func (s *WorkflowStore) GetAssignmentByID(ctx context.Context, id string) (*store.WorkflowAssignment, error) {
|
||||
var a store.WorkflowAssignment
|
||||
var rc []byte
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, channel_id, stage, team_id, assigned_to, status,
|
||||
review_comments, created_at, claimed_at, completed_at
|
||||
FROM workflow_assignments WHERE id = $1
|
||||
`, id).Scan(&a.ID, &a.ChannelID, &a.Stage, &a.TeamID, &a.AssignedTo, &a.Status,
|
||||
&rc, &a.CreatedAt, &a.ClaimedAt, &a.CompletedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.ReviewComments = rc
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) AddReviewComment(ctx context.Context, assignmentID string, comment store.ReviewComment) error {
|
||||
commentJSON, err := json.Marshal(comment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET review_comments = review_comments || $1::jsonb
|
||||
WHERE id = $2
|
||||
`, "["+string(commentJSON)+"]", assignmentID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2,188 +2,42 @@ package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"switchboard-core/models"
|
||||
"switchboard-core/store"
|
||||
"switchboard-core/database"
|
||||
)
|
||||
|
||||
// ── HealthStore ─────────────────────────────
|
||||
|
||||
type HealthStore struct{}
|
||||
|
||||
func NewHealthStore() *HealthStore { return &HealthStore{} }
|
||||
|
||||
func (s *HealthStore) UpsertWindow(ctx context.Context, w *models.ProviderHealthWindow) error {
|
||||
id := store.NewID()
|
||||
windowStr := w.WindowStart.Format(timeFmt)
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO provider_health (id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT (provider_config_id, window_start) DO UPDATE SET
|
||||
request_count = provider_health.request_count + excluded.request_count,
|
||||
error_count = provider_health.error_count + excluded.error_count,
|
||||
timeout_count = provider_health.timeout_count + excluded.timeout_count,
|
||||
rate_limit_count = provider_health.rate_limit_count + excluded.rate_limit_count,
|
||||
total_latency_ms = provider_health.total_latency_ms + excluded.total_latency_ms,
|
||||
max_latency_ms = MAX(provider_health.max_latency_ms, excluded.max_latency_ms),
|
||||
last_error = COALESCE(excluded.last_error, provider_health.last_error),
|
||||
last_error_at = COALESCE(excluded.last_error_at, provider_health.last_error_at),
|
||||
updated_at = datetime('now')
|
||||
`, id, w.ProviderConfigID, windowStr,
|
||||
w.RequestCount, w.ErrorCount, w.TimeoutCount, w.RateLimitCount,
|
||||
w.TotalLatencyMs, w.MaxLatencyMs, w.LastError, w.LastErrorAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *HealthStore) GetCurrentWindow(ctx context.Context, providerConfigID string) (*models.ProviderHealthWindow, error) {
|
||||
windowStr := time.Now().UTC().Truncate(time.Hour).Format(timeFmt)
|
||||
var w models.ProviderHealthWindow
|
||||
var windowStartStr string
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE provider_config_id = ? AND window_start = ?
|
||||
`, providerConfigID, windowStr).Scan(
|
||||
&w.ID, &w.ProviderConfigID, &windowStartStr,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TimeoutCount, &w.RateLimitCount,
|
||||
&w.TotalLatencyMs, &w.MaxLatencyMs, &w.LastError, &w.LastErrorAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.WindowStart, _ = time.Parse(timeFmt, windowStartStr)
|
||||
return &w, nil
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListWindows(ctx context.Context, providerConfigID string, hours int) ([]models.ProviderHealthWindow, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE provider_config_id = ?
|
||||
ORDER BY window_start DESC
|
||||
LIMIT ?
|
||||
`, providerConfigID, hours)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanHealthRows(rows)
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListAllCurrent(ctx context.Context) ([]models.ProviderHealthWindow, error) {
|
||||
windowStr := time.Now().UTC().Truncate(time.Hour).Format(timeFmt)
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, provider_config_id, window_start,
|
||||
request_count, error_count, timeout_count, rate_limit_count,
|
||||
total_latency_ms, max_latency_ms, last_error, last_error_at
|
||||
FROM provider_health
|
||||
WHERE window_start = ?
|
||||
ORDER BY provider_config_id
|
||||
`, windowStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanHealthRows(rows)
|
||||
}
|
||||
|
||||
// Prune deletes stale kernel data older than the given time.
|
||||
func (s *HealthStore) Prune(ctx context.Context, before time.Time) (int64, error) {
|
||||
result, err := DB.ExecContext(ctx, `
|
||||
DELETE FROM provider_health WHERE window_start < ?
|
||||
`, before.Format(timeFmt))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
var total int64
|
||||
ts := before.UTC().Format("2006-01-02 15:04:05")
|
||||
|
||||
res, _ := database.DB.ExecContext(ctx,
|
||||
`DELETE FROM ws_tickets WHERE expires_at < ?`, ts)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
DB.ExecContext(ctx, `DELETE FROM tool_health WHERE window_start < ?`, before.Format(timeFmt))
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
// ── Tool Health (v0.22.4) ────────────────────
|
||||
|
||||
func (s *HealthStore) UpsertToolWindow(ctx context.Context, w *models.ToolHealthWindow) error {
|
||||
id := store.NewID()
|
||||
windowStr := w.WindowStart.Format(timeFmt)
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO tool_health (id, tool_name, window_start,
|
||||
request_count, error_count, total_latency_ms, max_latency_ms,
|
||||
last_error, last_error_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT (tool_name, window_start) DO UPDATE SET
|
||||
request_count = tool_health.request_count + excluded.request_count,
|
||||
error_count = tool_health.error_count + excluded.error_count,
|
||||
total_latency_ms = tool_health.total_latency_ms + excluded.total_latency_ms,
|
||||
max_latency_ms = MAX(tool_health.max_latency_ms, excluded.max_latency_ms),
|
||||
last_error = COALESCE(excluded.last_error, tool_health.last_error),
|
||||
last_error_at = COALESCE(excluded.last_error_at, tool_health.last_error_at),
|
||||
updated_at = datetime('now')
|
||||
`, id, w.ToolName, windowStr,
|
||||
w.RequestCount, w.ErrorCount, w.TotalLatencyMs, w.MaxLatencyMs,
|
||||
w.LastError, w.LastErrorAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *HealthStore) ListAllToolCurrent(ctx context.Context) ([]models.ToolHealthWindow, error) {
|
||||
windowStr := time.Now().UTC().Truncate(time.Hour).Format(timeFmt)
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, tool_name, window_start,
|
||||
request_count, error_count, total_latency_ms, max_latency_ms,
|
||||
last_error, last_error_at
|
||||
FROM tool_health
|
||||
WHERE window_start = ?
|
||||
ORDER BY tool_name
|
||||
`, windowStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
res, _ = database.DB.ExecContext(ctx,
|
||||
`DELETE FROM rate_limit_counters WHERE window_start < ?`, ts)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.ToolHealthWindow
|
||||
for rows.Next() {
|
||||
var w models.ToolHealthWindow
|
||||
var windowStartStr string
|
||||
if err := rows.Scan(
|
||||
&w.ID, &w.ToolName, &windowStartStr,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TotalLatencyMs, &w.MaxLatencyMs,
|
||||
&w.LastError, &w.LastErrorAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.WindowStart, _ = time.Parse(timeFmt, windowStartStr)
|
||||
result = append(result, w)
|
||||
res, _ = database.DB.ExecContext(ctx,
|
||||
`DELETE FROM user_presence WHERE last_seen < ? AND status = 'offline'`, ts)
|
||||
if res != nil {
|
||||
n, _ := res.RowsAffected()
|
||||
total += n
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *HealthStore) DeactivateProvider(ctx context.Context, configID string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE provider_configs SET is_active = 0 WHERE id = ?`, configID)
|
||||
return err
|
||||
}
|
||||
|
||||
func scanHealthRows(rows *sql.Rows) ([]models.ProviderHealthWindow, error) {
|
||||
var result []models.ProviderHealthWindow
|
||||
for rows.Next() {
|
||||
var w models.ProviderHealthWindow
|
||||
var windowStartStr string
|
||||
if err := rows.Scan(
|
||||
&w.ID, &w.ProviderConfigID, &windowStartStr,
|
||||
&w.RequestCount, &w.ErrorCount, &w.TimeoutCount, &w.RateLimitCount,
|
||||
&w.TotalLatencyMs, &w.MaxLatencyMs, &w.LastError, &w.LastErrorAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.WindowStart, _ = time.Parse(timeFmt, windowStartStr)
|
||||
result = append(result, w)
|
||||
}
|
||||
return result, rows.Err()
|
||||
return total, nil
|
||||
}
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"switchboard-core/models"
|
||||
"switchboard-core/store"
|
||||
)
|
||||
|
||||
// ── SessionStore ───────────────────────────
|
||||
|
||||
type SessionStore struct{}
|
||||
|
||||
func NewSessionStore() *SessionStore { return &SessionStore{} }
|
||||
|
||||
func (s *SessionStore) Create(ctx context.Context, sp *models.SessionParticipant) error {
|
||||
if sp.ID == "" {
|
||||
sp.ID = store.NewID()
|
||||
}
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO session_participants (id, session_token, channel_id, display_name, fingerprint)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
sp.ID, sp.SessionToken, sp.ChannelID, sp.DisplayName, nullText(sp.Fingerprint),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return DB.QueryRowContext(ctx, `SELECT created_at FROM session_participants WHERE id = ?`, sp.ID).
|
||||
Scan(st(&sp.CreatedAt))
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByToken(ctx context.Context, token string) (*models.SessionParticipant, error) {
|
||||
sp := &models.SessionParticipant{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE session_token = ?`, token,
|
||||
).Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, st(&sp.CreatedAt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) GetByID(ctx context.Context, id string) (*models.SessionParticipant, error) {
|
||||
sp := &models.SessionParticipant{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE id = ?`, id,
|
||||
).Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, st(&sp.CreatedAt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
func (s *SessionStore) ListForChannel(ctx context.Context, channelID string) ([]models.SessionParticipant, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, session_token, channel_id, display_name, COALESCE(fingerprint, ''), created_at
|
||||
FROM session_participants WHERE channel_id = ?
|
||||
ORDER BY created_at ASC`, channelID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.SessionParticipant
|
||||
for rows.Next() {
|
||||
var sp models.SessionParticipant
|
||||
if err := rows.Scan(&sp.ID, &sp.SessionToken, &sp.ChannelID, &sp.DisplayName, &sp.Fingerprint, st(&sp.CreatedAt)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, sp)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *SessionStore) CountForChannel(ctx context.Context, channelID string) (int, error) {
|
||||
var count int
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM session_participants WHERE channel_id = ?`, channelID,
|
||||
).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (s *SessionStore) Delete(ctx context.Context, id string) error {
|
||||
res, err := DB.ExecContext(ctx, `DELETE FROM session_participants WHERE id = ?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if n == 0 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteExpired removes sessions created before olderThan whose channel
|
||||
// has no messages. Returns the count of deleted rows.
|
||||
func (s *SessionStore) DeleteExpired(ctx context.Context, olderThan time.Time) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
DELETE FROM session_participants
|
||||
WHERE created_at < ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM messages WHERE messages.channel_id = session_participants.channel_id
|
||||
)`, olderThan)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func nullText(s string) interface{} {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -19,14 +19,12 @@ func NewStores(db *sql.DB) store.Stores {
|
||||
ResourceGrants: NewResourceGrantStore(),
|
||||
Notifications: NewNotificationStore(),
|
||||
NotifPrefs: NewNotificationPreferenceStore(),
|
||||
Sessions: NewSessionStore(),
|
||||
Presence: NewPresenceStore(),
|
||||
Health: NewHealthStore(),
|
||||
Connections: NewConnectionStore(),
|
||||
Dependencies: NewDependencyStore(),
|
||||
Packages: NewPackageStore(),
|
||||
Workflows: NewWorkflowStore(),
|
||||
Tasks: NewTaskStore(),
|
||||
ExtPermissions: NewExtensionPermissionStore(),
|
||||
ExtData: NewExtDataStore(),
|
||||
Tickets: NewTicketStore(),
|
||||
|
||||
@@ -1,362 +0,0 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"switchboard-core/models"
|
||||
"switchboard-core/store"
|
||||
)
|
||||
|
||||
type TaskStore struct{}
|
||||
|
||||
func NewTaskStore() *TaskStore { return &TaskStore{} }
|
||||
|
||||
// ── Full column list (single source of truth) ──────────────────
|
||||
|
||||
// taskColumns is the canonical SELECT list for tasks.
|
||||
// COALESCE wraps nullable columns that scan into non-pointer Go types.
|
||||
// tool_grants uses COALESCE to '[]' so the string intermediate never sees NULL.
|
||||
const taskColumns = `id, owner_id, team_id, name, description, scope,
|
||||
task_type, COALESCE(system_function, '') AS system_function,
|
||||
persona_id, model_id, system_prompt, user_prompt,
|
||||
workflow_id, COALESCE(tool_grants, '[]') AS tool_grants,
|
||||
schedule, timezone, is_active,
|
||||
COALESCE(trigger_token, '') AS trigger_token,
|
||||
max_tokens, max_tool_calls, max_wall_clock, output_mode,
|
||||
output_channel_id,
|
||||
COALESCE(webhook_url, '') AS webhook_url,
|
||||
COALESCE(webhook_secret, '') AS webhook_secret,
|
||||
provider_config_id,
|
||||
notify_on_complete, notify_on_failure,
|
||||
last_run_at, next_run_at, run_count, created_at, updated_at`
|
||||
|
||||
// scanTask scans a full task row into the model.
|
||||
//
|
||||
// SQLite dialect issues handled here:
|
||||
// - tool_grants: modernc driver returns TEXT as Go string, not []byte.
|
||||
// json.RawMessage (named []byte) can't accept string via convertAssign.
|
||||
// Scan into string intermediate, then cast.
|
||||
// - is_active, notify_on_complete, notify_on_failure: stored as INTEGER
|
||||
// (0/1). modernc returns int64, but convertAssign can't assign int64
|
||||
// to *bool. Scan into int intermediate, then convert.
|
||||
//
|
||||
// These match the patterns in store/sqlite/workflows.go.
|
||||
func scanTask(scanner interface{ Scan(...interface{}) error }, t *models.Task) error {
|
||||
var toolGrantsStr string
|
||||
var isActive, notifyComplete, notifyFailure int
|
||||
err := scanner.Scan(
|
||||
&t.ID, &t.OwnerID, &t.TeamID, &t.Name, &t.Description, &t.Scope,
|
||||
&t.TaskType, &t.SystemFunction,
|
||||
&t.PersonaID, &t.ModelID, &t.SystemPrompt, &t.UserPrompt,
|
||||
&t.WorkflowID, &toolGrantsStr, &t.Schedule, &t.Timezone, &isActive,
|
||||
&t.TriggerToken,
|
||||
&t.MaxTokens, &t.MaxToolCalls, &t.MaxWallClock, &t.OutputMode,
|
||||
&t.OutputChannelID, &t.WebhookURL, &t.WebhookSecret, &t.ProviderConfigID,
|
||||
¬ifyComplete, ¬ifyFailure,
|
||||
stN(&t.LastRunAt), stN(&t.NextRunAt), &t.RunCount, st(&t.CreatedAt), st(&t.UpdatedAt),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.ToolGrants = json.RawMessage(toolGrantsStr)
|
||||
t.IsActive = isActive != 0
|
||||
t.NotifyOnComplete = notifyComplete != 0
|
||||
t.NotifyOnFailure = notifyFailure != 0
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── CRUD ───────────────────────────────────────
|
||||
|
||||
func (s *TaskStore) Create(ctx context.Context, t *models.Task) error {
|
||||
t.ID = store.NewID()
|
||||
now := time.Now().UTC()
|
||||
t.CreatedAt = now
|
||||
t.UpdatedAt = now
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO tasks (id, owner_id, team_id, name, description, scope,
|
||||
task_type, system_function,
|
||||
persona_id, model_id, system_prompt, user_prompt,
|
||||
workflow_id, tool_grants, schedule, timezone, is_active,
|
||||
trigger_token,
|
||||
max_tokens, max_tool_calls, max_wall_clock, output_mode,
|
||||
output_channel_id, webhook_url, webhook_secret, provider_config_id,
|
||||
notify_on_complete, notify_on_failure, next_run_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
t.ID, t.OwnerID, t.TeamID, t.Name, t.Description, t.Scope,
|
||||
t.TaskType, t.SystemFunction,
|
||||
t.PersonaID, t.ModelID, t.SystemPrompt, t.UserPrompt,
|
||||
t.WorkflowID, nullableJSON(t.ToolGrants), t.Schedule, t.Timezone, boolToInt(t.IsActive),
|
||||
nilIfEmpty(t.TriggerToken),
|
||||
t.MaxTokens, t.MaxToolCalls, t.MaxWallClock, t.OutputMode,
|
||||
t.OutputChannelID, t.WebhookURL, t.WebhookSecret, t.ProviderConfigID,
|
||||
boolToInt(t.NotifyOnComplete), boolToInt(t.NotifyOnFailure), timeToSQLite(t.NextRunAt))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetByID(ctx context.Context, id string) (*models.Task, error) {
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx, `SELECT `+taskColumns+` FROM tasks WHERE id = ?`, id)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetByTriggerToken(ctx context.Context, token string) (*models.Task, error) {
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx, `SELECT `+taskColumns+` FROM tasks WHERE trigger_token = ?`, token)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) Update(ctx context.Context, id string, p models.TaskPatch) error {
|
||||
q := "UPDATE tasks SET updated_at = datetime('now')"
|
||||
args := []interface{}{}
|
||||
if p.Name != nil { q += ", name = ?"; args = append(args, *p.Name) }
|
||||
if p.Description != nil { q += ", description = ?"; args = append(args, *p.Description) }
|
||||
if p.PersonaID != nil { q += ", persona_id = ?"; args = append(args, *p.PersonaID) }
|
||||
if p.ModelID != nil { q += ", model_id = ?"; args = append(args, *p.ModelID) }
|
||||
if p.SystemPrompt != nil { q += ", system_prompt = ?"; args = append(args, *p.SystemPrompt) }
|
||||
if p.UserPrompt != nil { q += ", user_prompt = ?"; args = append(args, *p.UserPrompt) }
|
||||
if p.WorkflowID != nil { q += ", workflow_id = ?"; args = append(args, *p.WorkflowID) }
|
||||
if p.ToolGrants != nil { q += ", tool_grants = ?"; args = append(args, nullableJSON(*p.ToolGrants)) }
|
||||
if p.Schedule != nil { q += ", schedule = ?"; args = append(args, *p.Schedule) }
|
||||
if p.Timezone != nil { q += ", timezone = ?"; args = append(args, *p.Timezone) }
|
||||
if p.IsActive != nil { q += ", is_active = ?"; args = append(args, boolToInt(*p.IsActive)) }
|
||||
if p.MaxTokens != nil { q += ", max_tokens = ?"; args = append(args, *p.MaxTokens) }
|
||||
if p.MaxToolCalls != nil { q += ", max_tool_calls = ?"; args = append(args, *p.MaxToolCalls) }
|
||||
if p.MaxWallClock != nil { q += ", max_wall_clock = ?"; args = append(args, *p.MaxWallClock) }
|
||||
if p.OutputMode != nil { q += ", output_mode = ?"; args = append(args, *p.OutputMode) }
|
||||
if p.OutputChannelID != nil { q += ", output_channel_id = ?"; args = append(args, *p.OutputChannelID) }
|
||||
if p.WebhookURL != nil { q += ", webhook_url = ?"; args = append(args, *p.WebhookURL) }
|
||||
if p.ProviderConfigID != nil { q += ", provider_config_id = ?"; args = append(args, *p.ProviderConfigID) }
|
||||
if p.NotifyOnComplete != nil { q += ", notify_on_complete = ?"; args = append(args, boolToInt(*p.NotifyOnComplete)) }
|
||||
if p.NotifyOnFailure != nil { q += ", notify_on_failure = ?"; args = append(args, boolToInt(*p.NotifyOnFailure)) }
|
||||
q += " WHERE id = ?"
|
||||
args = append(args, id)
|
||||
_, err := DB.ExecContext(ctx, q, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) Delete(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `DELETE FROM tasks WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListByOwner(ctx context.Context, ownerID string) ([]models.Task, error) {
|
||||
return s.list(ctx, `WHERE owner_id = ? ORDER BY created_at DESC`, ownerID)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListByTeam(ctx context.Context, teamID string) ([]models.Task, error) {
|
||||
return s.list(ctx, `WHERE team_id = ? ORDER BY created_at DESC`, teamID)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListAll(ctx context.Context) ([]models.Task, error) {
|
||||
return s.list(ctx, `ORDER BY created_at DESC`)
|
||||
}
|
||||
|
||||
func (s *TaskStore) ClaimDueTask(ctx context.Context) (*models.Task, error) {
|
||||
// SQLite: single-process, no contention. Select the oldest due task,
|
||||
// then atomically clear next_run_at to mark it claimed.
|
||||
t := &models.Task{}
|
||||
row := DB.QueryRowContext(ctx,
|
||||
`SELECT `+taskColumns+` FROM tasks
|
||||
WHERE is_active = 1 AND next_run_at <= datetime('now')
|
||||
ORDER BY next_run_at ASC LIMIT 1`)
|
||||
if err := scanTask(row, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, _ = DB.ExecContext(ctx,
|
||||
`UPDATE tasks SET next_run_at = NULL WHERE id = ?`, t.ID)
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// ── Scheduler bookkeeping ──────────────────────
|
||||
|
||||
func (s *TaskStore) SetNextRun(ctx context.Context, id string, nextRun interface{}) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET next_run_at = ?, updated_at = datetime('now') WHERE id = ?`, timeToSQLiteAny(nextRun), id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) SetLastRun(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET last_run_at = datetime('now'), updated_at = datetime('now') WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) IncrementRunCount(ctx context.Context, id string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE tasks SET run_count = run_count + 1, updated_at = datetime('now') WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ── Run History ─────────────────────────────────
|
||||
|
||||
func (s *TaskStore) CreateRun(ctx context.Context, r *models.TaskRun) error {
|
||||
r.ID = store.NewID()
|
||||
// F4 audit fix: set StartedAt in Go so the returned struct matches PG
|
||||
// behavior (PG returns it via RETURNING; SQLite can't).
|
||||
r.StartedAt = time.Now().UTC()
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO task_runs (id, task_id, channel_id, status, trigger_payload, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, r.ID, r.TaskID, r.ChannelID, r.Status,
|
||||
nilIfEmpty(r.TriggerPayload), r.StartedAt.UTC().Format("2006-01-02 15:04:05"))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) CreateRunExclusive(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
// SQLite: check-then-insert. Single-process, no race.
|
||||
var count int
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM task_runs
|
||||
WHERE task_id = ? AND status IN ('running', 'queued')`, taskID).Scan(&count)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count > 0 {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
r := &models.TaskRun{
|
||||
ID: store.NewID(),
|
||||
TaskID: taskID,
|
||||
Status: "running",
|
||||
StartedAt: time.Now().UTC(),
|
||||
}
|
||||
_, err = DB.ExecContext(ctx, `
|
||||
INSERT INTO task_runs (id, task_id, status, started_at)
|
||||
VALUES (?, ?, 'running', ?)`,
|
||||
r.ID, taskID, r.StartedAt.UTC().Format("2006-01-02 15:04:05"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) UpdateRun(ctx context.Context, id, status string, tokensUsed, toolCalls, wallClock int, errMsg string) error {
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
UPDATE task_runs SET status = ?, tokens_used = ?, tool_calls = ?,
|
||||
wall_clock = ?, error = ?, completed_at = datetime('now')
|
||||
WHERE id = ?`, status, tokensUsed, toolCalls, wallClock, errMsg, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) TransitionRunStatus(ctx context.Context, id string, status string) error {
|
||||
_, err := DB.ExecContext(ctx, `UPDATE task_runs SET status = ? WHERE id = ?`, status, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetActiveRun(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
r := &models.TaskRun{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''), started_at
|
||||
FROM task_runs WHERE task_id = ? AND status = 'running'
|
||||
LIMIT 1`, taskID).Scan(&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload, st(&r.StartedAt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) GetQueuedRun(ctx context.Context, taskID string) (*models.TaskRun, error) {
|
||||
r := &models.TaskRun{}
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''), started_at
|
||||
FROM task_runs WHERE task_id = ? AND status = 'queued'
|
||||
ORDER BY started_at ASC LIMIT 1`, taskID).Scan(
|
||||
&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload, st(&r.StartedAt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (s *TaskStore) ListRuns(ctx context.Context, taskID string, limit int) ([]models.TaskRun, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, task_id, channel_id, status, COALESCE(trigger_payload, ''),
|
||||
started_at, completed_at, tokens_used, tool_calls, wall_clock,
|
||||
COALESCE(error, '')
|
||||
FROM task_runs WHERE task_id = ?
|
||||
ORDER BY started_at DESC LIMIT ?`, taskID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var runs []models.TaskRun
|
||||
for rows.Next() {
|
||||
var r models.TaskRun
|
||||
if err := rows.Scan(&r.ID, &r.TaskID, &r.ChannelID, &r.Status, &r.TriggerPayload,
|
||||
st(&r.StartedAt), stN(&r.CompletedAt),
|
||||
&r.TokensUsed, &r.ToolCalls, &r.WallClock, &r.Error); err != nil {
|
||||
continue
|
||||
}
|
||||
runs = append(runs, r)
|
||||
}
|
||||
return runs, nil
|
||||
}
|
||||
|
||||
// ── list helper ────────────────────────────────
|
||||
|
||||
func (s *TaskStore) list(ctx context.Context, where string, args ...interface{}) ([]models.Task, error) {
|
||||
q := `SELECT ` + taskColumns + ` FROM tasks ` + where
|
||||
|
||||
rows, err := DB.QueryContext(ctx, q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var tasks []models.Task
|
||||
for rows.Next() {
|
||||
var t models.Task
|
||||
if err := scanTask(rows, &t); err != nil {
|
||||
continue
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
return tasks, nil
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────
|
||||
|
||||
func nullableJSON(data []byte) interface{} {
|
||||
if len(data) == 0 || string(data) == "null" {
|
||||
return nil
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func nilIfEmpty(s string) interface{} {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// timeToSQLite converts *time.Time to the TEXT format that datetime('now')
|
||||
// produces ("2006-01-02 15:04:05"). Returns nil for nil input.
|
||||
// This prevents the modernc driver from serializing time.Time in an
|
||||
// unparseable format (int64 / RFC3339Nano / driver-specific).
|
||||
func timeToSQLite(t *time.Time) interface{} {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
return t.UTC().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
// timeToSQLiteAny handles interface{} that may be *time.Time, time.Time, or nil.
|
||||
func timeToSQLiteAny(v interface{}) interface{} {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
switch t := v.(type) {
|
||||
case *time.Time:
|
||||
return timeToSQLite(t)
|
||||
case time.Time:
|
||||
return t.UTC().Format("2006-01-02 15:04:05")
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,7 @@ func (s *WorkflowStore) CreateStage(ctx context.Context, st *models.WorkflowStag
|
||||
transRules := jsonOrEmpty(st.TransitionRules)
|
||||
stageMode := st.StageMode
|
||||
if stageMode == "" {
|
||||
stageMode = models.StageModeChatOnly
|
||||
stageMode = models.StageModeCustom
|
||||
}
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO workflow_stages (id, workflow_id, ordinal, name, persona_id, assignment_team_id,
|
||||
@@ -203,7 +203,7 @@ func (s *WorkflowStore) UpdateStage(ctx context.Context, st *models.WorkflowStag
|
||||
transRules := jsonOrEmpty(st.TransitionRules)
|
||||
stageMode := st.StageMode
|
||||
if stageMode == "" {
|
||||
stageMode = models.StageModeChatOnly
|
||||
stageMode = models.StageModeCustom
|
||||
}
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_stages
|
||||
@@ -380,218 +380,6 @@ func nullIfEmpty(s string) interface{} {
|
||||
|
||||
// ── Assignments (v0.29.0-cs3) ───────────────────────────────────────────
|
||||
|
||||
func (s *WorkflowStore) CreateAssignment(ctx context.Context, a *store.WorkflowAssignment) error {
|
||||
a.ID = store.NewID()
|
||||
_, err := DB.ExecContext(ctx, `
|
||||
INSERT INTO workflow_assignments (id, channel_id, stage, team_id)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, a.ID, a.ChannelID, a.Stage, a.TeamID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ListAssignmentsForTeam(ctx context.Context, teamID, status string) ([]store.WorkflowAssignment, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT id, channel_id, stage, team_id, assigned_to, status,
|
||||
created_at, claimed_at, completed_at
|
||||
FROM workflow_assignments
|
||||
WHERE team_id = ? AND status = ?
|
||||
ORDER BY created_at DESC
|
||||
`, teamID, status)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ListAssignmentsMine(ctx context.Context, userID string) ([]store.WorkflowAssignment, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT DISTINCT wa.id, wa.channel_id, wa.stage, wa.team_id, wa.assigned_to, wa.status,
|
||||
wa.created_at, wa.claimed_at, wa.completed_at
|
||||
FROM workflow_assignments wa
|
||||
LEFT JOIN team_members tm ON tm.team_id = wa.team_id AND tm.user_id = ?
|
||||
WHERE (wa.assigned_to = ? AND wa.status = 'claimed')
|
||||
OR (wa.status = 'unassigned' AND tm.user_id IS NOT NULL)
|
||||
ORDER BY wa.created_at DESC
|
||||
`, userID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanAssignments(rows)
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ClaimAssignment(ctx context.Context, assignmentID, userID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = ?, status = 'claimed', claimed_at = ?
|
||||
WHERE id = ? AND status = 'unassigned'
|
||||
`, userID, time.Now().UTC().Format(timeFmt), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) CompleteAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'completed', completed_at = ?
|
||||
WHERE id = ? AND status = 'claimed'
|
||||
`, time.Now().UTC().Format(timeFmt), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) GetAssignmentChannelID(ctx context.Context, assignmentID string) (string, error) {
|
||||
var channelID string
|
||||
err := DB.QueryRowContext(ctx,
|
||||
`SELECT channel_id FROM workflow_assignments WHERE id = ?`, assignmentID).Scan(&channelID)
|
||||
return channelID, err
|
||||
}
|
||||
|
||||
// ── Lifecycle operations (v0.37.15) ──
|
||||
|
||||
func (s *WorkflowStore) CancelAssignmentsForChannel(ctx context.Context, channelID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'cancelled'
|
||||
WHERE channel_id = ? AND status IN ('unassigned', 'claimed')
|
||||
`, channelID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) UnclaimAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'unassigned', assigned_to = NULL, claimed_at = NULL
|
||||
WHERE id = ? AND status = 'claimed'
|
||||
`, assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) ReassignAssignment(ctx context.Context, assignmentID, newUserID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = ?, claimed_at = ?
|
||||
WHERE id = ? AND status = 'claimed'
|
||||
`, newUserID, time.Now().UTC().Format(timeFmt), assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) CancelAssignment(ctx context.Context, assignmentID string) (int64, error) {
|
||||
res, err := DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET status = 'cancelled'
|
||||
WHERE id = ? AND status IN ('unassigned', 'claimed')
|
||||
`, assignmentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) TryRoundRobin(ctx context.Context, teamID, assignmentID string) (string, error) {
|
||||
rows, err := DB.QueryContext(ctx, `
|
||||
SELECT m.user_id, COALESCE(MAX(wa.claimed_at), '1970-01-01 00:00:00') as last_claim
|
||||
FROM team_members m
|
||||
LEFT JOIN workflow_assignments wa ON wa.assigned_to = m.user_id AND wa.team_id = ?
|
||||
WHERE m.team_id = ?
|
||||
GROUP BY m.user_id
|
||||
ORDER BY last_claim ASC
|
||||
LIMIT 1
|
||||
`, teamID, teamID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
if !rows.Next() {
|
||||
return "", nil
|
||||
}
|
||||
var userID, lastClaim string
|
||||
if err := rows.Scan(&userID, &lastClaim); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
_, err = DB.ExecContext(ctx, `
|
||||
UPDATE workflow_assignments
|
||||
SET assigned_to = ?, status = 'claimed', claimed_at = ?
|
||||
WHERE id = ? AND status = 'unassigned'
|
||||
`, userID, time.Now().UTC().Format(timeFmt), assignmentID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func scanAssignments(rows *sql.Rows) ([]store.WorkflowAssignment, error) {
|
||||
var result []store.WorkflowAssignment
|
||||
for rows.Next() {
|
||||
var a store.WorkflowAssignment
|
||||
var claimedAt, completedAt *time.Time
|
||||
if err := rows.Scan(&a.ID, &a.ChannelID, &a.Stage, &a.TeamID,
|
||||
&a.AssignedTo, &a.Status, st(&a.CreatedAt), stN(&claimedAt), stN(&completedAt)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.ClaimedAt = claimedAt
|
||||
a.CompletedAt = completedAt
|
||||
result = append(result, a)
|
||||
}
|
||||
if result == nil {
|
||||
result = []store.WorkflowAssignment{}
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// ── Review Comments (v0.35.0) ───────────────────────────
|
||||
|
||||
func (s *WorkflowStore) GetAssignmentByID(ctx context.Context, id string) (*store.WorkflowAssignment, error) {
|
||||
var a store.WorkflowAssignment
|
||||
var rc string
|
||||
var claimedAt, completedAt *time.Time
|
||||
err := DB.QueryRowContext(ctx, `
|
||||
SELECT id, channel_id, stage, team_id, assigned_to, status,
|
||||
COALESCE(review_comments, '[]'), created_at, claimed_at, completed_at
|
||||
FROM workflow_assignments WHERE id = ?
|
||||
`, id).Scan(&a.ID, &a.ChannelID, &a.Stage, &a.TeamID, &a.AssignedTo, &a.Status,
|
||||
&rc, st(&a.CreatedAt), stN(&claimedAt), stN(&completedAt))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.ReviewComments = json.RawMessage(rc)
|
||||
a.ClaimedAt = claimedAt
|
||||
a.CompletedAt = completedAt
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *WorkflowStore) AddReviewComment(ctx context.Context, assignmentID string, comment store.ReviewComment) error {
|
||||
commentJSON, err := json.Marshal(comment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// SQLite: read, append, write back
|
||||
var existing string
|
||||
err = DB.QueryRowContext(ctx, `SELECT COALESCE(review_comments, '[]') FROM workflow_assignments WHERE id = ?`, assignmentID).Scan(&existing)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var arr []json.RawMessage
|
||||
_ = json.Unmarshal([]byte(existing), &arr)
|
||||
arr = append(arr, json.RawMessage(commentJSON))
|
||||
updated, _ := json.Marshal(arr)
|
||||
_, err = DB.ExecContext(ctx, `UPDATE workflow_assignments SET review_comments = ? WHERE id = ?`, string(updated), assignmentID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"switchboard-core/models"
|
||||
)
|
||||
|
||||
// TaskStore manages task definitions and run history.
|
||||
type TaskStore interface {
|
||||
// Task CRUD
|
||||
Create(ctx context.Context, t *models.Task) error
|
||||
GetByID(ctx context.Context, id string) (*models.Task, error)
|
||||
Update(ctx context.Context, id string, patch models.TaskPatch) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
ListByOwner(ctx context.Context, ownerID string) ([]models.Task, error)
|
||||
ListByTeam(ctx context.Context, teamID string) ([]models.Task, error)
|
||||
ListAll(ctx context.Context) ([]models.Task, error)
|
||||
|
||||
// Trigger lookup (inbound webhooks)
|
||||
GetByTriggerToken(ctx context.Context, token string) (*models.Task, error)
|
||||
|
||||
// Scheduler queries
|
||||
ClaimDueTask(ctx context.Context) (*models.Task, error)
|
||||
SetNextRun(ctx context.Context, id string, nextRun interface{}) error
|
||||
SetLastRun(ctx context.Context, id string) error
|
||||
IncrementRunCount(ctx context.Context, id string) error
|
||||
|
||||
// Run history
|
||||
CreateRun(ctx context.Context, r *models.TaskRun) error
|
||||
CreateRunExclusive(ctx context.Context, taskID string) (*models.TaskRun, error)
|
||||
UpdateRun(ctx context.Context, id string, status string, tokensUsed, toolCalls, wallClock int, errMsg string) error
|
||||
TransitionRunStatus(ctx context.Context, id string, status string) error
|
||||
GetActiveRun(ctx context.Context, taskID string) (*models.TaskRun, error)
|
||||
GetQueuedRun(ctx context.Context, taskID string) (*models.TaskRun, error)
|
||||
ListRuns(ctx context.Context, taskID string, limit int) ([]models.TaskRun, error)
|
||||
}
|
||||
@@ -28,62 +28,4 @@ type WorkflowStore interface {
|
||||
Publish(ctx context.Context, v *models.WorkflowVersion) error
|
||||
GetVersion(ctx context.Context, workflowID string, versionNumber int) (*models.WorkflowVersion, error)
|
||||
GetLatestVersion(ctx context.Context, workflowID string) (*models.WorkflowVersion, error)
|
||||
|
||||
// ── Assignments (v0.29.0-cs3) ──
|
||||
|
||||
// CreateAssignment inserts a workflow_assignments row.
|
||||
CreateAssignment(ctx context.Context, a *WorkflowAssignment) error
|
||||
|
||||
// ListAssignmentsForTeam returns assignments for a team filtered by status.
|
||||
ListAssignmentsForTeam(ctx context.Context, teamID, status string) ([]WorkflowAssignment, error)
|
||||
|
||||
// ListAssignmentsMine returns claimed + unassigned assignments visible to a user.
|
||||
ListAssignmentsMine(ctx context.Context, userID string) ([]WorkflowAssignment, error)
|
||||
|
||||
// ClaimAssignment sets assigned_to and status='claimed' on an unassigned row.
|
||||
// Returns rows affected (0 = already claimed or not found).
|
||||
ClaimAssignment(ctx context.Context, assignmentID, userID string) (int64, error)
|
||||
|
||||
// CompleteAssignment sets status='completed' on a claimed row.
|
||||
// Returns rows affected (0 = not claimed or not found).
|
||||
CompleteAssignment(ctx context.Context, assignmentID string) (int64, error)
|
||||
|
||||
// GetAssignmentChannelID returns the channel_id for an assignment.
|
||||
GetAssignmentChannelID(ctx context.Context, assignmentID string) (string, error)
|
||||
|
||||
// TryRoundRobin finds the least-recently-assigned team member and claims.
|
||||
// Returns the assigned user ID, or "" if no members available.
|
||||
TryRoundRobin(ctx context.Context, teamID, assignmentID string) (string, error)
|
||||
|
||||
// ── Lifecycle operations (v0.37.15) ──
|
||||
|
||||
// CancelAssignmentsForChannel sets status='cancelled' on all
|
||||
// unassigned/claimed assignments for a channel.
|
||||
CancelAssignmentsForChannel(ctx context.Context, channelID string) (int64, error)
|
||||
|
||||
// UnclaimAssignment returns a claimed assignment to unassigned.
|
||||
// Returns rows affected (0 = not claimed or not found).
|
||||
UnclaimAssignment(ctx context.Context, assignmentID string) (int64, error)
|
||||
|
||||
// ReassignAssignment changes assigned_to on a claimed assignment.
|
||||
// Returns rows affected.
|
||||
ReassignAssignment(ctx context.Context, assignmentID, newUserID string) (int64, error)
|
||||
|
||||
// CancelAssignment sets a single assignment to cancelled.
|
||||
CancelAssignment(ctx context.Context, assignmentID string) (int64, error)
|
||||
|
||||
// ── Review Comments (v0.35.0) ──
|
||||
|
||||
// GetAssignmentByID returns a single assignment by ID.
|
||||
GetAssignmentByID(ctx context.Context, id string) (*WorkflowAssignment, error)
|
||||
|
||||
// AddReviewComment appends a comment to an assignment's review_comments array.
|
||||
AddReviewComment(ctx context.Context, assignmentID string, comment ReviewComment) error
|
||||
}
|
||||
|
||||
// ReviewComment is a single review comment on a workflow assignment (v0.35.0).
|
||||
type ReviewComment struct {
|
||||
Text string `json:"text"`
|
||||
UserID string `json:"user_id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WorkflowChannelStatus holds the workflow state columns from the channels table.
|
||||
type WorkflowChannelStatus struct {
|
||||
WorkflowID *string `json:"workflow_id"`
|
||||
WorkflowVersion *int `json:"workflow_version"`
|
||||
CurrentStage int `json:"current_stage"`
|
||||
StageData json.RawMessage `json:"stage_data"`
|
||||
Status string `json:"status"`
|
||||
LastActivityAt *string `json:"last_activity_at"`
|
||||
StageEnteredAt *string `json:"stage_entered_at,omitempty"`
|
||||
}
|
||||
|
||||
// WorkflowAssignment is a row from the workflow_assignments table.
|
||||
type WorkflowAssignment struct {
|
||||
ID string `json:"id"`
|
||||
ChannelID string `json:"channel_id"`
|
||||
Stage int `json:"stage"`
|
||||
TeamID string `json:"team_id"`
|
||||
AssignedTo *string `json:"assigned_to"`
|
||||
Status string `json:"status"`
|
||||
ReviewComments json.RawMessage `json:"review_comments"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ClaimedAt *time.Time `json:"claimed_at"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
}
|
||||
Reference in New Issue
Block a user