mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-28 02:40:53 +08:00
fix(goals,planner): enforce structured set_goals contract and guard empty planner context (#585)
This commit is contained in:
+37
-29
@@ -46,12 +46,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 +381,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 +403,19 @@ 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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var specs []goalSpec
|
||||
for _, g := range decomposed {
|
||||
if strings.TrimSpace(g.Text) != "" {
|
||||
specs = append(specs, goalSpec{Text: g.Text, VulnClass: g.VulnClass})
|
||||
if text := strings.TrimSpace(g.Text); text != "" {
|
||||
specs = append(specs, goalSpec{Text: text, VulnClass: strings.TrimSpace(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)
|
||||
origin, _ := t.Store.OriginFactID()
|
||||
id, _ := t.Store.AddNode(db.KindGoal, map[string]any{"text": g}, 0, "open", "system", nil)
|
||||
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 nil, fmt.Errorf("goal decomposition produced no valid goals")
|
||||
}
|
||||
return specs
|
||||
return specs, nil
|
||||
}
|
||||
|
||||
+122
-2
@@ -2,11 +2,131 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user