feat: Phase 9 gaps closed — ApprovalService.Decide convergence, execlog fold, execworker poller
Some checks are pending
ci / build-test (push) Waiting to run
ci / docker-build (push) Waiting to run

- ApprovalService (core/app/approval.go) + ApprovalRepo (postgres adapter) with
  full decide transaction: HMAC token verify, approval flip, execution un-gate,
  session-scoped window keys (+session suffix matching GovernanceStore gate),
  nomos session flip, audit+event on failure abort. httpapi DecideApproval now
  a thin presenter delegating to the service. ListPending payload format fixed
  (json.Unmarshal not raw-wrap).
- execlog folded into postgres adapter: internal/execlog deleted, NewExecutionLog
  / ReadExecutionLog live in the db package, callers updated (mcp, httpapi).
- execworker poller over ExecutionService.DispatchQueued: advisory lock leak
  fixed (defer/recover per execution), correlation_id preserved via Finalize
  event emission (ExecRunRepo.Finalize now emits execution.{status} with
  correlation_id from the row).
- Phase 8 session export-rename completed: Store, New, and all 53 methods
  exported; cmd/nomos/ agent.go fixed to use session.PendingContinuation etc.
- Coverage gates: ExecutionService.Submit 93.1%, PolicyService.Decide 100%.
- Plans index updated, VERSION bumped to 0.36.0.
This commit is contained in:
2026-08-16 12:29:59 +02:00
parent 986937799a
commit b98d7c24bf
27 changed files with 1161 additions and 600 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -153,6 +154,40 @@ gated mutations through run. Be concise. Prefer tools over guessing.`
// explicit typed confirmation regardless of the window.
const assentWindowDuration = 30 * time.Minute
// approveExecution calls the oikos API to approve a pending execution.
// Returns true + new status on success, false on any error.
func (a *agent) approveExecution(ctx context.Context, execID string) (bool, string, error) {
if a.apiBase == "" || a.apiToken == "" {
return false, "", fmt.Errorf("nomos: apiBase or apiToken not configured")
}
body, _ := json.Marshal(map[string]string{"status": "approved"})
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
a.apiBase+"/api/v1/approvals/"+execID+"/decision", bytes.NewReader(body))
if err != nil {
return false, "", fmt.Errorf("nomos: create approval request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+a.apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := a.httpClient.Do(req)
if err != nil {
return false, "", fmt.Errorf("nomos: approval request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return false, "", fmt.Errorf("nomos: approval %s not found", execID)
}
if resp.StatusCode != http.StatusOK {
return false, "", fmt.Errorf("nomos: approval %s returned %d", execID, resp.StatusCode)
}
var result struct {
Status string `json:"status"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, "", fmt.Errorf("nomos: decode approval response: %w", err)
}
return true, result.Status, nil
}
// openAssentWindow records an active assent window in autonomy_settings so
// the MCP run tool (separate process) can check it before requiring approval
// for config_mutation commands. Key is scoped to this agent's UUID AND this
@@ -295,12 +330,12 @@ func (a *agent) chatWith(ctx context.Context, sessionID, message, systemInject s
// isTypedConfirmation ("I confirm ...", per SOUL.md's guidance for what
// to ask the operator to type).
pending := assent.ExtractPendingApprovals(func() []string {
texts := make([]string, len(lastAssistantCalls))
for i, c := range lastAssistantCalls {
texts[i] = c.resultText()
}
return texts
}())
texts := make([]string, len(lastAssistantCalls))
for i, c := range lastAssistantCalls {
texts[i] = c.resultText()
}
return texts
}())
operatorAssented := assent.IsAssent(message)
typedConfirm := assent.IsTypedConfirmation(message)
if len(pending) > 0 && (operatorAssented || typedConfirm) {
@@ -394,11 +429,11 @@ func (a *agent) chatWith(ctx context.Context, sessionID, message, systemInject s
var acc openai.ChatCompletionAccumulator
// Capture token usage from this LLM response for activity logging.
// Previously always NULL — every agent_activity row had no token
// count. Now each tool call in this iteration gets the same total.
totalTokens := 0
// Previously always NULL — every agent_activity row had no token
// count. Now each tool call in this iteration gets the same total.
totalTokens := 0
for attempt := 0; attempt <= maxLLMRetries; attempt++ {
for attempt := 0; attempt <= maxLLMRetries; attempt++ {
acc = openai.ChatCompletionAccumulator{}
stream := a.provider.Chat.Completions.NewStreaming(ctx, params, a.reqOpts...)
for stream.Next() {
@@ -437,12 +472,12 @@ func (a *agent) chatWith(ctx context.Context, sessionID, message, systemInject s
if len(msg.ToolCalls) == 0 {
if isRefusalOrEmpty(msg.Content) {
if attempt < maxLLMRetries {
slog.Warn("nomos: empty or refusal response, retrying",
"session", sessionID, "iter", i+1, "attempt", attempt+1,
"content_len", len(msg.Content), "finish_reason", finishReason)
continue
}
if attempt < maxLLMRetries {
slog.Warn("nomos: empty or refusal response, retrying",
"session", sessionID, "iter", i+1, "attempt", attempt+1,
"content_len", len(msg.Content), "finish_reason", finishReason)
continue
}
// B.4: surface the real error context (finish_reason +
// refusal text) instead of a generic "empty response" —
// the operator can tell "content_filter — rephrase" from

View File

@@ -4,15 +4,17 @@ import (
"context"
"testing"
"github.com/dtoro/oikos/internal/nomos/session"
"github.com/dtoro/oikos/internal/nomos/turngate"
"github.com/google/uuid"
)
func TestExtractExecutionIDs(t *testing.T) {
// Real tool-result phrasings that should yield an execution id.
pos := map[string]string{
`"pct_create on host:strong auto-approved via assent window — execution 019f4b19-eafd-74ed-baa6-d24a27b3f52c running."`: "019f4b19-eafd-74ed-baa6-d24a27b3f52c",
`"run on lxc:caddy requires approval (risk: config_mutation) — execution 019f4af7-7eff-7723-b38c-b540b267f407 queued."`: "019f4af7-7eff-7723-b38c-b540b267f407",
`"apt_upgrade on host:hubris auto-approved via assent window — execution 019f4b58-c88c-7767-87dd-044608ced913 running."`: "019f4b58-c88c-7767-87dd-044608ced913",
`"pct_create on host:strong auto-approved via assent window — execution 019f4b19-eafd-74ed-baa6-d24a27b3f52c running."`: "019f4b19-eafd-74ed-baa6-d24a27b3f52c",
`"run on lxc:caddy requires approval (risk: config_mutation) — execution 019f4af7-7eff-7723-b38c-b540b267f407 queued."`: "019f4af7-7eff-7723-b38c-b540b267f407",
`"apt_upgrade on host:hubris auto-approved via assent window — execution 019f4b58-c88c-7767-87dd-044608ced913 running."`: "019f4b58-c88c-7767-87dd-044608ced913",
}
for in, want := range pos {
ids := extractExecutionIDs(in)
@@ -48,14 +50,14 @@ func TestExtractExecutionIDs(t *testing.T) {
// return false, body never executed — when a turn is already active for the
// session. continueSession relies on this so it only marks a continuation
// "continued" after a turn really ran (otherwise the result is lost: marked
// continued, never re-queued by pendingContinuations).
// continued, never re-queued by PendingContinuations).
//
// A minimal agent with only a gate is enough: if the body ever ran, chatWith
// would dereference the nil provider and panic. Returning false cleanly proves
// the body was skipped.
func TestResumeSession_SkipsWhenBusy(t *testing.T) {
a := &agent{gate: turngate.New()}
if !a.gate.acquire("sess", 0) {
if !a.gate.Acquire("sess", 0) {
t.Fatal("precondition: initial acquire should succeed on a free session")
}
ran := a.resumeSession(context.Background(), "sess", "note")
@@ -70,9 +72,9 @@ func TestResumeSession_SkipsWhenBusy(t *testing.T) {
// without reaching resumeSession's body (nil provider → panic) or markContinued.
func TestContinueSession_DefersWhenBusy(t *testing.T) {
a := &agent{gate: turngate.New()}
if !a.gate.acquire("sess", 0) {
if !a.gate.Acquire("sess", 0) {
t.Fatal("precondition: initial acquire should succeed on a free session")
}
p := pendingContinuation{ExecID: uuid.New(), SessionID: "sess", Status: "completed"}
p := session.PendingContinuation{ExecID: uuid.New(), SessionID: "sess", Status: "completed"}
a.continueSession(context.Background(), p) // must not panic; must not run/mark
}

View File

@@ -17,6 +17,7 @@ import (
"github.com/dtoro/oikos/internal/nomos/session"
"github.com/dtoro/oikos/internal/safego"
"github.com/dtoro/oikos/internal/secrets"
"github.com/jackc/pgx/v5"
)
func main() {
@@ -425,7 +426,7 @@ func handleSessionsList(w http.ResponseWriter, r *http.Request, st *session.Stor
limit = n
}
}
sessions, err := st.ListSessionsFiltered(r.Context(), ListFilter{
sessions, err := st.ListSessionsFiltered(r.Context(), session.ListFilter{
Outcome: q.Get("outcome"),
Status: q.Get("status"),
EntityID: q.Get("entity_id"),
@@ -692,4 +693,4 @@ func truncate(s string, n int) string {
return s
}
return s[:n] + "..."
}
}

View File

@@ -8,6 +8,8 @@ import (
"regexp"
"strings"
"time"
"github.com/dtoro/oikos/internal/nomos/session"
)
// Task tools are nomos-LOCAL, not MCP tools. They are session-scoped, and the
@@ -222,7 +224,7 @@ func (a *agent) handleTaskTool(ctx context.Context, sessionID, name string, args
case "propose_plan":
raw, _ := args["steps"].([]any)
var steps []PlanStepInput
var steps []session.PlanStepInput
for _, r := range raw {
m, ok := r.(map[string]any)
if !ok {
@@ -234,7 +236,7 @@ func (a *agent) handleTaskTool(ctx context.Context, sessionID, name string, args
}
detail, _ := m["detail"].(string)
target, _ := m["target_slug"].(string)
steps = append(steps, PlanStepInput{Title: title, Detail: detail, TargetSlug: target})
steps = append(steps, session.PlanStepInput{Title: title, Detail: detail, TargetSlug: target})
}
if len(steps) == 0 {
return "error: propose_plan needs at least one step with a title", true
@@ -263,7 +265,7 @@ func (a *agent) handleTaskTool(ctx context.Context, sessionID, name string, args
}
appendedNote := ""
if !hasWritebackStep {
steps = append(steps, PlanStepInput{
steps = append(steps, session.PlanStepInput{
Title: "Write back: update_entity_attributes + create_relationship + upsert_knowledge",
Detail: "Call update_entity_attributes for every entity you ran against (versions, states, counts, timestamps). Call create_relationship for any edge you discovered. Then upsert_knowledge about the affected entities (pass `about` as an array).",
})