Merge pull request #586 from BaaRai/fix/585-decomposer-contract

fix(goals,planner): enforce structured set_goals and refuse empty planning context
This commit is contained in:
BaaRai
2026-11-27 01:50:56 +01:00
committed by GitHub
7 changed files with 702 additions and 59 deletions
+107 -26
View File
@@ -3,7 +3,9 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"github.com/Autumn-27/artex/db"
@@ -72,10 +74,30 @@ type GoalSpec struct {
VulnClass string `json:"vulnclass,omitempty"`
}
// ErrGoalDecompositionContract reports that the Goal Decomposer did not submit
// at least one non-empty goal through a structured set_goals tool call even
// after the single strict retry.
var ErrGoalDecompositionContract = errors.New("goal decomposition did not produce a structured set_goals tool call")
// ErrGoalDecompositionEmptyInput reports that goal decomposition was invoked
// with an empty task goal.
var ErrGoalDecompositionEmptyInput = errors.New("goal decomposition requires a non-empty task goal")
// ErrGoalDecompositionNoProvider reports that goal decomposition cannot run
// because no LLM provider is configured. Callers distinguish this from a
// structured tool-call contract failure (ErrGoalDecompositionContract).
var ErrGoalDecompositionNoProvider = errors.New("goal decomposition failed: no LLM provider configured")
// goalsStrictRetryPrompt is sent once when the initial goal decomposition run
// finishes without persisting any non-empty goal via a structured set_goals
// tool call (e.g. the model emitted set_goals in plain text instead).
const goalsStrictRetryPrompt = "You did not submit any goals through a structured tool call. Do not write set_goals or JSON as plain text. Invoke the structured set_goals tool now with at least one non-empty goal."
// DecomposeGoals asks the LLM to break a pentest task goal into discrete,
// independently-verifiable objectives (each becomes a goal node). Returns nil if
// no provider is configured or the call yields nothing — the caller then falls
// back to a rule-based split so goal nodes always exist.
// independently-verifiable objectives (each becomes a goal node). It enforces
// the structured set_goals tool-call contract: if no non-empty goal is
// submitted on the first pass, it retries once with a stricter instruction and
// then returns an explicit error instead of materializing empty goals.
//
// prov is supplied by the caller (rather than built here from a Config) so goal
// decomposition rides the SAME provider instance as the rest of the engine — it
@@ -94,12 +116,8 @@ type GoalSpec struct {
//
// ts is the task's exploration store: set_goals writes the decomposed goal nodes
// straight into it (the same managed tool the main agent uses to add goals at
// runtime). The returned specs are read back from the store so callers can emit
// per-goal activity and detect the "LLM produced nothing" case for their fallback.
func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, emit func(db.Activity)) []GoalSpec {
if prov == nil {
return nil
}
// runtime).
func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, emit func(db.Activity)) ([]GoalSpec, error) {
return DecomposeGoalsWithProvider(ctx, prov, dataDir, goalText, desc, as, ts, taskID, false, 0, emit)
}
@@ -107,9 +125,16 @@ func DecomposeGoals(ctx context.Context, prov llm.Provider, dataDir, goalText, d
// ordered provider chain. It preserves the same tools and write behavior while
// letting the caller own provider selection/failover. maxTokens is the profile's
// per-reply output cap (0 = send none).
func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, nonStreaming bool, maxTokens int, emit func(db.Activity)) []GoalSpec {
func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir, goalText, desc string, as *db.AssetStore, ts *db.ExplorationStore, taskID int64, nonStreaming bool, maxTokens int, emit func(db.Activity)) ([]GoalSpec, error) {
if prov == nil {
return nil
return nil, ErrGoalDecompositionNoProvider
}
if ts == nil {
return nil, errors.New("goal decomposition failed: exploration store is not initialized")
}
trimmedGoal := strings.TrimSpace(goalText)
if trimmedGoal == "" {
return nil, ErrGoalDecompositionEmptyInput
}
// Goal decomposition is a one-shot call: it does not attach a transcript store, so
// agentcore does not put a session id on the ctx (it only does when there is a
@@ -120,8 +145,10 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
// explicitly: decomposition requests of the same exploration share it (good for
// cache hits), the naming does not collide with planner/worker, and
// llmrec.parseSession can attribute it correctly.
if ts != nil {
ctx = transcript.WithSessionID(ctx, fmt.Sprintf("exp%d-goals", ts.ID()))
ctx = transcript.WithSessionID(ctx, fmt.Sprintf("exp%d-goals", ts.ID()))
beforeIDs, err := existingGoalIDs(ts)
if err != nil {
return nil, fmt.Errorf("goal decomposition failed to read existing goals: %w", err)
}
// worker="goals" tags the goal nodes' provenance; ts/taskID let set_goals link
// each goal under the task root. This is the catalog's real set_goals tool, so a
@@ -142,19 +169,19 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
tools = append(tools, tsx.addTaskScope())
sys += goalsScopeTail
}
userMsg := "Task goal:\n" + goalText
userMsg := "Task goal:\n" + trimmedGoal
if d := strings.TrimSpace(desc); d != "" {
userMsg += "\n\nTask description (background information, may include target scope / flag count / engagement notes; for reference only — do not invent anything it does not mention):\n" + d
}
// Use captureRun so every LLM step is emitted as an activity record (visible in
// the plan tab under the round-0 marker). Falls back gracefully when emit is nil.
// Use captureRunSession on one session so a single strict retry keeps any
// prior tool results (constraints/scope) and shows the model its prior output.
captureEmit := func(r db.Activity) {
if emit != nil {
r.Worker = "planner"
emit(r)
}
}
captureRun(ctx, agentcore.Options{
session := agentcore.NewSession(agentcore.Options{
Provider: prov,
SystemPrompt: []string{sys},
Tools: tools,
@@ -164,23 +191,77 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
MaxTurns: 8,
NonStreaming: nonStreaming, // when this profile selects non-streaming, use Provider.Complete
MaxTokens: maxTokens, // 0 = send no cap, the server's default decides
}, userMsg, captureEmit)
// set_goals persisted the goals directly; read them back so the caller sees what
// was written (empty slice ⇒ the LLM produced nothing ⇒ caller falls back).
if ts == nil {
return nil
})
defer session.Close()
finalText, _, runErr := captureRunSession(ctx, session, userMsg, captureEmit)
if ctx.Err() != nil {
return nil, ctx.Err()
}
if runErr != nil {
return nil, fmt.Errorf("goal decomposition failed: %w", runErr)
}
out, err := readNewGoals(ts, beforeIDs)
if err != nil {
return nil, fmt.Errorf("goal decomposition failed to read persisted goals: %w", err)
}
if len(out) > 0 {
return out, nil
}
// No valid structured set_goals call succeeded on the first pass: allow
// exactly one strict retry before failing explicitly.
log.Printf("[goals] task %d: goal decomposer produced no structured set_goals tool call; retrying once with stricter instruction", taskID)
finalText, _, runErr = captureRunSession(ctx, session, goalsStrictRetryPrompt, captureEmit)
if ctx.Err() != nil {
return nil, ctx.Err()
}
if runErr != nil {
return nil, fmt.Errorf("goal decomposition retry failed: %w", runErr)
}
out, err = readNewGoals(ts, beforeIDs)
if err != nil {
return nil, fmt.Errorf("goal decomposition failed to read persisted goals after retry: %w", err)
}
if len(out) > 0 {
return out, nil
}
if strings.TrimSpace(finalText) != "" {
return nil, fmt.Errorf("%w after retry (model returned plain text instead of a structured tool call)", ErrGoalDecompositionContract)
}
return nil, fmt.Errorf("%w after retry", ErrGoalDecompositionContract)
}
func existingGoalIDs(ts *db.ExplorationStore) (map[int64]struct{}, error) {
nodes, err := ts.ListByKind(db.KindGoal, 10000)
if err != nil {
return nil, err
}
ids := make(map[int64]struct{}, len(nodes))
for _, n := range nodes {
ids[n.ID] = struct{}{}
}
return ids, nil
}
func readNewGoals(ts *db.ExplorationStore, before map[int64]struct{}) ([]GoalSpec, error) {
nodes, err := ts.ListByKind(db.KindGoal, 10000)
if err != nil {
return nil, err
}
nodes, _ := ts.ListByKind(db.KindGoal, 10000)
var out []GoalSpec
for _, n := range nodes {
if _, existed := before[n.ID]; existed {
continue
}
var p struct {
Text string `json:"text"`
VulnClass string `json:"vulnclass"`
}
_ = json.Unmarshal(n.Payload, &p)
if strings.TrimSpace(p.Text) != "" {
out = append(out, GoalSpec{Text: p.Text, VulnClass: p.VulnClass})
if text := strings.TrimSpace(p.Text); text != "" {
out = append(out, GoalSpec{Text: text, VulnClass: strings.TrimSpace(p.VulnClass)})
}
}
return out
return out, nil
}
+279
View File
@@ -0,0 +1,279 @@
package agent
import (
"bytes"
"context"
"errors"
"iter"
"log"
"strings"
"sync"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/norma/llm"
)
// scriptedDecomposerProvider replays a sequence of scripted stream turns and
// records every CompletionRequest it receives.
type scriptedDecomposerProvider struct {
mu sync.Mutex
turns [][]llm.StreamEvent
reqs []llm.CompletionRequest
}
func (p *scriptedDecomposerProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
p.mu.Lock()
idx := len(p.reqs)
p.reqs = append(p.reqs, req)
var evs []llm.StreamEvent
if idx < len(p.turns) {
evs = p.turns[idx]
} else if len(p.turns) > 0 {
evs = p.turns[len(p.turns)-1]
}
p.mu.Unlock()
return func(yield func(llm.StreamEvent, error) bool) {
for _, ev := range evs {
if !yield(ev, nil) {
return
}
}
}
}
func (p *scriptedDecomposerProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
acc := llm.NewAccumulator()
for ev, err := range p.Stream(ctx, req) {
if err != nil {
return llm.Message{}, "", llm.Usage{}, err
}
acc.Add(ev)
}
return acc.Message(), acc.StopReason, acc.Usage, nil
}
func (p *scriptedDecomposerProvider) calls() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.reqs)
}
func plainTextTurn(text string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SETextDelta, Text: text},
{Type: llm.SEMessageDelta, StopReason: "end_turn"},
}
}
func toolCallTurn(id, name, inputJSON string) []llm.StreamEvent {
return []llm.StreamEvent{
{Type: llm.SEToolUseStart, ToolID: id, ToolName: name},
{Type: llm.SEToolInputJSON, Text: inputJSON},
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
}
}
func TestDecomposeGoalsPlainTextToolCallFailsAfterSingleRetry(t *testing.T) {
ts := guardTaskStore(t)
prov := &scriptedDecomposerProvider{
turns: [][]llm.StreamEvent{
plainTextTurn(`set_goals({"goals":[{"text":"Audit auth on lab.local"}]})`),
plainTextTurn(`set_goals({"goals":[{"text":"Audit auth on lab.local"}]})`),
plainTextTurn(`should never be reached`),
},
}
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit auth on lab.local", "planning only", nil, ts, 0, nil)
if !errors.Is(err, ErrGoalDecompositionContract) {
t.Fatalf("expected ErrGoalDecompositionContract, got goals=%+v err=%v", got, err)
}
if len(got) != 0 {
t.Fatalf("expected no returned goals, got %+v", got)
}
if prov.calls() != 2 {
t.Fatalf("expected exactly 2 LLM calls (initial + 1 retry), got %d", prov.calls())
}
// Verify the second call received the stricter retry prompt.
second := prov.reqs[1]
foundRetry := false
for _, msg := range second.Messages {
for _, blk := range msg.Content {
if strings.Contains(blk.Text, "structured set_goals tool") {
foundRetry = true
}
}
}
if !foundRetry {
t.Fatalf("second request did not include the stricter retry instruction: %+v", second.Messages)
}
nodes, lerr := ts.ListByKind(db.KindGoal, 100)
if lerr != nil {
t.Fatal(lerr)
}
if len(nodes) != 0 {
t.Fatalf("expected 0 materialized goal nodes in DB, got %d", len(nodes))
}
}
func TestDecomposeGoalsSingleRetrySucceeds(t *testing.T) {
ts := guardTaskStore(t)
prov := &scriptedDecomposerProvider{
turns: [][]llm.StreamEvent{
plainTextTurn(`set_goals({"goals":[{"text":"Identify SQLi on /login"}]})`),
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":"Identify SQLi on /login","vulnclass":"SQLi"}]}`),
plainTextTurn("Goals submitted."),
},
}
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Test /login for SQLi", "scope: lab.local", nil, ts, 0, nil)
if err != nil {
t.Fatalf("expected single retry to succeed, got err=%v", err)
}
if len(got) != 1 || got[0].Text != "Identify SQLi on /login" || got[0].VulnClass != "SQLi" {
t.Fatalf("unexpected goals: %+v", got)
}
// Turn 1: plain text; Turn 2: retry tool call; Turn 3: post-tool completion.
if prov.calls() != 3 {
t.Fatalf("expected 3 provider turns (plain text, retry tool_use, final), got %d", prov.calls())
}
nodes, lerr := ts.ListByKind(db.KindGoal, 100)
if lerr != nil {
t.Fatal(lerr)
}
if len(nodes) != 1 {
t.Fatalf("expected 1 persisted goal node, got %d", len(nodes))
}
}
func TestDecomposeGoalsValidStructuredToolCallAccepted(t *testing.T) {
ts := guardTaskStore(t)
prov := &scriptedDecomposerProvider{
turns: [][]llm.StreamEvent{
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":"Confirm auth bypass on admin panel","vulnclass":"AuthBypass"},{"text":"Verify IDOR on /api/users","vulnclass":"IDOR"}]}`),
plainTextTurn("Done."),
},
}
got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit admin panel and /api/users", "", nil, ts, 0, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != 2 {
t.Fatalf("expected 2 goals, got %+v", got)
}
// Only 2 turns (tool_use + final end_turn) — no retry was needed.
if prov.calls() != 2 {
t.Fatalf("expected 2 turns with no retry, got %d", prov.calls())
}
}
func TestDecomposeGoalsRejectsEmptyTaskGoalAndEmptyToolArgs(t *testing.T) {
ts := guardTaskStore(t)
prov := &scriptedDecomposerProvider{
turns: [][]llm.StreamEvent{
toolCallTurn("tc_1", "set_goals", `{"goals":[{"text":" "}]}`),
plainTextTurn("ok"),
toolCallTurn("tc_2", "set_goals", `{"goals":[{"text":""}]}`),
plainTextTurn("ok"),
},
}
if got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), " ", "desc", nil, ts, 0, nil); !errors.Is(err, ErrGoalDecompositionEmptyInput) || len(got) != 0 {
t.Fatalf("empty goalText: got goals=%+v err=%v", got, err)
}
if prov.calls() != 0 {
t.Fatalf("empty goalText must not call LLM, got %d calls", prov.calls())
}
if got, err := DecomposeGoals(t.Context(), prov, t.TempDir(), "Real task goal", "", nil, ts, 0, nil); !errors.Is(err, ErrGoalDecompositionContract) || len(got) != 0 {
t.Fatalf("blank tool args: expected ErrGoalDecompositionContract, got goals=%+v err=%v", got, err)
}
nodes, err := ts.ListByKind(db.KindGoal, 100)
if err != nil {
t.Fatal(err)
}
if len(nodes) != 0 {
t.Fatalf("blank tool args must not materialize empty goal nodes, got %d", len(nodes))
}
}
func TestPlannerRefusesEmptyContextAndOverviewOmitsEmptyFields(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTaskWithOptions("", "", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
ts := d.Exploration(task.ExplorationID)
// Even if a blank goal node exists in the graph, overview must drop it and
// omit empty task description/goal, and Planner.Plan must refuse to plan.
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": " "}, 0, "open", "system", nil); err != nil {
t.Fatal(err)
}
tsx := NewToolSet(ts, "planner")
overview := tsx.graphOverviewData()
if goals, _ := overview["goals"].([]map[string]any); len(goals) != 0 {
t.Fatalf("graphOverviewData materialized empty goals: %+v", goals)
}
if _, hasTask := overview["task"]; hasTask {
t.Fatalf("graphOverviewData materialized empty task block: %+v", overview["task"])
}
prov := &scriptedDecomposerProvider{
turns: [][]llm.StreamEvent{plainTextTurn("should not run")},
}
planner := NewPlanner(prov, "test-model", t.TempDir(), nil, 0, 2)
var logBuf bytes.Buffer
prevOut := log.Writer()
log.SetOutput(&logBuf)
t.Cleanup(func() { log.SetOutput(prevOut) })
if _, _, err := planner.Plan(t.Context(), task.ID, nil, nil, "", nil, nil, nil); !errors.Is(err, ErrPlannerEmptyContext) {
t.Fatalf("nil store: expected ErrPlannerEmptyContext, got %v", err)
}
if _, _, err := planner.Plan(t.Context(), task.ID, nil, ts, " ", nil, nil, nil); !errors.Is(err, ErrPlannerEmptyContext) {
t.Fatalf("empty context: expected ErrPlannerEmptyContext, got %v", err)
}
if prov.calls() != 0 {
t.Fatalf("planner must not call LLM on empty context, got %d calls", prov.calls())
}
if !strings.Contains(logBuf.String(), "refusing to plan on empty context") {
t.Fatalf("expected clear refusal log, got: %q", logBuf.String())
}
// Verify graphOverviewData includes non-empty goal and task fields normally.
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Audit /admin"}, 0, "open", "goals", nil); err != nil {
t.Fatal(err)
}
overview = tsx.graphOverviewData()
goals, _ := overview["goals"].([]map[string]any)
if len(goals) != 1 || goals[0]["text"] != "Audit /admin" {
t.Fatalf("expected 1 non-empty goal in overview, got %+v", overview["goals"])
}
// With a valid goal node present, Planner.Plan proceeds even if the explicit
// goal arg was empty.
if _, _, err := planner.Plan(t.Context(), task.ID, nil, ts, "", nil, nil, nil); err != nil {
t.Fatalf("planner with valid goal node should proceed, got err=%v", err)
}
if prov.calls() != 1 {
t.Fatalf("expected 1 LLM call when context is valid, got %d", prov.calls())
}
}
func TestDecomposeGoalsNoProviderReturnsSentinel(t *testing.T) {
ts := guardTaskStore(t)
got, err := DecomposeGoals(t.Context(), nil, t.TempDir(), "Audit target", "desc", nil, ts, 0, nil)
if !errors.Is(err, ErrGoalDecompositionNoProvider) {
t.Fatalf("expected ErrGoalDecompositionNoProvider, got goals=%+v err=%v", got, err)
}
if errors.Is(err, ErrGoalDecompositionContract) {
t.Fatalf("no-provider error must not match ErrGoalDecompositionContract: %v", err)
}
if len(got) != 0 {
t.Fatalf("expected no goals returned, got %+v", got)
}
}
+48
View File
@@ -3,7 +3,9 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strconv"
"strings"
"sync"
@@ -516,7 +518,53 @@ func plannerSystem(goal, dataDir, workDir string) string {
// for time/heartbeat wakes). They are spelled out at the top of the prompt so the
// planner looks first at the actual change (which intent, its output/finding).
// hooks (the task's target-only Guard) sees every tool call; may be nil.
// ErrPlannerEmptyContext reports that Planner.Plan was called without usable
// planning context (missing exploration store, or both task goal and goal nodes
// are empty).
var ErrPlannerEmptyContext = errors.New("planner refused to plan on empty context")
func hasNonEmptyGoalNodes(ts *db.ExplorationStore) bool {
if ts == nil {
return false
}
nodes, err := ts.ListByKind(db.KindGoal, 100)
if err != nil {
return false
}
for _, n := range nodes {
var payload struct {
Text string `json:"text"`
}
if json.Unmarshal(n.Payload, &payload) == nil && strings.TrimSpace(payload.Text) != "" {
return true
}
}
return false
}
func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, goal string, triggers []TriggerEvent, hooks harness.HookRunner, emit func(db.Activity)) (met bool, reason string, err error) {
if ts == nil {
msg := fmt.Sprintf("task %d: refusing to plan on empty context (exploration store is nil)", taskID)
log.Printf("[planner] %s", msg)
if emit != nil {
emit(db.Activity{Worker: "planner", Kind: "result", IsError: true, Summary: msg, Detail: msg})
}
return false, "", fmt.Errorf("%w: exploration store is nil", ErrPlannerEmptyContext)
}
rootDesc, rootGoal, _ := ts.Root()
effectiveGoal := strings.TrimSpace(goal)
if effectiveGoal == "" {
effectiveGoal = strings.TrimSpace(rootGoal)
}
if effectiveGoal == "" && !hasNonEmptyGoalNodes(ts) {
msg := fmt.Sprintf("task %d: refusing to plan on empty context (empty task goal and no goals; description=%q)", taskID, strings.TrimSpace(rootDesc))
log.Printf("[planner] %s", msg)
if emit != nil {
emit(db.Activity{Worker: "planner", Kind: "result", IsError: true, Summary: msg, Detail: msg})
}
return false, "", fmt.Errorf("%w: empty task goal and no goals", ErrPlannerEmptyContext)
}
goal = effectiveGoal
// cold-digest §2.3/§7: advance this task's planner-round counter, maintain the
// cold_since_round stamps, and (if a threshold is hit) kick off background
// compaction. Synchronous part is cheap (a few queries); the LLM compaction
+16 -2
View File
@@ -501,7 +501,12 @@ func (t *ToolSet) graphOverviewData() map[string]any {
for _, g := range goals {
var p map[string]any
_ = json.Unmarshal(g.Payload, &p)
gsum = append(gsum, map[string]any{"id": g.ID, "state": g.State, "text": p["text"]})
text, _ := p["text"].(string)
text = strings.TrimSpace(text)
if text == "" {
continue
}
gsum = append(gsum, map[string]any{"id": g.ID, "state": g.State, "text": text})
}
out["goals"] = gsum
// hints: strategic hints attached to the graph by the human/main agent via
@@ -681,7 +686,16 @@ func (t *ToolSet) graphOverviewData() map[string]any {
// the original task (root) so the planner always has it, not just the
// decomposed goals.
if description, goal, err := t.ts.Root(); err == nil {
out["task"] = map[string]any{"description": description, "goal": goal}
task := map[string]any{}
if d := strings.TrimSpace(description); d != "" {
task["description"] = d
}
if g := strings.TrimSpace(goal); g != "" {
task["goal"] = g
}
if len(task) > 0 {
out["task"] = task
}
}
// Direct source tasks are a live, read-only blackboard view. Keep their
// summaries in a separate field so their intents never enter this task's
+54 -28
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"errors"
"fmt"
"log"
"sort"
@@ -46,12 +47,28 @@ func (s *Server) startTaskEngine(t *Task) {
}
s.engine.emitActivity(t, db.Activity{Worker: "planner", Kind: "round",
Summary: "round 0 goal decomposition"})
goals := s.createGoals(ctx, t, func(r db.Activity) {
goals, err := s.createGoals(ctx, t, func(r db.Activity) {
s.engine.emitActivity(t, r)
})
if ctx.Err() != nil || s.engine.IsDeleting(t.ID) {
return
}
if err != nil {
log.Printf("[goals] task %s goal decomposition failed: %v", t.ID, err)
s.engine.emitActivity(t, db.Activity{
Worker: "planner",
Kind: "result",
IsError: true,
Summary: "Goal decomposition failed: " + err.Error(),
Detail: err.Error(),
})
if won, ferr := s.m.SetTaskStatusGuarded(t.ID, "failed", ""); ferr != nil {
log.Printf("[goals] task %s failed to persist failed status: %v", t.ID, ferr)
} else if won {
go s.reconcileConcurrency()
}
return
}
for _, g := range goals {
summary := g.Text
if g.VulnClass != "" {
@@ -365,22 +382,21 @@ func (s *Server) reviveTask(t *Task) {
}
}
// createGoals materializes the goal node(s) under the task root (rel objective).
// Decomposition is done ENTIRELY by the LLM (the project requires an LLM). There is
// no rule-based fallback splitter — it only ever produced garbage (shredded URLs,
// meaningless 2-way splits). If the LLM yields nothing (an error), the raw task goal
// is used verbatim as a single goal so the task still has something to judge against.
// Returns the seeded specs so callers can emit activity records for them.
// createGoals materializes the goal node(s) under the task root (rel objective)
// through the LLM Goal Decomposer's structured set_goals tool call. It returns an
// explicit error if the task has no goal or if the decomposer fails to submit at
// least one non-empty goal via a structured tool call (including after its single
// strict retry) — empty goals or raw fallbacks are never materialized.
// emit, when non-nil, is forwarded to DecomposeGoals so LLM steps are visible in the UI.
func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity)) []goalSpec {
func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity)) ([]goalSpec, error) {
if t == nil {
return nil
return nil, fmt.Errorf("task is nil")
}
if strings.TrimSpace(t.Goal) == "" {
return nil, fmt.Errorf("task %s has empty goal", t.ID)
}
// Use the SAME LLM the task runs on (its pinned profile, else the active profile),
// NOT agent.FromEnv() — the LLM is configured via the UI (DB profile), not env vars,
// so FromEnv returned empty and every task silently fell back to the crude rule
// splitter (which shredded URLs / made meaningless 2-way splits).
var specs []goalSpec
// NOT agent.FromEnv() — the LLM is configured via the UI (DB profile), not env vars.
var as *db.AssetStore
if s.m != nil {
as = s.m.Assets()
@@ -388,26 +404,36 @@ func (s *Server) createGoals(ctx context.Context, t *Task, emit func(db.Activity
taskID, _ := strconv.ParseInt(t.ID, 10, 64)
s.engine.BeginLLMCall(t.ID)
goalRuntime := s.agentsForTask(t).runtime
decomposed := agent.DecomposeGoalsWithProvider(ctx, goalRuntime, s.m.dir, t.Goal, t.Description, as, t.Store, taskID, goalRuntime.nonStreaming(), goalRuntime.maxTokens(), emit)
decomposed, err := agent.DecomposeGoalsWithProvider(ctx, goalRuntime, s.m.dir, t.Goal, t.Description, as, t.Store, taskID, goalRuntime.nonStreaming(), goalRuntime.maxTokens(), emit)
s.engine.EndLLMCall(t.ID)
for _, g := range decomposed {
if strings.TrimSpace(g.Text) != "" {
specs = append(specs, goalSpec{Text: g.Text, VulnClass: g.VulnClass})
}
}
if len(specs) == 0 {
// No decomposed goals (LLM error / no provider): use the raw task goal verbatim
// as a single goal so the task still has something to judge against. This is the
// only path that writes here — decomposed goals are already persisted by the tool.
if g := strings.TrimSpace(t.Goal); g != "" {
log.Printf("[goals] task %s: LLM goal decomposition produced nothing, falling back to the raw goal as a single goal", t.ID)
if err != nil {
if errors.Is(err, agent.ErrGoalDecompositionNoProvider) {
// No LLM provider is configured yet: preserve the pre-existing fallback
// so the task gets a single raw goal node linked to its origin fact and
// stays alive until an LLM is configured. Structured contract failures
// from an actual model remain strict and fail the task.
g := strings.TrimSpace(t.Goal)
log.Printf("[goals] task %s: no LLM provider configured, seeding raw goal as a single goal", t.ID)
origin, _ := t.Store.OriginFactID()
id, _ := t.Store.AddNode(db.KindGoal, map[string]any{"text": g}, 0, "open", "system", nil)
id, addErr := t.Store.AddNode(db.KindGoal, map[string]any{"text": g}, 0, "open", "system", nil)
if addErr != nil {
return nil, fmt.Errorf("seed raw goal: %w", addErr)
}
if origin > 0 && id > 0 {
_ = t.Store.Link(origin, db.RelSpawns, id) // goal descends from the task root (origin fact)
}
specs = []goalSpec{{Text: g}}
return []goalSpec{{Text: g}}, nil
}
return nil, err
}
var specs []goalSpec
for _, g := range decomposed {
if text := strings.TrimSpace(g.Text); text != "" {
specs = append(specs, goalSpec{Text: text, VulnClass: strings.TrimSpace(g.VulnClass)})
}
}
return specs
if len(specs) == 0 {
return nil, fmt.Errorf("goal decomposition produced no valid goals")
}
return specs, nil
}
+197 -2
View File
@@ -2,11 +2,206 @@ package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestCreateGoalsNilTask(t *testing.T) {
if got := (&Server{}).createGoals(context.Background(), nil, nil); len(got) != 0 {
t.Fatalf("nil task produced goals: %+v", got)
got, err := (&Server{}).createGoals(context.Background(), nil, nil)
if err == nil || len(got) != 0 {
t.Fatalf("nil task must return an error and no goals: got=%+v err=%v", got, err)
}
}
// TestStartTaskEngineFailsTaskOnPlainTextDecomposer verifies end-to-end that
// when the Goal Decomposer returns set_goals as plain text instead of a
// structured tool call, startTaskEngine retries once, never materializes empty
// or fallback goals, never starts the planner, and explicitly fails the task.
func TestStartTaskEngineFailsTaskOnPlainTextDecomposer(t *testing.T) {
skipWithoutDSN(t)
var (
mu sync.Mutex
calls int
)
mockOpenAI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
calls++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "chatcmpl-test",
"object": "chat.completion",
"model": "mock-local",
"choices": []map[string]any{
{
"index": 0,
"message": map[string]any{
"role": "assistant",
"content": `set_goals({"goals":[{"text":"Audit lab target"}]})`,
},
"finish_reason": "stop",
},
},
"usage": map[string]any{"prompt_tokens": 20, "completion_tokens": 12, "total_tokens": 32},
})
}))
defer mockOpenAI.Close()
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = m.Close() })
if m.pg == nil {
db.SkipNoPG(t)
}
ctx, cancel := context.WithCancel(context.Background())
s := New(ctx, m, "", m.dir, m.dir)
t.Cleanup(func() { stopTestServer(t, s, cancel) })
pid, err := m.pg.SaveProfile(&db.LLMProfile{
Name: "mock-plaintext-decomposer",
Format: "openai",
BaseURL: mockOpenAI.URL + "/v1",
Model: "mock-local",
APIKey: "test-key",
Streaming: false,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = m.pg.DeleteProfile(pid) })
task, err := m.CreateTaskWithOptions("planning-only lab check", "Audit lab target 10.10.52.1", db.TaskCreateOptions{
LLMProfileIDs: []int64{pid},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
s.startTaskEngine(task)
mu.Lock()
gotCalls := calls
mu.Unlock()
if gotCalls != 2 {
t.Fatalf("expected exactly 2 decomposer calls (initial + 1 retry), got %d", gotCalls)
}
if st := task.lifecycleSnapshot().Status; st != "failed" {
t.Fatalf("expected in-memory task status failed, got %q", st)
}
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
if err != nil || stored == nil {
t.Fatalf("GetTask: %v %v", stored, err)
}
if stored.Status != "failed" {
t.Fatalf("expected persisted task status failed, got %q", stored.Status)
}
goals, err := task.Store.ListByKind(db.KindGoal, 100)
if err != nil {
t.Fatal(err)
}
if len(goals) != 0 {
t.Fatalf("expected 0 goal nodes materialized after contract failure, got %d", len(goals))
}
acts, _, err := task.Store.ActivityList(nil, 0, 200)
if err != nil {
t.Fatal(err)
}
foundErrAct := false
for _, a := range acts {
if a.Kind == "result" && a.IsError && strings.Contains(a.Summary, "Goal decomposition failed") {
foundErrAct = true
break
}
}
if !foundErrAct {
t.Fatalf("expected error activity describing goal decomposition failure, got %+v", acts)
}
}
// TestCreateGoalsNoProviderSeedsRawGoalAndKeepsTaskAlive verifies that when no
// LLM provider is configured, createGoals falls back to seeding the raw task
// goal as a single goal node linked from the origin fact, keeping the task
// alive instead of marking it failed.
func TestCreateGoalsNoProviderSeedsRawGoalAndKeepsTaskAlive(t *testing.T) {
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = m.Close() })
if m.pg == nil {
db.SkipNoPG(t)
}
// Ensure no global LLM profile is configured in this test DB.
profiles, err := m.pg.ListProfiles()
if err != nil {
t.Fatal(err)
}
if len(profiles) > 0 {
t.Skip("test database already has configured LLM profiles")
}
ctx, cancel := context.WithCancel(context.Background())
s := New(ctx, m, "", m.dir, m.dir)
t.Cleanup(func() { stopTestServer(t, s, cancel) })
const rawGoal = "Probe http://127.0.0.1:9/v1 for unauthenticated exposure"
task, err := m.CreateTaskWithOptions("no-provider fallback", rawGoal, db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
// Seed origin fact as launchTask does so the spawns link is exercised.
s.seed(task, rawGoal)
originID, err := task.Store.OriginFactID()
if err != nil || originID <= 0 {
t.Fatalf("expected origin fact seeded, got id=%d err=%v", originID, err)
}
goals, err := s.createGoals(ctx, task, nil)
if err != nil {
t.Fatalf("createGoals without provider must fall back cleanly, got err=%v", err)
}
if len(goals) != 1 || goals[0].Text != rawGoal {
t.Fatalf("unexpected fallback goals: %+v", goals)
}
nodes, err := task.Store.ListByKind(db.KindGoal, 10)
if err != nil {
t.Fatal(err)
}
if len(nodes) != 1 {
t.Fatalf("expected 1 persisted goal node, got %d", len(nodes))
}
edges, err := task.Store.Edges(100)
if err != nil {
t.Fatal(err)
}
linked := false
for _, e := range edges {
if e.From == originID && e.Rel == db.RelSpawns && e.To == nodes[0].ID {
linked = true
break
}
}
if !linked {
t.Fatalf("fallback goal node #%d not linked from origin fact #%d via %q (edges=%+v)", nodes[0].ID, originID, db.RelSpawns, edges)
}
if st := task.lifecycleSnapshot().Status; st == "failed" {
t.Fatalf("task without provider must stay alive, got status=%q", st)
}
}
+1 -1
View File
@@ -248,7 +248,7 @@ func (r *taskLLMRuntime) currentFor(ctx context.Context) (taskLLMSelection, erro
}
prov, cfg, id, ok := r.s.globalProviderWithProfile()
if !ok {
return sel, fmt.Errorf("task %s has no available fallback LLM provider", r.taskID)
return sel, fmt.Errorf("task %s has no available fallback LLM provider: %w", r.taskID, agent.ErrGoalDecompositionNoProvider)
}
sel.provider, sel.retry = prov, cfg.Retry
sel.healthProfileID = healthIDFor(prov, id)