diff options
| author | Claude Sonnet 5 <noreply@anthropic.com> | 2026-07-03 23:01:50 +0000 |
|---|---|---|
| committer | Claude Sonnet 5 <noreply@anthropic.com> | 2026-07-03 23:01:50 +0000 |
| commit | 787b7fb1aed92c2b701724a7741576053b93cccb (patch) | |
| tree | 372aac85a10093a20ce3152e2c11fcfe20bb3e9d /internal/api/roles.go | |
| parent | 1f203a7ac0efad15ec3fc0a4c5b335ad7073a52f (diff) | |
feat(role): add versioned role configs + escalation ladder + scheduler (Phase 5)
Two parts:
Part A (fixes a gap from Phase 1): Groq/OpenRouter/OpenAI were documented in
docs/api-keys-setup.md as usable once configured, but nothing actually
constructed runners for them. internal/cli/cloudrunners.go consolidates
anthropic/google/groq/openrouter/openai NativeRunner construction into one
table-driven registerCloudRunners() helper, replacing the two hand-written
per-provider blocks in serve.go/run.go. Groq/OpenRouter/OpenAI reuse
openaicompat (no new adapter code) at SandboxKind: "docker".
Part B: the token-husbanding harness's core routing mechanism.
- internal/role: RoleConfig/Tier/Rung -- a role's system prompt and a
multi-tier (provider, model) escalation ladder, versioned via config_json.
- storage: new role_configs table (draft/active/retired, UNIQUE(role,
version)) with transactional activate-retires-prior-active semantics;
new executions.escalation_rung column.
- task.AgentConfig.Role string -- purely additive; every existing task shape
(Agent.Role == "") is unaffected, proven by TestPool_Execute_NonRoleTask_Unaffected
plus the full pre-existing suite passing unchanged.
- executor.Pool.execute(): role-typed tasks with no Agent.Type yet resolve
tier 0 of their active ladder (round-robin across multi-candidate tiers,
skipping rate-limited providers, falling back to soonest-clearing) before
the existing pickAgent/Classifier path runs; SystemPrompt applies to
Agent.SystemPromptAppend. Already-resolved role tasks (scheduler resubmits)
get their escalation_rung re-derived read-only via findTierIndex.
- internal/scheduler: polls role-typed FAILED tasks, retries at the same
rung under MaxRetries or escalates to the next tier's first candidate when
budget.Accountant.Allow() permits (emitting event.KindEscalated), else
leaves the task FAILED with a final:true KindEscalated event. An
in-memory per-execution-ID "handled" set keeps the poll loop convergent.
Started by `serve` only, config knob [scheduler].poll_interval_seconds.
- internal/api: POST/GET /api/roles/{role}/versions, POST
/api/roles/{role}/activate -- unauthenticated, matching the existing
projects/tasks REST endpoints' auth posture (only chatbot MCP, agent MCP,
and WebSocket are api_token-gated in this codebase today).
Documented as stored-but-not-yet-enforced (CLAUDE.md Design Debt, matching
how task.Priority/RetryConfig are already documented): RoleConfig.Tools/
SandboxKind don't affect dispatch yet; DefaultBudgetUSD is read narrowly as
the scheduler's escalation cost estimate, not enforced at initial dispatch;
scheduler escalation always targets Candidates[0] (no round-robin, unlike
initial-dispatch tier-0 resolution); the scheduler's dedupe is per-process
and resets on restart (idempotent, harmless).
go build/vet/test -race -count=1 all pass, 21 packages.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1moSNCJRcP6kykA4tyUSs
Diffstat (limited to 'internal/api/roles.go')
| -rw-r--r-- | internal/api/roles.go | 121 |
1 files changed, 121 insertions, 0 deletions
diff --git a/internal/api/roles.go b/internal/api/roles.go new file mode 100644 index 0000000..700bec4 --- /dev/null +++ b/internal/api/roles.go @@ -0,0 +1,121 @@ +package api + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + "github.com/thepeterstone/claudomator/internal/role" + "github.com/thepeterstone/claudomator/internal/storage" +) + +// roleVersionView is the JSON shape returned for a single role_configs +// version — decodes the stored config_json back into a role.RoleConfig so +// clients get structured fields rather than an opaque string. +type roleVersionView struct { + ID string `json:"id"` + Role string `json:"role"` + Version int `json:"version"` + Status string `json:"status"` + Config role.RoleConfig `json:"config"` + CreatedAt string `json:"created_at"` + ActivatedAt string `json:"activated_at,omitempty"` + RetiredAt string `json:"retired_at,omitempty"` + ProposedBy string `json:"proposed_by,omitempty"` +} + +// handleCreateRoleVersion handles POST /api/roles/{role}/versions. The +// request body is a role.RoleConfig (config_json shape, plus an optional +// proposed_by field); a new draft version is created with the next version +// number for that role. Mirrors handleCreateProject's shape (see +// internal/api/projects.go). +func (s *Server) handleCreateRoleVersion(w http.ResponseWriter, r *http.Request) { + roleName := r.PathValue("role") + if roleName == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "role is required"}) + return + } + + var input struct { + role.RoleConfig + ProposedBy string `json:"proposed_by"` + } + if err := json.NewDecoder(r.Body).Decode(&input); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON: " + err.Error()}) + return + } + input.RoleConfig.Role = roleName + + proposedBy := input.ProposedBy + if proposedBy == "" { + proposedBy = "human" + } + + configJSON, err := json.Marshal(input.RoleConfig) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) + return + } + + created, err := s.store.CreateRoleConfig(roleName, string(configJSON), proposedBy) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusCreated, toRoleVersionView(created)) +} + +// handleListRoleVersions handles GET /api/roles/{role}/versions. +func (s *Server) handleListRoleVersions(w http.ResponseWriter, r *http.Request) { + roleName := r.PathValue("role") + rows, err := s.store.ListRoleConfigVersions(roleName) + if err != nil { + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) + return + } + views := make([]*roleVersionView, 0, len(rows)) + for _, row := range rows { + views = append(views, toRoleVersionView(row)) + } + writeJSON(w, http.StatusOK, views) +} + +// handleActivateRoleVersion handles POST /api/roles/{role}/activate?version=N. +func (s *Server) handleActivateRoleVersion(w http.ResponseWriter, r *http.Request) { + roleName := r.PathValue("role") + versionStr := r.URL.Query().Get("version") + version, err := strconv.Atoi(versionStr) + if err != nil || version < 1 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid or missing version query param"}) + return + } + if err := s.store.ActivateRoleConfigVersion(roleName, version); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusOK, map[string]interface{}{ + "message": "role config version activated", + "role": roleName, + "version": version, + }) +} + +func toRoleVersionView(row *storage.RoleConfigRow) *roleVersionView { + v := &roleVersionView{ + ID: row.ID, + Role: row.Role, + Version: row.Version, + Status: row.Status, + CreatedAt: row.CreatedAt.Format(time.RFC3339), + ProposedBy: row.ProposedBy, + } + if row.ActivatedAt != nil { + v.ActivatedAt = row.ActivatedAt.Format(time.RFC3339) + } + if row.RetiredAt != nil { + v.RetiredAt = row.RetiredAt.Format(time.RFC3339) + } + _ = json.Unmarshal([]byte(row.ConfigJSON), &v.Config) + return v +} |
