Files
Dialectic.Backend/main.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

94 lines
2.8 KiB
Go

// Dialectic.Backend.Go — entrypoint.
//
// Greenfield Go rewrite of the Python v1 backend; agent-only debate
// platform per /home/hzhang/arch/DIALECTIC-V2-DESIGN.md.
//
// This file: load config → open db → run migrations → mount routes →
// serve until SIGINT/SIGTERM. Everything else lives in internal/.
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/config"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/db"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/fabric"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/httpapi"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/orchestrator"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/store"
)
// Version is overridden at build time via -ldflags="-X main.Version=...".
var Version = "dev"
func main() {
log.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)
cfg, err := config.LoadFromEnv()
if err != nil {
log.Fatalf("config: %v", err)
}
log.Printf("starting dialectic-backend %s mode=%s addr=%s", Version, cfg.Mode, cfg.HTTPAddr)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conn, err := db.Open(ctx, cfg.DSN())
if err != nil {
log.Fatalf("db open: %v", err)
}
defer conn.Close()
if err := db.RunMigrations(ctx, conn); err != nil {
log.Fatalf("migrations: %v", err)
}
log.Printf("migrations: ok")
// Wire orchestrator + Fabric announcer + start the ticker.
announcer := fabric.NewAnnouncer(fabric.AnnounceConfig{
GuildBaseURL: cfg.FabricGuildBaseURL,
ChannelID: cfg.FabricAnnounceChannelID,
SystemAPIKey: cfg.FabricSystemAPIKey,
BotBearerToken: cfg.FabricBotBearerToken,
})
topicStore := store.NewTopicStore(conn)
signupStore := store.NewSignupStore(conn)
campStore := store.NewCampStore(conn)
roundStore := store.NewRoundStore(conn)
ticker := orchestrator.NewTicker(conn, topicStore, signupStore, campStore, roundStore,
announcer, cfg.OrchestratorTickInterval)
go ticker.Run(ctx)
srv := &http.Server{
Addr: cfg.HTTPAddr,
Handler: httpapi.Mount(cfg, conn, Version),
ReadHeaderTimeout: 10 * time.Second,
}
// Graceful shutdown on SIGINT/SIGTERM.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
go func() {
<-shutdown
log.Printf("shutdown signal received")
ctx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx2); err != nil {
log.Printf("http shutdown error: %v", err)
}
}()
log.Printf("http server listening on %s", cfg.HTTPAddr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("http serve: %v", err)
}
log.Printf("bye")
}