Files
Dialectic.Backend/internal/orchestrator/allocator.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

117 lines
3.8 KiB
Go

// Package orchestrator owns the topic lifecycle state machine:
// signup-window allocator, round driver, judge invocation, Fabric
// announce broadcaster. All long-running coordination logic lives
// here so handlers stay thin.
package orchestrator
import (
"math/rand"
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
)
// AllocateResult is the outcome of running the camp allocator on a
// topic's signup pool. Either Allocation is set (one agent per camp,
// no duplicates) or CancelReason is set (signup pool insufficient
// after backfill).
type AllocateResult struct {
Allocation map[models.Camp]string // camp → agentId
CancelReason string // non-empty when allocation could not complete
}
// Allocate runs the 3-camp self-enrollment allocation algorithm
// agreed on in the 2026-05-23 design session.
//
// for each camp in [pro, con, judge]:
// if any signup has that camp in willing_camps AND that agent
// isn't already locked → random pick, lock.
// if camps still unfilled AND remaining unallocated signups >= unfilled:
// random pick from remaining to fill, one each.
// if any camp still unfilled (i.e. signup pool < 3 effective):
// return CancelReason; creator re-times.
//
// Invariants: same agent never lands in two camps; allocation order
// respects [pro, con, judge] so the test seed produces deterministic
// results when rng is seeded.
//
// `rng` is injected so tests can supply a deterministic source. Pass
// `rand.New(rand.NewSource(time.Now().UnixNano()))` in prod.
func Allocate(signups []models.SignupView, rng *rand.Rand) AllocateResult {
allocated := make(map[models.Camp]string, 3)
used := make(map[string]struct{}, len(signups))
// Pass 1 — fill each camp from its volunteers.
for _, camp := range models.AllCamps {
candidates := make([]string, 0)
for _, s := range signups {
if _, taken := used[s.AgentID]; taken {
continue
}
for _, w := range s.WillingCamps {
if w == camp {
candidates = append(candidates, s.AgentID)
break
}
}
}
if len(candidates) == 0 {
continue
}
pick := candidates[rng.Intn(len(candidates))]
allocated[camp] = pick
used[pick] = struct{}{}
}
// Pass 2 — backfill unfilled camps from any remaining signup.
if len(allocated) < 3 {
remaining := make([]string, 0)
for _, s := range signups {
if _, taken := used[s.AgentID]; taken {
continue
}
remaining = append(remaining, s.AgentID)
}
// We can only fill if we have enough remaining for every still-empty camp.
unfilled := make([]models.Camp, 0, 3)
for _, c := range models.AllCamps {
if _, ok := allocated[c]; !ok {
unfilled = append(unfilled, c)
}
}
if len(remaining) >= len(unfilled) {
// Shuffle remaining, then take one per unfilled camp in order.
rng.Shuffle(len(remaining), func(i, j int) {
remaining[i], remaining[j] = remaining[j], remaining[i]
})
for i, c := range unfilled {
allocated[c] = remaining[i]
used[remaining[i]] = struct{}{}
}
}
}
// Verdict — all 3 filled or we cancel.
if len(allocated) < 3 {
filled := len(allocated)
return AllocateResult{
CancelReason: cancelReason(filled, len(signups)),
}
}
return AllocateResult{Allocation: allocated}
}
func cancelReason(filled, totalSignups int) string {
switch {
case totalSignups == 0:
return "no signups received"
case totalSignups < 3:
return "insufficient signups: need at least 3 distinct agents across pro/con/judge"
default:
// Edge case: pool >= 3 but allocator still couldn't fill — e.g.
// every signup volunteered for the same one camp and the same
// person was somehow used (shouldn't happen with current rules,
// but make the message honest).
return "allocation infeasible: signup distribution does not cover all 3 camps"
}
}