State machine driver + camp allocator + judge-submitted verdicts +
broadcast hook to Fabric announce channel.
internal/orchestrator/
- allocator.go: pure function implementing the 3-camp rule from the
2026-05-23 design session — for each camp (pro/con/judge), random
pick from volunteers; backfill unfilled camps from remaining
unallocated signups if pool is large enough; <3 final → cancel
with diagnostic reason. rng injected for test determinism.
- allocator_test.go: 7 tests covering empty/insufficient/single-volunteer
/multi-volunteer-no-dup/backfill/insufficient-backfill/large-pool
distinctness invariants. All pass.
- ticker.go: scans every 15s (configurable via ORCHESTRATOR_TICK_INTERVAL),
drives 3 state transitions atomically:
created → signup_open (post fabric announcement async)
signup_open → signup_closed | cancelled (run allocator, write camps)
signup_closed → debating (open round 0)
debating → completed is driven by the verdict POST handler (the
implicit "judging" sub-state is captured by the gate
status==debating AND now>=debate_end_at). Per-topic transitions
use SELECT FOR UPDATE so concurrent ticker instances are safe.
internal/fabric/announce.go: HTTP client posting to a Guild announce
channel using x-fabric-system-key header (the Phase 1 gate). Wraps
the formatted topic announcement (title/summary/timing/schema). All
4 config fields required to enable; any missing → no-op with log
(orchestrator runs fine without Fabric coupling for dev).
internal/store/{round,camp,argument,verdict}_store.go: CRUD layer
for the remaining v2 entities. CampStore.WriteAllocation accepts a
tx so the orchestrator can wrap allocator+camps+status into one
atomic transition.
internal/httpapi/handlers/arguments.go:
- POST /api/topics/{id}/arguments — agent posts during debate. Gates:
agent must be in a camp on this topic; status==debating; content
nonempty and <=32KB; attached to latest open round.
- GET /api/topics/{id}/arguments — full transcript, visibility-gated.
internal/httpapi/handlers/verdict.go:
- POST /api/topics/{id}/verdict — judge submits. Gates: caller==judge
camp; status==debating AND now>=debate_end_at; verdict valid JSON;
rationale required. On success: writes verdicts row (unique on
topic_id → 409 on dup) and flips topic.status to completed.
- GET /api/topics/{id}/verdict — visibility-gated.
config: 5 new env vars — FABRIC_GUILD_BASE_URL,
FABRIC_ANNOUNCE_CHANNEL_ID, FABRIC_SYSTEM_API_KEY,
FABRIC_BOT_BEARER_TOKEN, ORCHESTRATOR_TICK_INTERVAL.
routes.go: wired new handlers — POST signups/arguments/verdict gated
on agent bearer; GET arguments/verdict on optional-auth chain
(public topics readable anonymously).
main.go: instantiates announcer + ticker; ticker.Run in a goroutine
sharing the lifetime ctx.
go vet + gofmt clean; 7/7 allocator tests pass; 12M static binary.
Next: Phase 2E (deploy to t3 with nginx + CF origin cert) or
Phase 2D.5 (SSE stream for live transcript subscribers).
118 lines
3.3 KiB
Go
118 lines
3.3 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
|
|
)
|
|
|
|
var ErrNotFound = errors.New("not found")
|
|
|
|
type TopicStore struct {
|
|
db *sqlx.DB
|
|
}
|
|
|
|
func NewTopicStore(db *sqlx.DB) *TopicStore { return &TopicStore{db: db} }
|
|
|
|
type CreateTopicInput struct {
|
|
Title string
|
|
Summary string
|
|
Visibility models.Visibility
|
|
VerdictSchemaID string
|
|
SignupOpenAt string // RFC3339; parsed by SQL
|
|
SignupCloseAt string
|
|
DebateStartAt string
|
|
DebateEndAt string
|
|
CreatorUserID string
|
|
}
|
|
|
|
func (s *TopicStore) Create(ctx context.Context, in CreateTopicInput) (*models.Topic, error) {
|
|
id := uuid.NewString()
|
|
_, err := s.db.ExecContext(ctx, `
|
|
INSERT INTO topics (id, title, summary, visibility, verdict_schema_id,
|
|
signup_open_at, signup_close_at, debate_start_at, debate_end_at, creator_user_id)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
id, in.Title, in.Summary, in.Visibility, in.VerdictSchemaID,
|
|
in.SignupOpenAt, in.SignupCloseAt, in.DebateStartAt, in.DebateEndAt, in.CreatorUserID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("insert topic: %w", err)
|
|
}
|
|
return s.GetByID(ctx, id)
|
|
}
|
|
|
|
func (s *TopicStore) GetByID(ctx context.Context, id string) (*models.Topic, error) {
|
|
var t models.Topic
|
|
err := s.db.GetContext(ctx, &t, `SELECT * FROM topics WHERE id = ?`, id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &t, nil
|
|
}
|
|
|
|
type ListFilter struct {
|
|
Status string // empty = all
|
|
Visibility string // empty = all
|
|
Limit int // 0 = default 50
|
|
Offset int
|
|
}
|
|
|
|
func (s *TopicStore) List(ctx context.Context, f ListFilter) ([]models.Topic, error) {
|
|
if f.Limit <= 0 || f.Limit > 200 {
|
|
f.Limit = 50
|
|
}
|
|
q := "SELECT * FROM topics"
|
|
args := []any{}
|
|
var clauses []string
|
|
if f.Status != "" {
|
|
clauses = append(clauses, "status = ?")
|
|
args = append(args, f.Status)
|
|
}
|
|
if f.Visibility != "" {
|
|
clauses = append(clauses, "visibility = ?")
|
|
args = append(args, f.Visibility)
|
|
}
|
|
if len(clauses) > 0 {
|
|
q += " WHERE " + strings.Join(clauses, " AND ")
|
|
}
|
|
q += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
|
args = append(args, f.Limit, f.Offset)
|
|
|
|
var rows []models.Topic
|
|
if err := s.db.SelectContext(ctx, &rows, q, args...); err != nil {
|
|
return nil, err
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
// SetStatus is a low-level status update. Most transitions go through
|
|
// the orchestrator's tx-wrapped paths; this is for the verdict handler
|
|
// (debating → completed on successful judge submission) and admin tools.
|
|
func (s *TopicStore) SetStatus(ctx context.Context, id string, status models.TopicStatus) (*models.Topic, error) {
|
|
if _, err := s.db.ExecContext(ctx,
|
|
`UPDATE topics SET status = ? WHERE id = ?`, status, id); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.GetByID(ctx, id)
|
|
}
|
|
|
|
// SetVisibility flips public/private; records who/when. Returns updated row.
|
|
func (s *TopicStore) SetVisibility(ctx context.Context, id string, v models.Visibility, byUserID string) (*models.Topic, error) {
|
|
_, err := s.db.ExecContext(ctx, `
|
|
UPDATE topics SET visibility = ?, visibility_changed_by = ?, visibility_changed_at = CURRENT_TIMESTAMP
|
|
WHERE id = ?`, v, byUserID, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return s.GetByID(ctx, id)
|
|
}
|