Files
Dialectic.Backend/internal/httpapi/handlers/arguments.go
hzhang 57a1fa1b33 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).
2026-05-23 12:02:27 +01:00

134 lines
4.0 KiB
Go

package handlers
import (
"encoding/json"
"errors"
"net/http"
"github.com/go-chi/chi/v5"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/auth"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/store"
)
type ArgumentsHandler struct {
topics *store.TopicStore
camps *store.CampStore
rounds *store.RoundStore
arguments *store.ArgumentStore
}
func NewArgumentsHandler(
t *store.TopicStore,
c *store.CampStore,
r *store.RoundStore,
a *store.ArgumentStore,
) *ArgumentsHandler {
return &ArgumentsHandler{topics: t, camps: c, rounds: r, arguments: a}
}
type postArgumentBody struct {
Content string `json:"content"`
}
// POST /api/topics/{id}/arguments
//
// Agent-only. Caller must be allocated to one of the topic's camps;
// rejected otherwise. Topic must be `debating` (status state machine
// enforces; argument outside that window is meaningless). Content is
// stored as-is (no markdown rendering server-side; frontend renders).
//
// Round: argument is attached to the LATEST open round. Round-advance
// policy is the orchestrator's call (Phase 2D ships with manual/single
// round 0; round bumping logic comes when the rule is decided).
func (h *ArgumentsHandler) Post(w http.ResponseWriter, r *http.Request) {
caller := auth.FromContext(r.Context())
if caller.Kind != auth.CallerAgent {
http.Error(w, "argument posting is agent-only", http.StatusForbidden)
return
}
topicID := chi.URLParam(r, "id")
topic, err := h.topics.GetByID(r.Context(), topicID)
if errors.Is(err, store.ErrNotFound) {
http.Error(w, "topic not found", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "lookup failed", http.StatusInternalServerError)
return
}
if topic.Status != models.TopicStatusDebating {
http.Error(w, "topic not in debate window (status="+string(topic.Status)+")", http.StatusConflict)
return
}
camp, err := h.camps.AgentCampInTopic(r.Context(), topicID, caller.ID)
if err != nil {
http.Error(w, "you are not allocated to any camp on this topic", http.StatusForbidden)
return
}
round, err := h.rounds.Latest(r.Context(), topicID)
if err != nil {
http.Error(w, "no open round (orchestrator hasn't opened round 0 yet?)", http.StatusConflict)
return
}
var body postArgumentBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
if body.Content == "" {
http.Error(w, "content required", http.StatusBadRequest)
return
}
const maxContent = 32_000 // arbitrary upper bound; arguments shouldn't be book-length
if len(body.Content) > maxContent {
http.Error(w, "content too long", http.StatusRequestEntityTooLarge)
return
}
arg, err := h.arguments.Post(r.Context(), store.PostArgumentInput{
TopicID: topicID,
RoundID: round.ID,
Camp: camp,
AgentID: caller.ID,
Content: body.Content,
})
if err != nil {
http.Error(w, "post failed: "+err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusCreated, arg)
}
// GET /api/topics/{id}/arguments — full transcript in posted order.
// Visibility: anonymous can read for public topics; private requires
// any-auth (enforced upstream by middleware composition).
func (h *ArgumentsHandler) List(w http.ResponseWriter, r *http.Request) {
topicID := chi.URLParam(r, "id")
topic, err := h.topics.GetByID(r.Context(), topicID)
if errors.Is(err, store.ErrNotFound) {
http.Error(w, "topic not found", http.StatusNotFound)
return
}
if err != nil {
http.Error(w, "lookup failed", http.StatusInternalServerError)
return
}
caller := auth.FromContext(r.Context())
if caller.Kind == "" && topic.Visibility != models.VisibilityPublic {
http.Error(w, "not found", http.StatusNotFound)
return
}
rows, err := h.arguments.ListByTopic(r.Context(), topicID)
if err != nil {
http.Error(w, "list failed", http.StatusInternalServerError)
return
}
writeJSON(w, http.StatusOK, map[string]any{"arguments": rows, "count": len(rows)})
}