Compare commits

..
Author SHA1 Message Date
BaaRai e5c7bfcbdd Merge pull request #586 from BaaRai/fix/585-decomposer-contract
fix(goals,planner): enforce structured set_goals and refuse empty planning context
2026-11-27 01:50:56 +01:00
BaaRai 3d79ec9528 fix(goals): fall back to raw goal only when no LLM provider is configured (#585) 2026-11-27 01:39:33 +01:00
BaaRai 10fb8d389d Merge pull request #589 from BaaRai/fix/473-finding-fingerprint-dedup
feat(agent): deterministic finding fingerprint dedup
2026-11-27 01:27:59 +01:00
BaaRai 066b978687 Merge pull request #588 from BaaRai/fix/526-conntest-reject-tool-calls
fix(agent): reject tool-call replies in the LLM connection test
2026-11-27 01:27:53 +01:00
BaaRai cc25ad55c4 Merge pull request #587 from BaaRai/fix/550-compaction-thinking-and-evidence-hint
fix(compaction,tools): stop forcing thinking=disabled and degrade stale evidence_hint_id
2026-11-27 01:27:49 +01:00
BaaRai 1f558d8681 fix(agent): reject tool calls and tool_calls finish_reason in TestConnection (#526) 2026-11-27 01:08:46 +01:00
BaaRai 01424b685e fix(goals,planner): enforce structured set_goals contract and guard empty planner context (#585) 2026-11-27 01:08:45 +01:00
BaaRai 478bdcae82 fix(tools): degrade stale or invalid evidence_hint_id cleanly in report_finding (#550) 2026-11-27 01:08:45 +01:00
BaaRai efe588a526 fix(compaction): omit hardcoded thinking=disabled to avoid Anthropic 400 (#550) 2026-11-27 01:08:45 +01:00
13 changed files with 1146 additions and 73 deletions
+18 -2
View File
@@ -537,16 +537,32 @@ func buildCompressionInput(g *coldGraph, b block, nodeByID map[int64]*db.Node) s
return sb.String()
}
// isThinkingBetweenToolsError reports an Anthropic 400 telling the caller that
// the model rejects thinking.type="disabled" and requires "between_tools" instead
// (e.g. Claude Sonnet 5.5, #550).
func isThinkingBetweenToolsError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "between_tools") && strings.Contains(msg, "thinking")
}
// compress runs the §4 body LLM call on one block. Uses the same model the agent
// runs on; thinking disabled (a pure summarization step).
// runs on without forcing thinking.type="disabled" (models such as Claude Sonnet
// 5.5 reject {"type":"disabled"} with HTTP 400; inheriting the profile's working
// thinking setting avoids sending an unsupported parameter, #550).
func (c *Compactor) compress(ctx context.Context, g *coldGraph, b block, nodeByID map[int64]*db.Node) (string, error) {
req := llm.CompletionRequest{
System: []string{compressionSystem},
Messages: []llm.Message{llm.UserText(buildCompressionInput(g, b, nodeByID))},
MaxTokens: 1500,
Thinking: "disabled",
}
msg, _, _, err := c.prov.Complete(ctx, req)
if err != nil && isThinkingBetweenToolsError(err) {
req.Thinking = "between_tools"
msg, _, _, err = c.prov.Complete(ctx, req)
}
if err != nil {
return "", err
}
+146
View File
@@ -0,0 +1,146 @@
package agent
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/norma/llm"
)
func sampleCompactionInputs() (*coldGraph, block, map[int64]*db.Node) {
n1 := &db.Node{ID: 10, Kind: db.KindIntent, State: "done", Payload: json.RawMessage(`{"summary":"Scan /api/login"}`)}
n2 := &db.Node{ID: 11, Kind: db.KindFact, State: "confirmed", Payload: json.RawMessage(`{"summary":"Login returns 401"}`)}
g := newColdGraph(
[]cgNode{
{ID: 10, Kind: db.KindIntent, State: "done"},
{ID: 11, Kind: db.KindFact, State: "confirmed"},
},
[]cgEdge{
{From: 10, Rel: db.RelYields, To: 11},
},
)
b := block{Members: []int64{10, 11}}
return g, b, map[int64]*db.Node{10: n1, 11: n2}
}
// Regression for #550: compaction must not hardcode thinking={"type":"disabled"},
// which Claude Sonnet 5.5 rejects with HTTP 400 invalid_request_error.
func TestCompactorCompressDoesNotSendThinkingDisabled(t *testing.T) {
var (
mu sync.Mutex
bodies []map[string]any
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
mu.Lock()
bodies = append(bodies, m)
mu.Unlock()
if th, ok := m["thinking"].(map[string]any); ok && th["type"] == "disabled" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"To turn thinking off on this model, send \"thinking\": {\"type\": \"between_tools\"} instead of {\"type\": \"disabled\"}. The model does not think before responding."}}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"msg_1","type":"message","role":"assistant","content":[{"type":"text","text":"Consolidated summary (#10,#11)."}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":6}}`))
}))
defer srv.Close()
prov, err := llm.NewProvider(llm.Config{
Format: llm.FormatAnthropic,
BaseURL: srv.URL,
APIKey: "test-key",
Model: "claude-sonnet-5-5",
})
if err != nil {
t.Fatal(err)
}
c := NewCompactor(prov, "claude-sonnet-5-5")
g, b, nodes := sampleCompactionInputs()
got, err := c.compress(context.Background(), g, b, nodes)
if err != nil {
t.Fatalf("compress failed: %v", err)
}
if got != "Consolidated summary (#10,#11)." {
t.Fatalf("unexpected compressed body: %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(bodies) != 1 {
t.Fatalf("expected 1 request, got %d", len(bodies))
}
if _, hasThinking := bodies[0]["thinking"]; hasThinking {
t.Fatalf("compaction request must not send rejected thinking parameter when profile has none: %+v", bodies[0]["thinking"])
}
}
// Regression for #550: if a profile itself sets ThinkingType="disabled" and the
// provider returns the Anthropic 400 requesting thinking.type="between_tools",
// compaction retries once with "between_tools" and succeeds.
func TestCompactorCompressRetriesWithBetweenToolsOnAnthropic400(t *testing.T) {
var (
mu sync.Mutex
thinkingTypes []string
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
tt := ""
if th, ok := m["thinking"].(map[string]any); ok {
tt, _ = th["type"].(string)
}
mu.Lock()
thinkingTypes = append(thinkingTypes, tt)
mu.Unlock()
if tt == "disabled" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"To turn thinking off on this model, send \"thinking\": {\"type\": \"between_tools\"} instead of {\"type\": \"disabled\"}."}}`))
return
}
if tt != "between_tools" {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"type":"error","error":{"type":"invalid_request_error","message":"unexpected thinking mode"}}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"msg_2","type":"message","role":"assistant","content":[{"type":"text","text":"Summary via between_tools (#10,#11)."}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":6}}`))
}))
defer srv.Close()
prov, err := llm.NewProvider(llm.Config{
Format: llm.FormatAnthropic,
BaseURL: srv.URL,
APIKey: "test-key",
Model: "claude-sonnet-5-5",
ThinkingType: "disabled",
})
if err != nil {
t.Fatal(err)
}
c := NewCompactor(prov, "claude-sonnet-5-5")
g, b, nodes := sampleCompactionInputs()
got, err := c.compress(context.Background(), g, b, nodes)
if err != nil {
t.Fatalf("compress failed on between_tools fallback: %v", err)
}
if got != "Summary via between_tools (#10,#11)." {
t.Fatalf("unexpected compressed body: %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(thinkingTypes) != 2 || thinkingTypes[0] != "disabled" || thinkingTypes[1] != "between_tools" {
t.Fatalf("expected thinking sequence [disabled between_tools], got %v", thinkingTypes)
}
}
+74
View File
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -36,3 +37,76 @@ func TestConnectionSendsNoTools(t *testing.T) {
t.Fatalf("connection test sent %d tools, want none:\n%s", len(req.Tools), body)
}
}
// Regression for #526: Ollama returning a tool call (with or without accompanying
// text) or finish_reason="tool_calls", or whitespace-only content, must fail
// TestConnection instead of reporting Connected.
func TestConnectionRejectsToolCallsAndWhitespaceReplies(t *testing.T) {
cases := []struct {
name string
stream bool
statusBody string
wantErrSub string
}{
{
name: "ollama_nonstream_tool_call_with_text",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_tool_call_only",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`,
wantErrSub: "tool call",
},
{
name: "ollama_nonstream_finish_reason_tool_calls_without_array",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}}`,
wantErrSub: "tool call",
},
{
name: "ollama_stream_tool_call_with_text",
stream: true,
statusBody: strings.Join([]string{
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"role":"assistant","content":"OK"}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]}}]}`,
`data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`data: [DONE]`,
``,
}, "\n\n"),
wantErrSub: "tool call",
},
{
name: "ollama_whitespace_only_content",
stream: false,
statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":" \n\t "},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":3,"total_tokens":23}}`,
wantErrSub: "no content",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
} else {
w.Header().Set("Content-Type", "application/json")
}
_, _ = w.Write([]byte(tc.statusBody))
}))
defer srv.Close()
cfg := ConfigFrom("ollama", "baronllm", srv.URL+"/v1", "", "")
cfg.Stream = tc.stream
_, reply, err := TestConnection(context.Background(), cfg)
if err == nil {
t.Fatalf("expected TestConnection to reject %s, got Connected with reply=%q", tc.name, reply)
}
if !strings.Contains(strings.ToLower(err.Error()), tc.wantErrSub) {
t.Fatalf("unexpected error for %s: %v (want substring %q)", tc.name, err, tc.wantErrSub)
}
})
}
}
+112
View File
@@ -107,3 +107,115 @@ func TestReportFindingNonHintNodeDegradesToExplicitRefs(t *testing.T) {
t.Fatalf("explicit proof ref did not survive: %+v", rec.got)
}
}
// Regression for #550: absent, null, empty, zero, or negative evidence_hint_id
// must succeed even when no explicit traffic_refs are supplied (the default
// workflow where the report agent binds traffic afterward).
func TestReportFindingAbsentOrZeroHintIDWithoutTrafficRefs(t *testing.T) {
prev := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(prev) })
SetFindingTrafficBindingEnabled(func() bool { return true })
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("absent hint id", "fixture", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
}()
cases := []struct {
name string
body string
}{
{"omitted", `{"vulnclass":"SQLI","severity":"high","summary":"omitted hint","evidence":"UNION rows"}`},
{"zero", `{"vulnclass":"SQLI","severity":"high","summary":"zero hint","evidence":"UNION rows","evidence_hint_id":0}`},
{"null", `{"vulnclass":"SQLI","severity":"high","summary":"null hint","evidence":"UNION rows","evidence_hint_id":null}`},
{"empty_string", `{"vulnclass":"SQLI","severity":"high","summary":"empty hint","evidence":"UNION rows","evidence_hint_id":""}`},
{"negative", `{"vulnclass":"SQLI","severity":"high","summary":"negative hint","evidence":"UNION rows","evidence_hint_id":-5}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ts := NewToolSet(nil, "")
ts.ts, ts.taskID = d.Exploration(task.ExplorationID), task.ID
rec := &capturingRecorder{}
ts.SetFindingRecorder(rec)
res, err := ts.addFinding().Call(t.Context(), json.RawMessage(tc.body), nil)
if err != nil {
t.Fatalf("report_finding returned error: %v", err)
}
if got := res.Flatten(); !strings.HasPrefix(got, "finding recorded: ") {
t.Fatalf("%s rejected: %q", tc.name, got)
}
if len(rec.got) != 0 {
t.Fatalf("%s unexpectedly bound refs: %+v", tc.name, rec.got)
}
})
}
}
// Regression for #550: a stale/deleted or non-hint evidence_hint_id passed
// without explicit traffic_refs must degrade cleanly (record the finding as
// not_bound with an explanatory evidence_note) instead of discarding it.
func TestReportFindingStaleOrNonHintIDWithoutTrafficRefsDegradesCleanly(t *testing.T) {
prev := FindingTrafficBindingEnabled()
t.Cleanup(func() { SetFindingTrafficBindingEnabled(prev) })
SetFindingTrafficBindingEnabled(func() bool { return true })
d := testDB(t)
defer d.Close()
task, err := d.CreateTask("stale hint id", "fixture", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
}()
exp := d.Exploration(task.ExplorationID)
factID, err := exp.AddNode(db.KindFact, map[string]any{"summary": "not a hint"}, 0, "confirmed", "worker", nil)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
hintID int64
}{
{"stale_nonexistent", 999999},
{"non_hint_fact_node", factID},
} {
t.Run(tc.name, func(t *testing.T) {
rec := &capturingRecorder{}
ts := NewToolSet(nil, "")
ts.ts, ts.taskID = exp, task.ID
ts.SetFindingRecorder(rec)
body, _ := json.Marshal(map[string]any{
"vulnclass": "XSS",
"severity": "medium",
"summary": "stale hint finding",
"evidence": "reflected payload",
"evidence_hint_id": tc.hintID,
})
res, err := ts.addFinding().Call(t.Context(), json.RawMessage(body), nil)
if err != nil {
t.Fatalf("report_finding returned error: %v", err)
}
got := res.Flatten()
if !strings.HasPrefix(got, "finding recorded: ") {
t.Fatalf("stale/non-hint evidence_hint_id discarded finding: %q", got)
}
if !strings.Contains(got, "Ignored stale or non-local evidence_hint_id=") {
t.Fatalf("expected explanatory evidence_note, got: %q", got)
}
if len(rec.got) != 0 {
t.Fatalf("expected 0 refs on degraded stale hint, got %+v", rec.got)
}
})
}
}
+8 -1
View File
@@ -2,6 +2,7 @@ package agent
import (
"encoding/json"
"errors"
"fmt"
"sync"
@@ -227,6 +228,12 @@ func HintTrafficSchema() map[string]any {
return map[string]any{"type": "array", "description": "Optional: verified traffic references corresponding to the specific vulnerability in this hint, order preserved; after handoff, report_finding can carry these references via evidence_hint_id.", "items": obj(map[string]any{"traffic_id": str("real traffic ID"), "role": str("baseline / proof / verification / supporting"), "note": str("which conclusion this traffic supports")}, "traffic_id")}
}
// errEvidenceHintNotFound marks an evidence_hint_id that does not resolve to a
// local hint node of the current task (e.g. stale/deleted ID, inherited hint, or
// non-hint node ID). report_finding degrades cleanly instead of discarding the
// finding (#550).
var errEvidenceHintNotFound = errors.New("evidence_hint_id is not a local hint node")
func (t *ToolSet) findingRefsFromHint(hintID int64, explicit []db.TrafficRef) ([]db.TrafficRef, error) {
if hintID <= 0 {
return db.NormalizeTrafficRefs(explicit)
@@ -236,7 +243,7 @@ func (t *ToolSet) findingRefsFromHint(hintID int64, explicit []db.TrafficRef) ([
return nil, err
}
if n == nil || n.Kind != db.KindHint {
return nil, fmt.Errorf("evidence_hint_id=%d must be a hint node of this task (inherited hints cannot be bound directly)", hintID)
return nil, fmt.Errorf("%w: evidence_hint_id=%d must be a hint node of this task (inherited hints cannot be bound directly)", errEvidenceHintNotFound, hintID)
}
var payload struct {
Refs []db.TrafficRef `json:"traffic_refs"`
+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
+57 -1
View File
@@ -14,6 +14,7 @@ import (
"context"
"fmt"
"io"
"iter"
"log/slog"
"net/http"
"net/url"
@@ -689,8 +690,9 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
// budget to emit OK cleanly (finish=stop).
// EscalateMaxTokens stays false: don't raise the cap and retry on truncation, to
// avoid burning tokens in a resume loop.
probe := &connTestProvider{inner: prov}
reply, err := agentcore.Run(ctx, agentcore.Options{
Provider: prov,
Provider: probe,
SystemPrompt: []string{"You are a connection test. Just output the two characters OK — no thinking, no explanation, nothing else."},
Tools: []actool.CoreTool{}, // not nil: nil means the SDK's unconfined file and shell tools
PermissionMode: acperm.ModeBypass,
@@ -712,6 +714,12 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, "", err
}
// Reject tool-call replies (#526): the connection test asks for plain text
// with no tools; a model answering with a tool call or tool_calls/tool_use
// finish reason must not be reported as Connected even if it also emitted text.
if probe.sawToolCall || isToolCallStopReason(probe.stopReason) {
return lat, "", fmt.Errorf("the model returned a tool call instead of a text reply (finish_reason=%q)", probe.stopReason)
}
// err==nil is not enough: requests that go through while the model emits nothing
// at all really happen (thinking burned the whole budget, the body got swallowed
// by a safety policy, a compatibility layer dropped the content). Such a config
@@ -723,3 +731,51 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
}
return lat, reply, nil
}
// connTestProvider observes the raw provider response during TestConnection so
// tool-call replies and tool_calls/tool_use stop reasons are rejected (#526).
type connTestProvider struct {
inner llm.Provider
sawToolCall bool
stopReason string
}
func (p *connTestProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
for ev, err := range p.inner.Stream(ctx, req) {
if err == nil {
if ev.Type == llm.SEToolUseStart {
p.sawToolCall = true
}
if ev.StopReason != "" {
p.stopReason = ev.StopReason
}
}
if !yield(ev, err) {
return
}
}
}
}
func (p *connTestProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
msg, stopReason, usage, err := p.inner.Complete(ctx, req)
if err == nil {
if len(msg.ToolUses()) > 0 {
p.sawToolCall = true
}
if stopReason != "" {
p.stopReason = stopReason
}
}
return msg, stopReason, usage, err
}
func isToolCallStopReason(stopReason string) bool {
switch strings.ToLower(strings.TrimSpace(stopReason)) {
case "tool_use", "tool_calls":
return true
default:
return false
}
}
+40 -11
View File
@@ -3,6 +3,7 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strconv"
@@ -500,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
@@ -680,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
@@ -1602,16 +1617,23 @@ func (t *ToolSet) addFinding() actool.CoreTool {
if !findingTrafficBindingEnabled() {
a.TrafficRefs, a.EvidenceHintID = nil, nil
}
// A model routinely emits "evidence_hint_id": 0 meaning "absent" — the field
// is optional, so 0 must mean "no hint", not an error. A hint id that does
// not resolve to a local hint node (passing a fact node number is the common
// case) must not sink an otherwise complete finding either: when explicit
// traffic_refs are present they are sufficient on their own, so degrade to
// them and keep the finding. Only a call with neither usable hint nor usable
// refs fails.
refs, err := t.findingRefsFromHint(pid(a.EvidenceHintID), a.TrafficRefs)
// A model routinely emits "evidence_hint_id": 0 (or null/"") meaning "absent",
// or passes a stale/non-hint node ID. Because evidence_hint_id is optional and
// findings without bound traffic are valid (the report agent binds traffic later),
// a stale or non-local hint ID must degrade cleanly to whatever valid explicit
// traffic_refs were passed (including none) instead of discarding the finding (#550).
hintID := pid(a.EvidenceHintID)
var ignoredHintNote string
refs, err := t.findingRefsFromHint(hintID, a.TrafficRefs)
if err != nil {
if degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs); derr == nil && len(degraded) > 0 {
if errors.Is(err, errEvidenceHintNotFound) {
degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs)
if derr != nil {
return actool.Errorf(derr.Error()), nil
}
refs = degraded
ignoredHintNote = fmt.Sprintf("Ignored stale or non-local evidence_hint_id=%d; finding recorded without hint references.", hintID)
} else if degraded, derr := db.NormalizeTrafficRefs(a.TrafficRefs); derr == nil && len(degraded) > 0 {
refs = degraded
} else {
return actool.Errorf(err.Error()), nil
@@ -1696,6 +1718,13 @@ func (t *ToolSet) addFinding() actool.CoreTool {
result.EvidenceNote = "Finding saved without bound traffic. Automatic agent traffic binding is off: this finding remains visible but cannot close a goal unless traffic is bound manually later (or a non-HTTP goal is proven with an observed tool_output fact)."
}
}
if ignoredHintNote != "" {
if result.EvidenceNote != "" {
result.EvidenceNote = ignoredHintNote + " " + result.EvidenceNote
} else {
result.EvidenceNote = ignoredHintNote
}
}
raw, _ := json.Marshal(result)
return actool.Text(fmt.Sprintf("finding recorded: %d\n%s", recorded.NodeID, raw)), nil
})
+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)
}
}
+6 -2
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)
@@ -873,7 +873,11 @@ func (s *Server) emitTaskLLMTransition(t *Task, transition db.TaskLLMTransition,
}
mode := "automatic"
kind := "llm_switch"
summary := fmt.Sprintf("%s quota exhausted", llmAuditProfileLabel(previous))
reasonLabel := "failed consecutive calls"
if isQuotaExhaustedError(cause) {
reasonLabel = "quota exhausted"
}
summary := fmt.Sprintf("%s %s", llmAuditProfileLabel(previous), reasonLabel)
if transition.NextProfileID != nil {
summary += fmt.Sprintf(", subsequent calls switched to %s", llmAuditProfileLabel(next))
} else {