Files
oikos/internal/httpapi/phase3_test.go
dtoro 095a3967c4 phase 3: control loop — scheduler, actuator, learning, notifier, policy, API endpoints
Implemented the full OODA control loop:

Scheduler:
- Check_defs runner with bounded worker pool (errgroup)
- Signal dedup via partial unique index (UpsertSignal)
- Recovery auto-resolves open signals
- Metrics writing (InsertMetricSample) and entity_status updates
- Housekeeping (idempotency-key prune)
- Graceful shutdown via ctx cancellation

Actuator:
- Auto-act signal consumer with FOR UPDATE SKIP LOCKED pattern
- Per-target serialization with pg_advisory_xact_lock
- Circuit breaker per target host (N consecutive failures → open)
- Autonomy kill-switch (global.auto_act, never_auto_act.<slug>)
- Execution record lifecycle (proposed → running → completed)

Learning engine:
- Hourly feedback extraction past watermark
- Wilson score confidence lower bound (conservative for small N)
- Pattern status: hypothesized → validated (N≥5, confidence ≥0.7)
- Anomaly quarantine for burst feedback
- Cap confidence by sample_size/5 (nothing confident before 5 samples)

Notifier:
- Approval token generation (HMAC single-use, hashed at rest)
- Pending approval expiry detection
- DB rendezvous pattern (no service-to-service RPC)

Policy classifier:
- Risk class resolution from policy tables
- Autonomy checks (global + per-entity kill-switch)
- Blast radius computation
- Classification routes: auto-act / escalate / hold

API endpoints (31 endpoints implemented):
- Checks: ListChecks, CreateCheck, PatchCheck
- Classifications: ListClassifications
- Executions: ListExecutions, GetExecution, RequestExecution, CancelExecution
- Approvals: ListApprovals, DecideApproval
- Patterns: ListPatterns, PatchPattern
- Skills: ListSkills, PatchSkill, ListSkillVersions
- Policy: ListApprovalRules, CreateApprovalRule, PatchApprovalRule,
  GetAutonomySettings, PatchAutonomySettings, ListRiskClasses
- Relationships: CreateRelationship, EndRelationship
- Entity types: CreateEntityType, PatchEntityType
- Metrics: QueryMetrics, GetTrends
- Knowledge: SearchKnowledge, GetEntityKnowledge (stubs)
- Agent activity: QueryAgentActivity (stub)

Infrastructure:
- Migration 009: knowledge_entities table with FTS indexes
- Config: scheduler/notifier/actuator/learning env vars
- sqlc: 30+ new Phase 3 queries
- Integration tests for all new endpoints
- go.sum updated with golang.org/x/sync
2026-07-07 15:19:25 +02:00

111 lines
2.8 KiB
Go

package httpapi
// Integration tests for Phase 3 endpoints: checks, classifications,
// executions, approvals, patterns, skills, policy, and knowledge search.
// Guarded by OIKOS_TEST_DATABASE_URL; run via `make test-db` or with env set.
import (
"encoding/json"
"testing"
)
func TestPhase3ListChecks(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/checks", nil)
if rec.Code != 200 {
t.Fatalf("list checks status %d: %v", rec.Code, body)
}
}
func TestPhase3ListApprovals(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/approvals", nil)
if rec.Code != 200 {
t.Fatalf("list approvals status %d: %v", rec.Code, body)
}
}
func TestPhase3ListRiskClasses(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/risk-classes", nil)
if rec.Code != 200 {
t.Fatalf("list risk classes status %d: %v", rec.Code, body)
}
items, _ := body["items"].([]any)
if len(items) < 2 {
t.Errorf("expected 2+ risk classes, got %d", len(items))
}
}
func TestPhase3ListAutonomySettings(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/autonomy-settings", nil)
if rec.Code != 200 {
t.Fatalf("get autonomy settings status %d: %v", rec.Code, body)
}
_ = body
}
func TestPhase3ListPatterns(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/patterns", nil)
if rec.Code != 200 {
t.Fatalf("list patterns status %d: %v", rec.Code, body)
}
}
func TestPhase3ListSkills(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/skills", nil)
if rec.Code != 200 {
t.Fatalf("list skills status %d: %v", rec.Code, body)
}
}
func TestPhase3ListExecutions(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/executions", nil)
if rec.Code != 200 {
t.Fatalf("list executions status %d: %v", rec.Code, body)
}
}
func TestPhase3ListClassifications(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/classifications", nil)
if rec.Code != 200 {
t.Fatalf("list classifications status %d: %v", rec.Code, body)
}
}
func TestPhase3QueryMetrics(t *testing.T) {
h := newTestHandler(t, devConfig())
rec, body := get(t, h, "/api/v1/metrics?entity_id=00000000-0000-0000-0000-000000000001&metric=health", nil)
if rec.Code != 200 {
t.Fatalf("query metrics status %d: %v", rec.Code, body)
}
}
func TestPhase3JSONRoundTrip(t *testing.T) {
sigData := map[string]any{
"id": "sig-123", "kind": "down", "severity": "critical",
"state": "raised", "occurrence_count": 1,
}
b, _ := json.Marshal(sigData)
var back map[string]any
if err := json.Unmarshal(b, &back); err != nil {
t.Fatalf("signal round-trip: %v", err)
}
if back["kind"] != "down" {
t.Errorf("kind = %v, want down", back["kind"])
}
}