Files
oikos/internal/policy/classify.go
dtoro e074f04bdf feat: Phase 0 of hexagonal refactor — ADR 0016, core scaffold, depguard rules
Problem: the hexagonal-architecture plan (plans/2026-08-15-hexagonal-
architecture.md) needs its foundation — an accepted ADR, the target
directory tree, and machine-checked dependency rules — before any
service extraction starts. Also folds the four outstanding review
findings (F3.1/F5/F6/F7) into the plan: ObservationService owns the
bounded probe-concurrency contract (scheduler.go:133), Phase 9 gates
ExecutionService+PolicyService ≥ 90% with a gating-matrix test,
per-phase abort criteria, and the §3.2 internal/config note.

Change:
- docs/adr/0016-hexagonal-ports-adapters.md records context, decision,
  and consequences of the ports & adapters migration.
- internal/domain → internal/core/domain (mechanical import rewrite,
  20 files), new internal/core/{ports,app}, internal/adapters trees
  with package docs.
- .golangci.yml: depguard rules for §3.1 (core purity, no agent-client
  tech in core, nomos isolation — the nomos rules self-activate when
  internal/nomos exists in Phase 8). Config migrated to golangci-lint
  v2 format so it loads at all (the v1 config errored under v2, masked
  by CI's advisory continue-on-error). Verified depguard fires on a
  planted openai-go import in internal/core/app.
- CONTRIBUTING.md layout section now shows the core/adapters tree.

Risk: import path churn is mechanical and tests pass unchanged; the
lint config migration surfaces the pre-existing 400-issue baseline
(advisory in CI, unchanged policy) — new/moved packages lint clean.

Verification: go vet ./..., make test (race, core/domain at 100%
coverage), make generate-check, golangci-lint on internal/core/... and
internal/adapters/... — 0 issues; depguard violation probe confirmed.
2026-08-15 22:09:19 +02:00

159 lines
4.8 KiB
Go

// Package policy implements Oikos classification and policy evaluation.
// Determines risk class, autonomy route, and approval requirements.
package policy
import (
"context"
"encoding/json"
"fmt"
"github.com/dtoro/oikos/internal/core/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// ClassificationResult holds the outcome of classifying a signal.
type ClassificationResult struct {
RiskClass string
Route string // 'auto-act', 'escalate', 'hold'
RecommendedAction json.RawMessage
AutonomyCheck string
BlastRadius []uuid.UUID
CorrelationID string
Reasoning json.RawMessage
}
// Classify evaluates a signal against policy rules to determine the action route.
// ctx must have a DB connection pool accessible via a helper interface.
type Classifier struct {
DB interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
Exec(ctx context.Context, sql string, args ...any) (int64, error)
}
}
// NewClassifier creates a classifier with a DB query interface.
func NewClassifier(dbc interface {
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
Exec(ctx context.Context, sql string, args ...any) (int64, error)
}) *Classifier {
return &Classifier{DB: dbc}
}
// ClassifySignal evaluates a signal and returns the classification result.
func (c *Classifier) ClassifySignal(ctx context.Context, signalEntityID, targetEntityID uuid.UUID,
kind, severity, correlationID string) (*ClassificationResult, error) {
// Determine target entity type
var entityType string
err := c.DB.QueryRow(ctx,
"SELECT type FROM entities WHERE id = $1", targetEntityID).Scan(&entityType)
if err != nil {
return nil, fmt.Errorf("%w: target entity %s", domain.ErrNotFound, targetEntityID)
}
// Look up risk class for this entity type and action
var riskClass string
var approvalRequired string
err = c.DB.QueryRow(ctx, `
SELECT rc.name, rc.approval_required
FROM risk_classes rc
WHERE rc.name = (
SELECT COALESCE(ar.risk_class, 'reversible_low')
FROM approval_rules ar
WHERE ar.entity_type = $1 AND ar.action = $2
LIMIT 1
)`, entityType, kind).Scan(&riskClass, &approvalRequired)
if err != nil {
// Default to escalate
riskClass = "reversible_low"
approvalRequired = "operator"
}
// Check global autonomy setting
var globalAutoAct string
err = c.DB.QueryRow(ctx,
"SELECT value FROM autonomy_settings WHERE key = 'global.auto_act'").Scan(&globalAutoAct)
if err != nil {
globalAutoAct = "on" // default to on
}
// Check per-entity kill-switch
var slug string
c.DB.QueryRow(ctx, "SELECT slug FROM entities WHERE id = $1", targetEntityID).Scan(&slug)
var entityAutoAct string
if slug != "" {
c.DB.QueryRow(ctx,
"SELECT value FROM autonomy_settings WHERE key = $1",
"never_auto_act."+slug).Scan(&entityAutoAct)
}
// Determine route
route, autonomyCheck := determineRoute(globalAutoAct, entityAutoAct, approvalRequired)
// Compute blast radius
blastRadius := computeBlastRadius(ctx, c.DB, targetEntityID)
reasoning := map[string]any{
"entity_type": entityType,
"risk_class": riskClass,
"approval_rule": approvalRequired,
"global_auto_act": globalAutoAct,
"entity_slug": slug,
}
reasoningJSON, _ := json.Marshal(reasoning)
recommended, _ := json.Marshal(map[string]any{
"action": kind,
"reason": fmt.Sprintf("signal %s on %s", severity, entityType),
})
return &ClassificationResult{
RiskClass: riskClass,
Route: route,
RecommendedAction: recommended,
AutonomyCheck: autonomyCheck,
BlastRadius: blastRadius,
CorrelationID: correlationID,
Reasoning: reasoningJSON,
}, nil
}
// determineRoute evaluates autonomy settings and approval requirements to
// decide whether a signal should auto-act, escalate, or hold for approval.
func determineRoute(globalAutoAct, entityAutoAct, approvalRequired string) (route, autonomyCheck string) {
if globalAutoAct == "off" || globalAutoAct == "false" {
return "escalate", "blocked: global auto_act disabled"
}
if entityAutoAct == "true" {
return "escalate", "blocked: per-entity kill-switch"
}
if approvalRequired == "none" {
return "auto-act", "allowed"
}
return "escalate", "requires approval: " + approvalRequired
}
// computeBlastRadius traverses relationships to find affected entities.
func computeBlastRadius(ctx context.Context, dbc interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}, entityID uuid.UUID) []uuid.UUID {
rows, err := dbc.Query(ctx, `
SELECT entity_id FROM blast_radius($1, 3)`, entityID)
if err != nil {
return nil
}
defer rows.Close()
var ids []uuid.UUID
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err == nil {
ids = append(ids, id)
}
}
return ids
}