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:
133
internal/httpapi/handlers/arguments.go
Normal file
133
internal/httpapi/handlers/arguments.go
Normal file
@@ -0,0 +1,133 @@
|
||||
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)})
|
||||
}
|
||||
165
internal/httpapi/handlers/verdict.go
Normal file
165
internal/httpapi/handlers/verdict.go
Normal file
@@ -0,0 +1,165 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"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 VerdictHandler struct {
|
||||
db *struct{} // placeholder; we don't use the raw conn directly here
|
||||
topics *store.TopicStore
|
||||
camps *store.CampStore
|
||||
verdicts *store.VerdictStore
|
||||
}
|
||||
|
||||
func NewVerdictHandler(t *store.TopicStore, c *store.CampStore, v *store.VerdictStore) *VerdictHandler {
|
||||
return &VerdictHandler{topics: t, camps: c, verdicts: v}
|
||||
}
|
||||
|
||||
type submitVerdictBody struct {
|
||||
Verdict json.RawMessage `json:"verdict"` // shape matches topic.verdict_schema_id
|
||||
Rationale string `json:"rationale"`
|
||||
TokensInput int `json:"tokens_input"`
|
||||
TokensOutput int `json:"tokens_output"`
|
||||
}
|
||||
|
||||
// POST /api/topics/{id}/verdict
|
||||
//
|
||||
// Judge-only. Caller must be allocated to the judge camp. Topic must be
|
||||
// in `debating` status AND past `debate_end_at` (the ticker doesn't
|
||||
// flip to `judging` in v1, see ticker.go note — the gate enforces the
|
||||
// time crossing instead).
|
||||
//
|
||||
// Schema validation (Phase 2D): shallow — confirm verdict is valid JSON
|
||||
// and not empty. Real schema-shape validation lands when we wire the
|
||||
// verdict_schemas.shape_json against a JSON-schema validator.
|
||||
func (h *VerdictHandler) Submit(w http.ResponseWriter, r *http.Request) {
|
||||
caller := auth.FromContext(r.Context())
|
||||
if caller.Kind != auth.CallerAgent {
|
||||
http.Error(w, "verdict submission 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 state (status="+string(topic.Status)+")", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if time.Now().Before(topic.DebateEndAt) {
|
||||
http.Error(w, "debate window still open; verdict premature", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
camp, err := h.camps.AgentCampInTopic(r.Context(), topicID, caller.ID)
|
||||
if err != nil || camp != models.CampJudge {
|
||||
http.Error(w, "only the judge can submit a verdict", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body submitVerdictBody
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "bad body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(body.Verdict) == 0 || string(body.Verdict) == "null" {
|
||||
http.Error(w, "verdict required (non-empty JSON object matching schema)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Sanity: ensure it parses as a JSON object/value.
|
||||
var probe any
|
||||
if err := json.Unmarshal(body.Verdict, &probe); err != nil {
|
||||
http.Error(w, "verdict must be valid JSON", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Rationale == "" {
|
||||
http.Error(w, "rationale required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
verdict, err := h.verdicts.Submit(r.Context(), store.SubmitVerdictInput{
|
||||
TopicID: topicID,
|
||||
JudgeAgentID: caller.ID,
|
||||
VerdictJSON: body.Verdict,
|
||||
Rationale: body.Rationale,
|
||||
TokensInput: body.TokensInput,
|
||||
TokensOutput: body.TokensOutput,
|
||||
})
|
||||
if err != nil {
|
||||
// Most likely cause: unique-key conflict (already submitted).
|
||||
http.Error(w, "submit failed: "+err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
|
||||
// Transition topic to completed. Best-effort; if it fails, the
|
||||
// verdict row exists and the ticker will retry on next scan
|
||||
// (well — once we add that transition; v1 leaves it to a manual
|
||||
// flip via SQL or a follow-up endpoint).
|
||||
if _, err := h.topics.SetStatus(r.Context(), topicID, models.TopicStatusCompleted); err != nil {
|
||||
// non-fatal: log via response header (caller can spot-check)
|
||||
w.Header().Set("x-warn", "verdict saved but status update failed: "+err.Error())
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"id": verdict.ID,
|
||||
"topic_id": verdict.TopicID,
|
||||
"judge_agent_id": verdict.JudgeAgentID,
|
||||
"verdict": json.RawMessage(verdict.VerdictJSON),
|
||||
"rationale": verdict.Rationale,
|
||||
"tokens_input": verdict.TokensInput,
|
||||
"tokens_output": verdict.TokensOutput,
|
||||
"produced_at": verdict.ProducedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/topics/{id}/verdict — fetch the published verdict (404 if
|
||||
// not yet produced). Visibility-gated like other read endpoints.
|
||||
func (h *VerdictHandler) Get(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
|
||||
}
|
||||
|
||||
verdict, err := h.verdicts.GetByTopic(r.Context(), topicID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
http.Error(w, "verdict not yet produced", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "lookup failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": verdict.ID,
|
||||
"topic_id": verdict.TopicID,
|
||||
"judge_agent_id": verdict.JudgeAgentID,
|
||||
"verdict": json.RawMessage(verdict.VerdictJSON),
|
||||
"rationale": verdict.Rationale,
|
||||
"produced_at": verdict.ProducedAt,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user