feat: Phase 2D — orchestrator, arguments/verdict endpoints, fabric announce
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).
This commit is contained in:
62
internal/store/argument_store.go
Normal file
62
internal/store/argument_store.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
|
||||
)
|
||||
|
||||
type Argument struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
TopicID string `db:"topic_id" json:"topic_id"`
|
||||
RoundID string `db:"round_id" json:"round_id"`
|
||||
Camp models.Camp `db:"camp" json:"camp"`
|
||||
AgentID string `db:"agent_id" json:"agent_id"`
|
||||
Content string `db:"content" json:"content"`
|
||||
PostedAt time.Time `db:"posted_at" json:"posted_at"`
|
||||
}
|
||||
|
||||
type ArgumentStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewArgumentStore(db *sqlx.DB) *ArgumentStore { return &ArgumentStore{db: db} }
|
||||
|
||||
type PostArgumentInput struct {
|
||||
TopicID string
|
||||
RoundID string
|
||||
Camp models.Camp
|
||||
AgentID string
|
||||
Content string
|
||||
}
|
||||
|
||||
func (s *ArgumentStore) Post(ctx context.Context, in PostArgumentInput) (*Argument, error) {
|
||||
id := uuid.NewString()
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO arguments (id, topic_id, round_id, camp, agent_id, content)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
id, in.TopicID, in.RoundID, in.Camp, in.AgentID, in.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var a Argument
|
||||
if err := s.db.GetContext(ctx, &a, `SELECT * FROM arguments WHERE id = ?`, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// ListByTopic returns the full transcript in posted order. Used by the
|
||||
// judge agent at end-of-debate to write the verdict, by the frontend
|
||||
// to render, and by observer agents querying via plugin.
|
||||
func (s *ArgumentStore) ListByTopic(ctx context.Context, topicID string) ([]Argument, error) {
|
||||
var rows []Argument
|
||||
if err := s.db.SelectContext(ctx, &rows,
|
||||
`SELECT * FROM arguments WHERE topic_id = ? ORDER BY posted_at ASC, id ASC`, topicID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
66
internal/store/camp_store.go
Normal file
66
internal/store/camp_store.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
|
||||
)
|
||||
|
||||
type Camp struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
TopicID string `db:"topic_id" json:"topic_id"`
|
||||
Camp models.Camp `db:"camp" json:"camp"`
|
||||
AgentID string `db:"agent_id" json:"agent_id"`
|
||||
AllocatedAt time.Time `db:"allocated_at" json:"allocated_at"`
|
||||
}
|
||||
|
||||
type CampStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewCampStore(db *sqlx.DB) *CampStore { return &CampStore{db: db} }
|
||||
|
||||
// WriteAllocation inserts all 3 camp rows for a topic atomically. Must
|
||||
// be called within a tx the orchestrator owns (so signup_close transition
|
||||
// + camps insert + status update are all-or-nothing). Receives an open
|
||||
// *sqlx.Tx, returns nothing on success.
|
||||
func (s *CampStore) WriteAllocation(ctx context.Context, tx *sqlx.Tx, topicID string, alloc map[models.Camp]string) error {
|
||||
for _, c := range models.AllCamps {
|
||||
agentID, ok := alloc[c]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO camps (id, topic_id, camp, agent_id) VALUES (?, ?, ?, ?)`,
|
||||
uuid.NewString(), topicID, c, agentID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CampStore) ListByTopic(ctx context.Context, topicID string) ([]Camp, error) {
|
||||
var rows []Camp
|
||||
if err := s.db.SelectContext(ctx, &rows,
|
||||
`SELECT * FROM camps WHERE topic_id = ? ORDER BY allocated_at ASC`, topicID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// AgentCampInTopic returns the camp `agentID` was allocated to, or empty
|
||||
// if the agent isn't in any camp on this topic. Used by argument/verdict
|
||||
// handlers to enforce "only camp members can post".
|
||||
func (s *CampStore) AgentCampInTopic(ctx context.Context, topicID, agentID string) (models.Camp, error) {
|
||||
var camp models.Camp
|
||||
err := s.db.GetContext(ctx, &camp,
|
||||
`SELECT camp FROM camps WHERE topic_id = ? AND agent_id = ? LIMIT 1`, topicID, agentID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return camp, nil
|
||||
}
|
||||
65
internal/store/round_store.go
Normal file
65
internal/store/round_store.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Round struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
TopicID string `db:"topic_id" json:"topic_id"`
|
||||
RoundNo int `db:"round_no" json:"round_no"`
|
||||
OpenedAt time.Time `db:"opened_at" json:"opened_at"`
|
||||
ClosedAt *time.Time `db:"closed_at" json:"closed_at,omitempty"`
|
||||
}
|
||||
|
||||
type RoundStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewRoundStore(db *sqlx.DB) *RoundStore { return &RoundStore{db: db} }
|
||||
|
||||
// Open creates the round-0 row for a topic entering `debating`. Subsequent
|
||||
// rounds (1, 2, ...) are inserted by the round driver as the debate
|
||||
// advances; we leave round-bumping logic outside the store so the policy
|
||||
// (time-based? all-participants-posted?) can evolve without DB churn.
|
||||
func (s *RoundStore) Open(ctx context.Context, topicID string, roundNo int) (*Round, error) {
|
||||
id := uuid.NewString()
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO rounds (id, topic_id, round_no) VALUES (?, ?, ?)`,
|
||||
id, topicID, roundNo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r Round
|
||||
if err := s.db.GetContext(ctx, &r, `SELECT * FROM rounds WHERE id = ?`, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
func (s *RoundStore) Latest(ctx context.Context, topicID string) (*Round, error) {
|
||||
var r Round
|
||||
err := s.db.GetContext(ctx, &r,
|
||||
`SELECT * FROM rounds WHERE topic_id = ? ORDER BY round_no DESC LIMIT 1`, topicID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
func (s *RoundStore) ListByTopic(ctx context.Context, topicID string) ([]Round, error) {
|
||||
var rows []Round
|
||||
if err := s.db.SelectContext(ctx, &rows,
|
||||
`SELECT * FROM rounds WHERE topic_id = ? ORDER BY round_no ASC`, topicID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
@@ -94,6 +94,17 @@ func (s *TopicStore) List(ctx context.Context, f ListFilter) ([]models.Topic, er
|
||||
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, `
|
||||
|
||||
63
internal/store/verdict_store.go
Normal file
63
internal/store/verdict_store.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
type Verdict struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
TopicID string `db:"topic_id" json:"topic_id"`
|
||||
JudgeAgentID string `db:"judge_agent_id" json:"judge_agent_id"`
|
||||
VerdictJSON []byte `db:"verdict_json" json:"-"` // surface raw via Render
|
||||
Rationale string `db:"rationale" json:"rationale"`
|
||||
TokensInput int `db:"tokens_input" json:"tokens_input"`
|
||||
TokensOutput int `db:"tokens_output" json:"tokens_output"`
|
||||
ProducedAt time.Time `db:"produced_at" json:"produced_at"`
|
||||
}
|
||||
|
||||
type VerdictStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewVerdictStore(db *sqlx.DB) *VerdictStore { return &VerdictStore{db: db} }
|
||||
|
||||
type SubmitVerdictInput struct {
|
||||
TopicID string
|
||||
JudgeAgentID string
|
||||
VerdictJSON []byte
|
||||
Rationale string
|
||||
TokensInput int
|
||||
TokensOutput int
|
||||
}
|
||||
|
||||
// Submit writes the (one-and-only) verdict for a topic. Unique constraint
|
||||
// on topic_id means a second submission returns a duplicate-key error;
|
||||
// caller surfaces that as 409.
|
||||
func (s *VerdictStore) Submit(ctx context.Context, in SubmitVerdictInput) (*Verdict, error) {
|
||||
id := uuid.NewString()
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO verdicts (id, topic_id, judge_agent_id, verdict_json, rationale, tokens_input, tokens_output)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
id, in.TopicID, in.JudgeAgentID, in.VerdictJSON, in.Rationale, in.TokensInput, in.TokensOutput); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetByTopic(ctx, in.TopicID)
|
||||
}
|
||||
|
||||
func (s *VerdictStore) GetByTopic(ctx context.Context, topicID string) (*Verdict, error) {
|
||||
var v Verdict
|
||||
err := s.db.GetContext(ctx, &v, `SELECT * FROM verdicts WHERE topic_id = ?`, topicID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
Reference in New Issue
Block a user