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

164 lines
5.2 KiB
Go

// Package config loads runtime configuration from environment variables.
//
// Conventions:
// - 12-factor: every config knob is an env var; no config files.
// - Sensible dev defaults for local docker-compose; prod sets via env.
// - Sensitive values (DB password, system api key) are *required* in
// prod; LoadFromEnv() fails fast if absent and ENV_MODE != "dev".
package config
import (
"fmt"
"os"
"strings"
"time"
)
type Config struct {
// "dev" | "prod". Dev relaxes required-field checks and enables a
// dev-mode auth bypass token. Prod requires every sensitive field.
Mode string
// HTTP server bind. e.g. "0.0.0.0:8090".
HTTPAddr string
// CORS allowed origins (comma-separated; "*" allowed only in dev).
CORSAllowOrigins []string
// MySQL DSN parts.
DBHost string
DBPort string
DBName string
DBUser string
DBPassword string
// Auth.
//
// SystemAPIKey: Phase-1 system key for posting to announce channels
// in Fabric. Mirrored here so Dialectic backend itself can post topic
// announcements via Fabric's POST /channels/:id/messages with
// x-fabric-system-key header.
//
// AgentAPIKeyPepper: HMAC pepper for hashing agent API keys at rest
// (we store sha256(pepper || raw) not the raw key). Rotating the
// pepper invalidates all keys — that's intentional, an emergency
// kill switch.
//
// OIDCDevBypassToken: dev-mode only. If set AND Mode == "dev", a
// browser request with header `x-dev-bypass: <token>` bypasses OIDC
// and is treated as user "dev-operator" with role "dialectic-admin".
// Prod ignores this even if set.
SystemAPIKey string
AgentAPIKeyPepper string
OIDCDevBypassToken string
// OIDC issuer URL (Keycloak realm endpoint). e.g.
// https://auth.hangman-lab.top/realms/hangman-lab
// Phase 2C ships this as configured-but-not-verified; Phase 4 wires
// real JWKS validation.
OIDCIssuer string
OIDCClientID string
// Fabric announce coupling (Phase 2D). All four required to enable;
// any empty → announcer becomes a no-op (logs intent, skips post).
// This lets the orchestrator run in environments where the Fabric
// coupling hasn't been wired yet.
FabricGuildBaseURL string // e.g. https://fabric-api.hangman-lab.top
FabricAnnounceChannelID string
FabricSystemAPIKey string // x-fabric-system-key value (env: FABRIC_SYSTEM_API_KEY)
FabricBotBearerToken string // Authorization Bearer for the dialectic-system Fabric user
// Orchestrator tick interval. 0 / unset → default 15s.
OrchestratorTickInterval time.Duration
}
func LoadFromEnv() (*Config, error) {
c := &Config{
Mode: getenv("ENV_MODE", "dev"),
HTTPAddr: getenv("HTTP_ADDR", "0.0.0.0:8090"),
CORSAllowOrigins: splitCSV(getenv("CORS_ALLOW_ORIGINS", "*")),
DBHost: getenv("DB_HOST", "127.0.0.1"),
DBPort: getenv("DB_PORT", "3306"),
DBName: getenv("DB_NAME", "dialectic"),
DBUser: getenv("DB_USER", "dialectic"),
DBPassword: os.Getenv("DB_PASSWORD"),
SystemAPIKey: os.Getenv("SYSTEM_API_KEY"),
AgentAPIKeyPepper: os.Getenv("AGENT_API_KEY_PEPPER"),
OIDCDevBypassToken: os.Getenv("OIDC_DEV_BYPASS_TOKEN"),
OIDCIssuer: os.Getenv("OIDC_ISSUER"),
OIDCClientID: os.Getenv("OIDC_CLIENT_ID"),
FabricGuildBaseURL: os.Getenv("FABRIC_GUILD_BASE_URL"),
FabricAnnounceChannelID: os.Getenv("FABRIC_ANNOUNCE_CHANNEL_ID"),
FabricSystemAPIKey: os.Getenv("FABRIC_SYSTEM_API_KEY"),
FabricBotBearerToken: os.Getenv("FABRIC_BOT_BEARER_TOKEN"),
}
if d := os.Getenv("ORCHESTRATOR_TICK_INTERVAL"); d != "" {
if parsed, err := time.ParseDuration(d); err == nil {
c.OrchestratorTickInterval = parsed
}
}
if c.Mode != "dev" && c.Mode != "prod" {
return nil, fmt.Errorf("ENV_MODE must be dev|prod, got %q", c.Mode)
}
if c.Mode == "prod" {
var missing []string
if c.DBPassword == "" {
missing = append(missing, "DB_PASSWORD")
}
if c.AgentAPIKeyPepper == "" {
missing = append(missing, "AGENT_API_KEY_PEPPER")
}
if c.OIDCIssuer == "" {
missing = append(missing, "OIDC_ISSUER")
}
if c.OIDCClientID == "" {
missing = append(missing, "OIDC_CLIENT_ID")
}
if len(missing) > 0 {
return nil, fmt.Errorf("prod mode requires env: %s", strings.Join(missing, ", "))
}
// In prod, "*" CORS is never accepted.
for _, o := range c.CORSAllowOrigins {
if o == "*" {
return nil, fmt.Errorf("prod mode forbids CORS_ALLOW_ORIGINS='*'")
}
}
}
return c, nil
}
func (c *Config) IsDev() bool { return c.Mode == "dev" }
func (c *Config) DSN() string {
// MySQL DSN: user:pass@tcp(host:port)/dbname?params
return fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?parseTime=true&charset=utf8mb4&collation=utf8mb4_unicode_ci",
c.DBUser, c.DBPassword, c.DBHost, c.DBPort, c.DBName,
)
}
func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func splitCSV(s string) []string {
if s == "" {
return nil
}
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
return out
}