Compare commits

..
Author SHA1 Message Date
BaaRai ee763fc526 feat(server): expose POST /api/tasks/{id}/retarget HTTP handler 2026-11-27 22:19:40 +01:00
BaaRai da7015f6e8 fix(engine,agent): emit ask_operator handoff with operator_handoff cause on poll-loop stop 2026-11-27 22:19:40 +01:00
BaaRai 82af66cdd8 feat(agent,db,server): add anti-poll escalation and RetargetTask helper 2026-11-27 22:19:40 +01:00
BaaRai 935f629acf feat(intercept,guard,server): add per-host mutation lease and pre-mutation baseline gate 2026-11-27 22:19:40 +01:00
BaaRai a7e63c5db4 chore(deps): bump BaaRai/Norma replace to v0.4.12 for resume pairing & thinking fixes 2026-11-27 22:19:39 +01:00
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 30d5b96a51 feat(agent): add deterministic finding fingerprint deduplication complementing LLM triage (#473) 2026-11-27 01:08:46 +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
4851aeea5a fix(db): check rows.Err after iterating query results (#539)
ListLogs, ListLogsBefore and the two task_relations reads in the task
archive code never checked rows.Err(). When a result set fails partway
(connection drop, statement timeout), Next returns false and closes the
rows, so the later Close returns nil and the caller got a silently
truncated list: missing log lines, or an archive whose source tasks
are incomplete.


Claude-Session: https://claude.ai/code/session_01JNRiKGwr3P1LP1njD8FbR4

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-27 00:15:26 +01:00
BaaRai f76810aa04 Merge pull request #522 from BaaRai/feat/knowledge-pack
feat(agent): add versioned knowledge pack and knowledge_lookup tool
2026-11-27 00:15:05 +01:00
39 changed files with 3112 additions and 92 deletions
+116
View File
@@ -0,0 +1,116 @@
package agent
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"regexp"
"strings"
)
// ErrPollLoopDetected is returned when a worker repeats identical read-only
// polls interleaved with sleep/Sleep instead of escalating via ask_operator.
var ErrPollLoopDetected = errors.New("polling loop detected: repeated identical read-only polls with sleep; stop polling and use ask_operator to request a fresh instance")
const pollLoopRepeatThreshold = 3
var (
bashSleepRe = regexp.MustCompile(`(?i)(?:^|[;&|\s])sleep\s+[0-9]+`)
bashOnlySleepRe = regexp.MustCompile(`(?i)^\s*(?:sleep\s+[0-9]+(?:\s*[;&|]+\s*)?)+\s*$`)
bashMutateHintRe = regexp.MustCompile(`(?i)(?:^|\s)(?:-X|--request)\s*=*\s*["']?(?:POST|PUT|PATCH|DELETE)\b|(?:-d|--data|--data-raw|--data-binary|-F|--form)(?:\s|=)`)
untrustedFenceRe = regexp.MustCompile(`(?m)^<<<(?:END_)?UNTRUSTED_OUTPUT [^\r\n]+>>>>\r?\n?`)
)
type pollLoopDetector struct {
pending map[string]string // toolUseID -> canonical read-only poll signature
lastSig string
lastRespHash string
sawSleep bool
repeats int
}
func newPollLoopDetector() *pollLoopDetector {
return &pollLoopDetector{pending: map[string]string{}}
}
func (d *pollLoopDetector) onToolUse(toolUseID, toolName, inputJSON string) {
if d == nil {
return
}
if toolName == "Sleep" {
d.sawSleep = true
return
}
if toolName == "Bash" {
var in struct {
Command string `json:"command"`
}
_ = json.Unmarshal([]byte(inputJSON), &in)
cmd := strings.TrimSpace(in.Command)
if bashSleepRe.MatchString(cmd) {
d.sawSleep = true
if bashOnlySleepRe.MatchString(cmd) {
return
}
}
if cmd == "" || bashMutateHintRe.MatchString(cmd) {
d.reset()
return
}
d.pending[toolUseID] = "Bash:" + strings.Join(strings.Fields(cmd), " ")
return
}
if toolName == "WebFetch" {
var in struct {
URL string `json:"url"`
Method string `json:"method"`
}
_ = json.Unmarshal([]byte(inputJSON), &in)
m := strings.ToUpper(strings.TrimSpace(in.Method))
if m != "" && m != "GET" && m != "HEAD" {
d.reset()
return
}
d.pending[toolUseID] = "WebFetch:" + strings.TrimSpace(in.URL)
return
}
// Other tools (e.g. ask_operator, record_fact) reset polling streak unless pure read.
d.reset()
}
func (d *pollLoopDetector) onToolResult(toolUseID, output string, isError bool) bool {
if d == nil {
return false
}
sig, ok := d.pending[toolUseID]
delete(d.pending, toolUseID)
if !ok || isError {
return false
}
normOut := strings.TrimSpace(untrustedFenceRe.ReplaceAllString(output, ""))
h := sha256.Sum256([]byte(normOut))
respHash := hex.EncodeToString(h[:])
if sig == d.lastSig && respHash == d.lastRespHash {
if d.sawSleep {
d.repeats++
d.sawSleep = false
if d.repeats >= pollLoopRepeatThreshold {
return true
}
}
return false
}
d.lastSig = sig
d.lastRespHash = respHash
d.repeats = 1
d.sawSleep = false
return false
}
func (d *pollLoopDetector) reset() {
d.lastSig = ""
d.lastRespHash = ""
d.repeats = 0
d.sawSleep = false
}
+72
View File
@@ -0,0 +1,72 @@
package agent
import (
"testing"
)
func TestPollLoopDetector(t *testing.T) {
cases := []struct {
name string
steps []struct {
id string
tool string
input string
output string
isError bool
want bool
}
}{
{
name: "three_identical_webfetch_polls_interleaved_with_sleep_triggers",
steps: []struct {
id, tool, input, output string
isError, want bool
}{
{id: "1", tool: "WebFetch", input: `{"url":"https://a.ctf/api/v1/estate"}`, output: `{"records":173}`},
{id: "s1", tool: "Sleep", input: `{"seconds":60}`, output: "slept"},
{id: "2", tool: "WebFetch", input: `{"url":"https://a.ctf/api/v1/estate"}`, output: `{"records":173}`},
{id: "s2", tool: "Sleep", input: `{"seconds":60}`, output: "slept"},
{id: "3", tool: "WebFetch", input: `{"url":"https://a.ctf/api/v1/estate"}`, output: `{"records":173}`, want: true},
},
},
{
name: "bash_curl_get_and_bash_sleep_triggers_on_third_repeat",
steps: []struct {
id, tool, input, output string
isError, want bool
}{
{id: "1", tool: "Bash", input: `{"command":"curl -s https://a.ctf/status"}`, output: "churned"},
{id: "s1", tool: "Bash", input: `{"command":"sleep 30"}`, output: ""},
{id: "2", tool: "Bash", input: `{"command":"curl -s https://a.ctf/status"}`, output: "churned"},
{id: "s2", tool: "Bash", input: `{"command":"sleep 30"}`, output: ""},
{id: "3", tool: "Bash", input: `{"command":"curl -s https://a.ctf/status"}`, output: "churned", want: true},
},
},
{
name: "changing_response_body_resets_streak",
steps: []struct {
id, tool, input, output string
isError, want bool
}{
{id: "1", tool: "WebFetch", input: `{"url":"https://a.ctf/status"}`, output: "v1"},
{id: "s1", tool: "Sleep", input: `{"seconds":10}`, output: "ok"},
{id: "2", tool: "WebFetch", input: `{"url":"https://a.ctf/status"}`, output: "v2"},
{id: "s2", tool: "Sleep", input: `{"seconds":10}`, output: "ok"},
{id: "3", tool: "WebFetch", input: `{"url":"https://a.ctf/status"}`, output: "v2", want: false},
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
d := newPollLoopDetector()
for _, st := range tc.steps {
d.onToolUse(st.id, st.tool, st.input)
got := d.onToolResult(st.id, st.output, st.isError)
if got != st.want {
t.Fatalf("step %s (%s): got triggered=%v, want %v", st.id, st.tool, got, st.want)
}
}
})
}
}
+2
View File
@@ -51,6 +51,8 @@ var (
"This Worker's claim on the intent expired (no heartbeat reached the database within the claim TTL) and another Worker took the intent over, so its heartbeat was rejected. This run was cancelled and its result is discarded; the intent now belongs to the new claimer")
AbortWorkFinished = cause("work_finished", "Worker finished normally, context freed",
"The Worker finished normally, and the engine released its context resources in detachWork. This is not an interruption; if it appears in an interruption message, the cancel and finish events raced")
AbortOperatorHandoff = cause("operator_handoff", "Intent paused for operator input",
"The intent paused and handed off to the operator; waiting for the operator's reply to resume")
AbortPausedRaceGuard = cause("paused_race_guard", "Refused a new run while task is paused",
"While the task is paused, the engine refuses to issue a new execution context, preventing a race between claim and pause from letting a Worker keep starting; already-claimed intents return to frontier")
+12 -2
View File
@@ -35,6 +35,9 @@ func captureRun(ctx context.Context, opts agentcore.Options, input string, emit
// multiple prompts on the SAME conversation (e.g. a settlement round that reuses
// the worker's accumulated context after the main run hit max_turns).
func captureRunSession(ctx context.Context, s *agentcore.Session, input string, emit func(db.Activity)) (string, harness.TerminalReason, error) {
ctx, cancelPoll := context.WithCancelCause(ctx)
defer cancelPoll(nil)
pollDet := newPollLoopDetector()
ctx, auditTrace := intercept.WithTrace(ctx, input, approvalHistory(s.Messages()))
defer auditTrace.Finish()
// Observe each model call's stop reason, so a provider refusal is reported as
@@ -85,7 +88,7 @@ func captureRunSession(ctx context.Context, s *agentcore.Session, input string,
flush()
if ctx.Err() != nil { // engine/user cancellation, not a provider failure
sum, detail := terminalText(ctx, &harness.Terminal{Reason: reason, Err: ctx.Err()}, lastTool)
rec(activityWithUsage(db.Activity{Kind: "result", Summary: firstLine(sum, 400), Detail: detail}, lastUsage))
rec(activityWithUsage(db.Activity{Kind: "result", IsError: false, Summary: firstLine(sum, 400), Detail: detail}, lastUsage))
return finalText, reason, ctx.Err()
}
rec(activityWithUsage(db.Activity{Kind: "result", IsError: true, Summary: "execution error: " + err.Error(), Detail: err.Error()}, lastUsage))
@@ -101,6 +104,7 @@ func captureRunSession(ctx context.Context, s *agentcore.Session, input string,
in := string(ev.ToolUse.Input)
lastTool.start(ev.ToolUse.ID, ev.ToolUse.Name, in)
auditTrace.Start(ev.ToolUse.ID, ev.ToolUse.Name, ev.ToolUse.Input)
pollDet.onToolUse(ev.ToolUse.ID, ev.ToolUse.Name, in)
rec(db.Activity{Kind: "tool_use", Tool: ev.ToolUse.Name, ToolUseID: ev.ToolUse.ID,
Summary: ev.ToolUse.Name + " " + firstLine(in, 200), Detail: in})
case harness.KindToolResult:
@@ -113,6 +117,10 @@ func captureRunSession(ctx context.Context, s *agentcore.Session, input string,
auditTrace.Complete(ev.ToolResult.ToolUseID, out, ev.ToolResult.IsError)
rec(db.Activity{Kind: "tool_result", Tool: toolNames[ev.ToolResult.ToolUseID], ToolUseID: ev.ToolResult.ToolUseID,
IsError: ev.ToolResult.IsError, Summary: firstLine(out, 200), Detail: out})
if pollDet.onToolResult(ev.ToolResult.ToolUseID, out, ev.ToolResult.IsError) {
cancelPoll(ErrPollLoopDetected)
return finalText, reason, ErrPollLoopDetected
}
case harness.KindText:
addDelta("text", ev.Text)
case harness.KindThinking:
@@ -148,7 +156,9 @@ func captureRunSession(ctx context.Context, s *agentcore.Session, input string,
sum, detail = terminalText(ctx, ev.Terminal, lastTool)
}
u := ev.Terminal.Usage // cumulative token usage for this session
rec(db.Activity{Kind: "result", IsError: ev.Terminal.Err != nil,
code, _, _, hasAbort := AbortReason(ctx)
isErr := ev.Terminal.Err != nil && !(hasAbort && code == "operator_handoff")
rec(db.Activity{Kind: "result", IsError: isErr,
Summary: firstLine(sum, 400), Detail: detail,
InputTokens: &u.InputTokens, OutputTokens: &u.OutputTokens,
CacheReadTokens: &u.CacheReadTokens, CacheWriteTokens: &u.CacheWriteTokens})
+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)
}
})
}
}
+317
View File
@@ -0,0 +1,317 @@
package agent
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log/slog"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"github.com/Autumn-27/artex/db"
)
// findingFingerprintMatch is a deterministic duplicate hit against an already
// registered finding (#473), complementing the advisory LLM triage pass.
type findingFingerprintMatch struct {
FindingID int64
NodeID int64
Fingerprint string
}
var (
fpURLRe = regexp.MustCompile(`(?i)\bhttps?://[^\s"'<>\]\)]+`)
fpMethodPathRe = regexp.MustCompile(`(?i)\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(/[^\s"'<>\]\)]+)`)
fpBarePathRe = regexp.MustCompile(`(?:^|[\s(\["'])(/[a-zA-Z0-9._~/%{}:-]+(?:\?[a-zA-Z0-9._~=&%-]+)?)`)
fpParamRe = regexp.MustCompile(`(?i)\b(?:param(?:eter)?|field|query\s+param(?:eter)?)\s*(?:=|:|\s+)\s*["'\x60]?([a-zA-Z_][a-zA-Z0-9_.-]{0,63})["'\x60]?`)
fpNonAlnumRe = regexp.MustCompile(`[^a-z0-9]+`)
)
// FindingFingerprint returns a deterministic SHA-256 fingerprint for a finding
// from three required axes (#473):
// 1. normalized vulnerability class / CWE,
// 2. canonical asset IDs (sorted/deduplicated) or URL host,
// 3. normalized affected endpoint path and/or parameter name.
//
// If any of the three axes cannot be extracted unambiguously, it returns "" so
// callers fall through to LLM triage / normal registration without false
// collisions.
func FindingFingerprint(in db.RecordFindingInput) string {
vulnClass := normalizeFingerprintToken(in.VulnClass)
if vulnClass == "" {
return ""
}
corpus := strings.Join([]string{in.Name, in.Summary, in.Evidence}, "\n")
assetKey := canonicalFindingAssetKey(in.AssetIDs, corpus)
if assetKey == "" {
return ""
}
endpointKey := canonicalFindingEndpointKey(corpus)
if endpointKey == "" {
return ""
}
h := sha256.Sum256([]byte(vulnClass + "\x00" + assetKey + "\x00" + endpointKey))
return "fp:" + hex.EncodeToString(h[:16])
}
func normalizeFingerprintToken(s string) string {
s = strings.ToLower(strings.TrimSpace(s))
if s == "" {
return ""
}
s = fpNonAlnumRe.ReplaceAllString(s, "_")
return strings.Trim(s, "_")
}
func canonicalFindingAssetKey(assetIDs []int64, corpus string) string {
if len(assetIDs) > 0 {
seen := make(map[int64]struct{}, len(assetIDs))
ids := make([]int64, 0, len(assetIDs))
for _, id := range assetIDs {
if id > 0 {
if _, ok := seen[id]; !ok {
seen[id] = struct{}{}
ids = append(ids, id)
}
}
}
if len(ids) > 0 {
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
parts := make([]string, len(ids))
for i, id := range ids {
parts[i] = strconv.FormatInt(id, 10)
}
return "ids:" + strings.Join(parts, ",")
}
}
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
raw = strings.TrimRight(raw, ".,;:!?)")
u, err := url.Parse(raw)
if err != nil || strings.TrimSpace(u.Host) == "" {
continue
}
return "host:" + strings.ToLower(strings.TrimSuffix(u.Host, "."))
}
return ""
}
func canonicalFindingEndpointKey(corpus string) string {
var pathSig string
var paramNames []string
// Prefer explicit URLs first so scheme/host are stripped cleanly.
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
raw = strings.TrimRight(raw, ".,;:!?)")
u, err := url.Parse(raw)
if err != nil {
continue
}
p := normalizeEndpointPath(u.Path)
if p != "" {
pathSig = p
paramNames = append(paramNames, sortedQueryParamNames(u.RawQuery)...)
break
}
}
if pathSig == "" {
if m := fpMethodPathRe.FindStringSubmatch(corpus); len(m) == 2 {
pathSig, paramNames = splitPathAndQuery(m[1])
}
}
if pathSig == "" {
for _, m := range fpBarePathRe.FindAllStringSubmatch(corpus, 8) {
if len(m) != 2 {
continue
}
candidate := strings.TrimRight(m[1], ".,;:!?)")
// Ignore common filesystem/OS paths unless nothing else; require
// at least one route character after '/'.
if len(candidate) <= 1 || strings.HasPrefix(candidate, "//") {
continue
}
pathSig, paramNames = splitPathAndQuery(candidate)
if pathSig != "" {
break
}
}
}
for _, m := range fpParamRe.FindAllStringSubmatch(corpus, 4) {
if len(m) == 2 {
if name := strings.ToLower(strings.TrimSpace(m[1])); name != "" {
paramNames = append(paramNames, name)
}
}
}
paramNames = dedupSortedStrings(paramNames)
if pathSig == "" && len(paramNames) == 0 {
return ""
}
if len(paramNames) == 0 {
return "path:" + pathSig
}
return "path:" + pathSig + "|params:" + strings.Join(paramNames, ",")
}
func splitPathAndQuery(raw string) (string, []string) {
raw = strings.TrimRight(strings.TrimSpace(raw), ".,;:!?)")
pathPart, queryPart, _ := strings.Cut(raw, "?")
return normalizeEndpointPath(pathPart), sortedQueryParamNames(queryPart)
}
func normalizeEndpointPath(p string) string {
p = strings.TrimSpace(p)
if p == "" || p == "/" {
return ""
}
p = strings.ToLower(p)
for strings.Contains(p, "//") {
p = strings.ReplaceAll(p, "//", "/")
}
p = strings.TrimRight(p, "/")
if p == "" {
return ""
}
return p
}
func sortedQueryParamNames(rawQuery string) []string {
if strings.TrimSpace(rawQuery) == "" {
return nil
}
var names []string
for _, pair := range strings.Split(rawQuery, "&") {
if pair == "" {
continue
}
k, _, _ := strings.Cut(pair, "=")
if k = strings.ToLower(strings.TrimSpace(k)); k != "" {
names = append(names, k)
}
}
return dedupSortedStrings(names)
}
func dedupSortedStrings(in []string) []string {
if len(in) == 0 {
return nil
}
seen := make(map[string]struct{}, len(in))
out := make([]string, 0, len(in))
for _, s := range in {
if _, ok := seen[s]; !ok {
seen[s] = struct{}{}
out = append(out, s)
}
}
sort.Strings(out)
return out
}
func isDismissedFindingStatus(status string) bool {
switch strings.ToLower(strings.TrimSpace(status)) {
case "false_positive", "ignored", "duplicate":
return true
default:
return false
}
}
// fingerprintDuplicate checks already registered active findings in this task,
// its directly related tasks, and tasks sharing the same assets for an exact
// deterministic fingerprint match (#473).
func (t *ToolSet) fingerprintDuplicate(in db.RecordFindingInput) (findingFingerprintMatch, bool) {
if t.ts == nil {
return findingFingerprintMatch{}, false
}
candFP := FindingFingerprint(in)
if candFP == "" {
return findingFingerprintMatch{}, false
}
nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500)
if err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: failed to list findings", "err", err)
return findingFingerprintMatch{}, false
}
if len(in.AssetIDs) > 0 {
if cross, err := t.ts.FindingsSharingAssets(in.AssetIDs, t.taskID, 100); err == nil {
seen := make(map[int64]bool, len(nodes))
for _, n := range nodes {
if n != nil {
seen[n.ID] = true
}
}
for _, n := range cross {
if n != nil && !seen[n.ID] {
nodes = append(nodes, n)
}
}
}
}
if len(nodes) == 0 {
return findingFingerprintMatch{}, false
}
if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: populate finding ids failed", "err", err)
return findingFingerprintMatch{}, false
}
findingIDs := make([]int64, 0, len(nodes))
for _, n := range nodes {
if n != nil && n.FindingID > 0 {
findingIDs = append(findingIDs, n.FindingID)
}
}
if len(findingIDs) == 0 {
return findingFingerprintMatch{}, false
}
meta, err := t.ts.FindingDedupMetadata(findingIDs)
if err != nil {
slog.Warn("[dedup] fingerprint lookup skipped: load finding metadata failed", "err", err)
return findingFingerprintMatch{}, false
}
// Check newest first for deterministic match selection.
sort.SliceStable(nodes, func(i, j int) bool { return nodes[i].ID > nodes[j].ID })
for _, n := range nodes {
if n == nil || n.FindingID <= 0 {
continue
}
m := meta[n.FindingID]
if isDismissedFindingStatus(m.Status) {
continue
}
var payload struct {
VulnClass string `json:"vulnclass"`
Name string `json:"name"`
Summary string `json:"summary"`
Status string `json:"status"`
Evidence struct {
PoC string `json:"poc"`
} `json:"evidence"`
}
if json.Unmarshal(n.Payload, &payload) != nil {
continue
}
if isDismissedFindingStatus(payload.Status) {
continue
}
existingFP := FindingFingerprint(db.RecordFindingInput{
VulnClass: payload.VulnClass,
Name: payload.Name,
Summary: payload.Summary,
Evidence: payload.Evidence.PoC,
AssetIDs: m.AssetIDs,
})
if existingFP != "" && existingFP == candFP {
slog.Info("[dedup] deterministic fingerprint matched existing finding",
"finding_id", n.FindingID, "node_id", n.ID, "fingerprint", candFP)
return findingFingerprintMatch{
FindingID: n.FindingID,
NodeID: n.ID,
Fingerprint: candFP,
}, true
}
}
return findingFingerprintMatch{}, false
}
+168
View File
@@ -0,0 +1,168 @@
package agent
import (
"context"
"encoding/json"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestFindingFingerprintDeterminismAndDistinctness(t *testing.T) {
base := db.RecordFindingInput{
VulnClass: "SQLi",
Name: "SQL Injection on search",
Summary: "GET https://app.example.test/api/v1/products/search?q=1&sort=asc is injectable",
AssetIDs: []int64{42, 10},
}
sameReordered := db.RecordFindingInput{
VulnClass: "sqli",
Name: "Re-verified SQLi",
Summary: "Confirmed again on https://APP.EXAMPLE.TEST/api/v1/products/search/?sort=desc&q=2",
AssetIDs: []int64{10, 42, 10},
}
fp1 := FindingFingerprint(base)
fp2 := FindingFingerprint(sameReordered)
if fp1 == "" || fp1 != fp2 {
t.Fatalf("equivalent findings must yield identical non-empty fingerprint: fp1=%q fp2=%q", fp1, fp2)
}
// Distinct endpoint on same host/asset must produce a different fingerprint.
diffEndpoint := base
diffEndpoint.Summary = "GET https://app.example.test/api/v1/users/search?q=1 is injectable"
if fp3 := FindingFingerprint(diffEndpoint); fp3 == "" || fp3 == fp1 {
t.Fatalf("different endpoint must yield different fingerprint: fp1=%q fp3=%q", fp1, fp3)
}
// Distinct parameter on same path must produce a different fingerprint.
diffParam := base
diffParam.Summary = "GET https://app.example.test/api/v1/products/search?category=1 is injectable"
if fp4 := FindingFingerprint(diffParam); fp4 == "" || fp4 == fp1 {
t.Fatalf("different parameter must yield different fingerprint: fp1=%q fp4=%q", fp1, fp4)
}
// Distinct vulnerability class on same endpoint must produce a different fingerprint.
diffClass := base
diffClass.VulnClass = "XSS"
if fp5 := FindingFingerprint(diffClass); fp5 == "" || fp5 == fp1 {
t.Fatalf("different vulnclass must yield different fingerprint: fp1=%q fp5=%q", fp1, fp5)
}
// Missing endpoint or missing asset/host returns "" (no false collision).
noEndpoint := db.RecordFindingInput{VulnClass: "SQLi", Summary: "generic database error", AssetIDs: []int64{10}}
if fp := FindingFingerprint(noEndpoint); fp != "" {
t.Fatalf("missing endpoint must return empty fingerprint, got %q", fp)
}
noAssetOrHost := db.RecordFindingInput{VulnClass: "SQLi", Summary: "GET /login?user=a is injectable"}
if fp := FindingFingerprint(noAssetOrHost); fp != "" {
t.Fatalf("missing asset/host must return empty fingerprint, got %q", fp)
}
}
type countingTriageClient struct {
calls atomic.Int64
ans DuplicateAnswer
}
func (c *countingTriageClient) Duplicate(_ context.Context, _ TriageCandidate, _ []TriageCandidate) (DuplicateAnswer, error) {
c.calls.Add(1)
return c.ans, nil
}
func TestReportFindingFingerprintDedupWithoutTriageClientAndComplementsTriage(t *testing.T) {
d := testDB(t)
t.Cleanup(func() { _ = d.Close() })
task, err := d.CreateTaskWithOptions("fingerprint dedup", "verify deterministic dedup", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = d.DeleteFindingsByTask(task.ID)
_ = d.DeleteTask(task.ID)
})
ts := NewToolSet(d.Exploration(task.ExplorationID), "worker-1")
ts.SetTaskID(task.ID)
// 1. First registration with URL host + vulnclass + endpoint succeeds.
first := `{"vulnclass":"SQLi","severity":"high","name":"Login SQLi","summary":"POST https://target.lab.local/api/login?user=admin vulnerable to boolean SQLi"}`
if res := callGuardTool(t, ts.addFinding(), first); res.IsError {
t.Fatalf("first report_finding failed: %s", res.Flatten())
}
nodes := findingNodes(t, ts)
if len(nodes) != 1 {
t.Fatalf("expected 1 finding after first report, got %d", len(nodes))
}
origFID, origNID := nodes[0].FindingID, nodes[0].ID
// 2. Re-verification with reworded summary on the same host+endpoint+param+class
// is suppressed deterministically even with NO triage client configured.
triageMock := &countingTriageClient{}
ts.SetTriageClient(triageMock)
dup := `{"vulnclass":"sqli","severity":"high","name":"Re-verified login SQLi","summary":"Re-confirmed SQL injection on https://TARGET.LAB.LOCAL/api/login/?user=test"}`
res := callGuardTool(t, ts.addFinding(), dup)
if res.IsError {
t.Fatalf("duplicate suppression returned error: %s", res.Flatten())
}
text := res.Flatten()
if !strings.Contains(text, "duplicate_not_registered") || !strings.Contains(text, `"dedup_source":"fingerprint"`) {
t.Fatalf("expected deterministic fingerprint suppression, got: %s", text)
}
if triageMock.calls.Load() != 0 {
t.Fatalf("fingerprint hit must short-circuit before LLM triage, got %d triage calls", triageMock.calls.Load())
}
var ans struct {
DuplicateOfFindingID int64 `json:"duplicate_of_finding_id"`
DuplicateOfNodeID int64 `json:"duplicate_of_finding_node_id"`
Fingerprint string `json:"fingerprint"`
}
if err := json.Unmarshal([]byte(text[strings.Index(text, "{"):]), &ans); err != nil {
t.Fatalf("parse suppression json: %v (%s)", err, text)
}
if ans.DuplicateOfFindingID != origFID || ans.DuplicateOfNodeID != origNID || !strings.HasPrefix(ans.Fingerprint, "fp:") {
t.Fatalf("unexpected suppression payload: %+v (want finding=%d node=%d)", ans, origFID, origNID)
}
if !strings.Contains(text, "finding_id="+strconv.FormatInt(origNID, 10)) {
t.Fatalf("suppression note must reference node id %d: %s", origNID, text)
}
if got := len(findingNodes(t, ts)); got != 1 {
t.Fatalf("expected still 1 finding after suppression, got %d", got)
}
// 3. A distinct endpoint on the same host is NOT suppressed by fingerprint and
// falls through to LLM triage (which returns distinct -> registers).
distinct := `{"vulnclass":"sqli","severity":"high","name":"Search SQLi","summary":"GET https://target.lab.local/api/search?q=abc vulnerable to UNION SQLi"}`
if res := callGuardTool(t, ts.addFinding(), distinct); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("distinct endpoint should register, got: %s", res.Flatten())
}
if triageMock.calls.Load() != 1 {
t.Fatalf("non-matching fingerprint must fall through to LLM triage, got %d calls", triageMock.calls.Load())
}
if got := len(findingNodes(t, ts)); got != 2 {
t.Fatalf("expected 2 findings after distinct endpoint, got %d", got)
}
// 4. force_register=true overrides deterministic fingerprint suppression.
forced := `{"force_register":true,"vulnclass":"sqli","severity":"high","name":"Distinct root cause on login","summary":"POST https://target.lab.local/api/login?user=admin second bug"}`
if res := callGuardTool(t, ts.addFinding(), forced); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("force_register must override fingerprint suppression, got: %s", res.Flatten())
}
if got := len(findingNodes(t, ts)); got != 3 {
t.Fatalf("expected 3 findings after force_register, got %d", got)
}
// 5. Dismissed (false_positive) findings must not suppress a new registration.
if _, err := d.Exec(`UPDATE findings SET status='false_positive' WHERE task_id=$1`, task.ID); err != nil {
t.Fatal(err)
}
ts.SetTriageClient(nil)
if res := callGuardTool(t, ts.addFinding(), dup); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
t.Fatalf("false_positive finding must not suppress re-discovery, got: %s", res.Flatten())
}
if got := len(findingNodes(t, ts)); got != 4 {
t.Fatalf("expected 4 findings after false_positive re-discovery, got %d", got)
}
}
+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
}
}
+6 -2
View File
@@ -64,7 +64,7 @@ func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (st
var sum string
if aborted {
_, short, _, ok := AbortReason(ctx)
code, short, _, ok := AbortReason(ctx)
if !ok {
short = "cancellation reason unavailable"
}
@@ -75,7 +75,11 @@ func terminalText(ctx context.Context, term *harness.Terminal, tr *runTrace) (st
case harness.ReasonAbortedTools:
stage = "the tool execution stage"
}
sum = "(run interrupted: " + short + "; stopped during " + stage + progressSuffix(term, tr) + ", unfinished)"
if code == "operator_handoff" {
sum = "(paused for operator input: " + short + "; waiting for operator reply)"
} else {
sum = "(run interrupted: " + short + "; stopped during " + stage + progressSuffix(term, tr) + ", unfinished)"
}
} else if reason == harness.ReasonMaxTurns || reason == harness.ReasonTimeout {
sum = "(run budget cap reached (" + string(reason) + "); wrap-up wrote back facts" + progressSuffix(term, tr) + "; no text summary this run)"
} else if refused {
+54 -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
@@ -1630,6 +1652,20 @@ func (t *ToolSet) addFinding() actool.CoreTool {
// retry hits the same check and is suppressed again.
if a.ForceRegister {
slog.Info("[triage] override: force_register set, registering without duplicate check", "candidate", a.Name)
} else if dup, ok := t.fingerprintDuplicate(input); ok {
res := map[string]any{
"duplicate_of_finding_id": dup.FindingID,
"duplicate_of_finding_node_id": dup.NodeID,
"dedup_source": "fingerprint",
"fingerprint": dup.Fingerprint,
"evidence_status": "duplicate_not_registered",
"note": fmt.Sprintf("Deterministic fingerprint (%s) matched already registered finding_id %d (exploration node %d), so no new finding was created. "+
"To extend that finding with new evidence, call update_finding_report with finding_id=%d (it addresses the NODE id, not the findings-table id). "+
"If the new evidence is in fact a distinct defect (different endpoint, parameter or root cause), call report_finding again with force_register=true.",
dup.Fingerprint, dup.FindingID, dup.NodeID, dup.NodeID),
}
raw, _ := json.Marshal(res)
return actool.Text(fmt.Sprintf("finding matched existing finding_id %d (node %d, fingerprint %s) — not registered again\n%s", dup.FindingID, dup.NodeID, dup.Fingerprint, raw)), nil
} else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
res := map[string]any{
"duplicate_of_finding_id": ans.DuplicateOf,
@@ -1682,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
})
+53
View File
@@ -1,6 +1,7 @@
package db
import (
"encoding/json"
"strings"
)
@@ -69,3 +70,55 @@ func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask i
}
return out, rows.Err()
}
// FindingDedupMeta carries the finding metadata needed by deterministic
// fingerprint deduplication (#473) without requiring any schema migration.
type FindingDedupMeta struct {
AssetIDs []int64
Status string
}
// FindingDedupMetadata returns asset_ids and status keyed by finding id.
func (s *ExplorationStore) FindingDedupMetadata(findingIDs []int64) (map[int64]FindingDedupMeta, error) {
out := make(map[int64]FindingDedupMeta, len(findingIDs))
if len(findingIDs) == 0 {
return out, nil
}
placeholders := make([]string, 0, len(findingIDs))
args := make([]any, 0, len(findingIDs))
seen := make(map[int64]struct{}, len(findingIDs))
for _, id := range findingIDs {
if id <= 0 {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
args = append(args, id)
placeholders = append(placeholders, "$"+itoa(int64(len(args))))
}
if len(args) == 0 {
return out, nil
}
rows, err := s.db.Query(
`SELECT id, COALESCE(asset_ids, '[]'::jsonb), COALESCE(status, 'pending') FROM findings WHERE id IN (`+strings.Join(placeholders, ",")+`)`,
args...,
)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id int64
var rawAssets []byte
var status string
if err := rows.Scan(&id, &rawAssets, &status); err != nil {
return nil, err
}
var aids []int64
_ = json.Unmarshal(rawAssets, &aids)
out[id] = FindingDedupMeta{AssetIDs: aids, Status: status}
}
return out, rows.Err()
}
+6
View File
@@ -43,6 +43,9 @@ func (d *DB) RecentLogs(limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
@@ -70,6 +73,9 @@ func (d *DB) ListLogsBefore(beforeID int64, limit int) ([]*DBLog, error) {
}
out = append(out, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
// Reverse to oldest-first
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
+163
View File
@@ -0,0 +1,163 @@
package db
import (
"context"
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
)
// RetargetResult summarizes the rows updated when retargeting a task to a new
// instance base URL.
type RetargetResult struct {
TaskID int64 `json:"task_id"`
OldHost string `json:"old_host"`
NewHost string `json:"new_host"`
NewBaseURL string `json:"new_base_url"`
GoalsUpdated int `json:"goals_updated"`
ConstraintsUpdated int `json:"constraints_updated"`
ScopesUpdated int `json:"scopes_updated"`
UpdatedGoal string `json:"updated_goal"`
}
func replaceHostCaseInsensitive(text, oldHost, newHost string) (string, bool) {
if oldHost == "" || newHost == "" || strings.EqualFold(oldHost, newHost) {
return text, false
}
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(oldHost))
if !re.MatchString(text) {
return text, false
}
return re.ReplaceAllString(text, newHost), true
}
// RetargetTask updates tasks.goal, explorations.goal, open goal node payloads,
// task_constraints, and task_scope from oldHost to newBaseURL in a single
// transaction (no schema migration).
func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL string) (*RetargetResult, error) {
u, err := url.Parse(strings.TrimSpace(newBaseURL))
if err != nil || u.Hostname() == "" {
return nil, fmt.Errorf("invalid new base URL %q", newBaseURL)
}
oldH := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(oldHost), "."))
newH := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(u.Hostname()), "."))
if oldH == "" {
return nil, fmt.Errorf("old_host is required")
}
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
var expID int64
var curGoal string
if err := tx.QueryRowContext(ctx, `SELECT exploration_id, goal FROM tasks WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskID).Scan(&expID, &curGoal); err != nil {
return nil, err
}
newGoal, replaced := replaceHostCaseInsensitive(curGoal, oldH, newH)
if !replaced && !strings.Contains(strings.ToLower(curGoal), newH) {
newGoal = strings.TrimSpace(curGoal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
}
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET goal=$1 WHERE id=$2`, newGoal, taskID); err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `UPDATE explorations SET goal=$1 WHERE id=$2`, newGoal, expID); err != nil {
return nil, err
}
res := &RetargetResult{
TaskID: taskID,
OldHost: oldH,
NewHost: newH,
NewBaseURL: strings.TrimSpace(newBaseURL),
UpdatedGoal: newGoal,
}
// Update open goal nodes.
rows, err := tx.QueryContext(ctx, `SELECT id, payload FROM exploration_nodes WHERE exploration_id=$1 AND kind=$2 AND state='open'`, expID, KindGoal)
if err != nil {
return nil, err
}
type goalUpd struct {
id int64
payload string
}
var goalUpds []goalUpd
for rows.Next() {
var id int64
var raw []byte
if err := rows.Scan(&id, &raw); err != nil {
rows.Close()
return nil, err
}
var p map[string]any
if json.Unmarshal(raw, &p) == nil {
if txt, _ := p["text"].(string); txt != "" {
if updated, ok := replaceHostCaseInsensitive(txt, oldH, newH); ok {
p["text"] = updated
b, _ := json.Marshal(p)
goalUpds = append(goalUpds, goalUpd{id: id, payload: string(b)})
}
}
}
}
rows.Close()
for _, gu := range goalUpds {
if _, err := tx.ExecContext(ctx, `UPDATE exploration_nodes SET payload=$1 WHERE id=$2`, gu.payload, gu.id); err != nil {
return nil, err
}
res.GoalsUpdated++
}
// Update task_constraints referencing oldH.
cRows, err := tx.QueryContext(ctx, `SELECT id, text FROM task_constraints WHERE exploration_id=$1`, expID)
if err != nil {
return nil, err
}
type cUpd struct {
id int64
text string
}
var cUpds []cUpd
for cRows.Next() {
var id int64
var txt string
if err := cRows.Scan(&id, &txt); err != nil {
cRows.Close()
return nil, err
}
if updated, ok := replaceHostCaseInsensitive(txt, oldH, newH); ok {
cUpds = append(cUpds, cUpd{id: id, text: updated})
}
}
cRows.Close()
for _, cu := range cUpds {
if _, err := tx.ExecContext(ctx, `UPDATE task_constraints SET text=$1 WHERE id=$2`, cu.text, cu.id); err != nil {
return nil, err
}
res.ConstraintsUpdated++
}
// Replace task_scope entries matching oldH with newH.
delRes, err := tx.ExecContext(ctx, `DELETE FROM task_scope WHERE task_id=$1 AND LOWER(value)=$2`, taskID, oldH)
if err != nil {
return nil, err
}
if n, _ := delRes.RowsAffected(); n > 0 {
res.ScopesUpdated += int(n)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO task_scope(task_id, kind, value, source, reason) VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance') ON CONFLICT DO NOTHING`, taskID, newH); err != nil {
return nil, err
}
res.ScopesUpdated++
if err := tx.Commit(); err != nil {
return nil, err
}
return res, nil
}
+66
View File
@@ -0,0 +1,66 @@
package db
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"sync"
"testing"
"time"
)
type midStreamErrDriver struct{}
type midStreamErrConn struct{}
type midStreamErrRows struct{ n int }
func (midStreamErrDriver) Open(string) (driver.Conn, error) { return midStreamErrConn{}, nil }
func (midStreamErrConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("unused") }
func (midStreamErrConn) Close() error { return nil }
func (midStreamErrConn) Begin() (driver.Tx, error) { return nil, errors.New("unused") }
func (midStreamErrConn) QueryContext(_ context.Context, _ string, _ []driver.NamedValue) (driver.Rows, error) {
return &midStreamErrRows{}, nil
}
func (r *midStreamErrRows) Columns() []string {
return []string{"id", "created_at", "level", "tag", "text"}
}
func (r *midStreamErrRows) Close() error { return nil }
func (r *midStreamErrRows) Next(dest []driver.Value) error {
if r.n == 0 {
r.n++
dest[0] = int64(1)
dest[1] = time.Now()
dest[2] = "info"
dest[3] = "test"
dest[4] = "first row"
return nil
}
if r.n == 1 {
r.n++
return errors.New("simulated mid-stream connection drop")
}
return io.EOF
}
var registerMidStreamErrDriverOnce sync.Once
func TestLogsMethodsReturnRowsErr(t *testing.T) {
registerMidStreamErrDriverOnce.Do(func() {
sql.Register("artex_test_mid_stream_err", midStreamErrDriver{})
})
raw, err := sql.Open("artex_test_mid_stream_err", "")
if err != nil {
t.Fatal(err)
}
defer raw.Close()
d := &DB{DB: raw}
if _, err := d.RecentLogs(10); err == nil {
t.Fatal("RecentLogs returned nil error on mid-stream rows.Next failure")
}
if _, err := d.ListLogsBefore(100, 10); err == nil {
t.Fatal("ListLogsBefore returned nil error on mid-stream rows.Next failure")
}
}
+12
View File
@@ -295,6 +295,12 @@ LIMIT 1`, taskID).Scan(&dependent)
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
@@ -664,6 +670,12 @@ func (d *DB) snapshotTaskArchive(taskID int64, llmRecords io.Writer) (*TaskArchi
}
sources = append(sources, id)
}
// Next closes rows on an error, after which Close returns nil: only Err
// reports a failure partway through the result set.
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
if err := rows.Close(); err != nil {
return nil, err
}
+1 -1
View File
@@ -80,4 +80,4 @@ require (
modernc.org/memory v1.11.0 // indirect
)
replace github.com/Autumn-27/norma => github.com/BaaRai/Norma v0.4.11
replace github.com/Autumn-27/norma => github.com/BaaRai/Norma v0.4.12
+2 -2
View File
@@ -1,5 +1,5 @@
github.com/BaaRai/Norma v0.4.11 h1:Z5lSRFKBDI0EzAw1YDA5iQ5GXsa9e7J19YmIe0zaVcQ=
github.com/BaaRai/Norma v0.4.11/go.mod h1:BudWrf7iHl96FgHqFr/HwN3mKYmGjJDt+xL2ZHXfFZw=
github.com/BaaRai/Norma v0.4.12 h1:grc1RX8DTiIktXzKIgt7O831u7FdLBUCz/TSCGgmOS0=
github.com/BaaRai/Norma v0.4.12/go.mod h1:BudWrf7iHl96FgHqFr/HwN3mKYmGjJDt+xL2ZHXfFZw=
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
+7 -1
View File
@@ -222,6 +222,9 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event, cmd string) h
return g.block(ev.ToolName, systemBlockMessage("manual approval not granted (user rejected or approval timed out)"), cmd)
}
}
if err := intercept.CheckStatefulTool(ctx, ev.ToolName, ev.Input, "", ""); err != nil {
return g.block(ev.ToolName, systemBlockMessage(err.Error()), cmd)
}
return hook.Result{}
}
@@ -320,7 +323,10 @@ var reBlocked = regexp.MustCompile(`(?i)\b(403|forbidden|waf|blocked|rate.?limit
// postToolUse is the Observer failure-attribution hook (G5): it classifies tool
// results into blocked / error / ok so the planner can change strategy instead
// of giving up at a WAF.
func (g *Guard) postToolUse(_ context.Context, ev hook.Event) hook.Result {
func (g *Guard) postToolUse(ctx context.Context, ev hook.Event) hook.Result {
if !ev.IsError {
intercept.RecordStatefulReadOnly(ctx, ev.ToolName, ev.Input, "", "")
}
if ev.ToolName != "Bash" {
return hook.Result{}
}
+235
View File
@@ -0,0 +1,235 @@
package intercept
import (
"context"
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
"sync"
)
// StatefulTargetGuard enforces two per-(task, host) safety invariants on
// stateful targets, completely independent of the MITM traffic store:
// 1. Pre-mutation baseline gate: any mutating HTTP call is refused until at
// least one read-only GET/HEAD call to that task+host has completed.
// 2. Mutation lease: only one intent per task may hold the mutation lease for
// a given host at a time; read-only calls remain parallel.
type StatefulTargetGuard struct {
mu sync.Mutex
leases map[string]int64 // taskID+"\x00"+host -> holding intentID
baselines map[string]bool // taskID+"\x00"+host -> true once read-only GET completed
}
func NewStatefulTargetGuard() *StatefulTargetGuard {
return &StatefulTargetGuard{
leases: map[string]int64{},
baselines: map[string]bool{},
}
}
type statefulGuardKey struct{}
type statefulActorKey struct{}
// StatefulActor identifies the task and intent executing a tool call.
type StatefulActor struct {
TaskID string
IntentID int64
}
func WithStatefulGuard(ctx context.Context, g *StatefulTargetGuard) context.Context {
if g == nil {
return ctx
}
return context.WithValue(ctx, statefulGuardKey{}, g)
}
func StatefulGuardFromContext(ctx context.Context) *StatefulTargetGuard {
g, _ := ctx.Value(statefulGuardKey{}).(*StatefulTargetGuard)
return g
}
func WithStatefulActor(ctx context.Context, taskID string, intentID int64) context.Context {
return context.WithValue(ctx, statefulActorKey{}, StatefulActor{TaskID: taskID, IntentID: intentID})
}
func StatefulActorFromContext(ctx context.Context) (StatefulActor, bool) {
a, ok := ctx.Value(statefulActorKey{}).(StatefulActor)
return a, ok && a.TaskID != ""
}
func canonicalGuardKey(taskID, host string) string {
h := strings.ToLower(strings.TrimSpace(host))
h = strings.TrimSuffix(h, ".")
return taskID + "\x00" + h
}
// RecordBaseline records that a read-only baseline request succeeded for host
// in taskID.
func (g *StatefulTargetGuard) RecordBaseline(taskID, host string) {
if g == nil || taskID == "" || strings.TrimSpace(host) == "" {
return
}
g.mu.Lock()
g.baselines[canonicalGuardKey(taskID, host)] = true
g.mu.Unlock()
}
// HasBaseline reports whether a read-only baseline has been recorded for host
// in taskID.
func (g *StatefulTargetGuard) HasBaseline(taskID, host string) bool {
if g == nil || taskID == "" || strings.TrimSpace(host) == "" {
return false
}
g.mu.Lock()
ok := g.baselines[canonicalGuardKey(taskID, host)]
g.mu.Unlock()
return ok
}
// AcquireMutationLease acquires the per-(taskID, host) mutation lease for
// intentID (re-entrant for the same intentID). Returns false and the holding
// intentID if another intent currently holds the lease.
func (g *StatefulTargetGuard) AcquireMutationLease(taskID, host string, intentID int64) (bool, int64) {
if g == nil || taskID == "" || strings.TrimSpace(host) == "" || intentID <= 0 {
return true, 0
}
key := canonicalGuardKey(taskID, host)
g.mu.Lock()
defer g.mu.Unlock()
if holder, ok := g.leases[key]; ok && holder != 0 && holder != intentID {
return false, holder
}
g.leases[key] = intentID
return true, intentID
}
// ReleaseIntent releases all mutation leases held by (taskID, intentID).
func (g *StatefulTargetGuard) ReleaseIntent(taskID string, intentID int64) {
if g == nil || taskID == "" || intentID <= 0 {
return
}
prefix := taskID + "\x00"
g.mu.Lock()
for k, holder := range g.leases {
if strings.HasPrefix(k, prefix) && holder == intentID {
delete(g.leases, k)
}
}
g.mu.Unlock()
}
var (
mutatingMethodFlagRe = regexp.MustCompile(`(?i)(?:^|\s)(?:-X|--request)\s*=*\s*["']?(POST|PUT|PATCH|DELETE)\b`)
mutatingBodyFlagRe = regexp.MustCompile(`(?i)(?:^|\s)(?:-d|--data|--data-raw|--data-binary|--data-urlencode|-F|--form)(?:\s|=)`)
mutatingScriptCallRe = regexp.MustCompile(`(?i)(?:\.(?:post|put|patch|delete)\s*\(|http\.Post|method\s*[=:]\s*["'](?:POST|PUT|PATCH|DELETE)["']|urlopen\s*\([^)]*data\s*=)`)
scriptURLRe = regexp.MustCompile(`(?i)https?://[^\s"'<>\\)\]]+`)
)
func isMutatingHTTPMethod(method string) bool {
switch strings.ToUpper(strings.TrimSpace(method)) {
case "POST", "PUT", "PATCH", "DELETE":
return true
default:
return false
}
}
// ClassifyHTTPAction extracts target hosts and whether the action performs a
// mutating HTTP request across WebFetch, Bash/shell tools, and custom tools
// (including runScriptTool).
func ClassifyHTTPAction(toolName string, input json.RawMessage, renderedText string, explicitMethod string) (hosts []string, mutating bool) {
seen := map[string]bool{}
addHost := func(h string) {
h = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(h), "."))
if h == "" || seen[h] {
return
}
seen[h] = true
hosts = append(hosts, h)
}
if len(input) > 0 {
for _, t := range ExtractTargets(toolName, input) {
addHost(t.Host)
}
}
if renderedText != "" {
var l targetList
l.scan(renderedText)
for _, t := range l.targets {
addHost(t.Host)
}
for _, raw := range scriptURLRe.FindAllString(renderedText, 16) {
if u, err := url.Parse(raw); err == nil && u.Hostname() != "" {
addHost(u.Hostname())
}
}
}
if explicitMethod != "" {
mutating = isMutatingHTTPMethod(explicitMethod)
return hosts, mutating
}
switch toolName {
case "WebFetch":
var in struct {
Method string `json:"method"`
}
_ = json.Unmarshal(input, &in)
mutating = isMutatingHTTPMethod(in.Method)
default:
text := renderedText
if text == "" && len(input) > 0 {
text = string(input)
}
mutating = mutatingMethodFlagRe.MatchString(text) ||
mutatingBodyFlagRe.MatchString(text) ||
mutatingScriptCallRe.MatchString(text)
}
return hosts, mutating
}
// CheckStatefulTool enforces the pre-mutation baseline gate and per-(task, host)
// mutation lease using the StatefulTargetGuard and StatefulActor on ctx.
func CheckStatefulTool(ctx context.Context, toolName string, input json.RawMessage, renderedText string, explicitMethod string) error {
g := StatefulGuardFromContext(ctx)
actor, ok := StatefulActorFromContext(ctx)
if g == nil || !ok {
return nil
}
hosts, mutating := ClassifyHTTPAction(toolName, input, renderedText, explicitMethod)
if len(hosts) == 0 || !mutating {
return nil
}
for _, h := range hosts {
if !g.HasBaseline(actor.TaskID, h) {
return fmt.Errorf("pre-mutation baseline required for host %s: perform a read-only GET baseline before mutating state", h)
}
}
for _, h := range hosts {
if acquired, holder := g.AcquireMutationLease(actor.TaskID, h, actor.IntentID); !acquired {
return fmt.Errorf("mutation lease for host %s is held by intent #%d; retry after it finishes", h, holder)
}
}
return nil
}
// RecordStatefulReadOnly records a baseline snapshot for each host touched by a
// completed non-mutating HTTP call.
func RecordStatefulReadOnly(ctx context.Context, toolName string, input json.RawMessage, renderedText string, explicitMethod string) {
g := StatefulGuardFromContext(ctx)
actor, ok := StatefulActorFromContext(ctx)
if g == nil || !ok {
return
}
hosts, mutating := ClassifyHTTPAction(toolName, input, renderedText, explicitMethod)
if mutating || len(hosts) == 0 {
return
}
for _, h := range hosts {
g.RecordBaseline(actor.TaskID, h)
}
}
+128
View File
@@ -0,0 +1,128 @@
package intercept
import (
"context"
"encoding/json"
"strings"
"testing"
)
func TestStatefulTargetGuardTableDriven(t *testing.T) {
cases := []struct {
name string
setup func(g *StatefulTargetGuard)
intentID int64
tool string
input string
rendered string
method string
wantErrSub string
recordRO bool
checkAfterRO string
}{
{
name: "post_blocked_without_baseline",
intentID: 1,
tool: "Bash",
input: `{"command":"curl -X POST https://target.lab.local/api/v1/certificates/upload -d '{}'"}`,
wantErrSub: "pre-mutation baseline required",
},
{
name: "get_runs_without_baseline_and_records_it",
intentID: 1,
tool: "WebFetch",
input: `{"url":"https://target.lab.local/api/v1/estate"}`,
recordRO: true,
},
{
name: "post_allowed_after_baseline",
setup: func(g *StatefulTargetGuard) {
g.RecordBaseline("task-1", "target.lab.local")
},
intentID: 1,
tool: "Bash",
input: `{"command":"curl -X POST https://target.lab.local/api/v1/certificates/upload -d '{}'"}`,
},
{
name: "concurrent_mutating_intent_rejected_while_lease_held",
setup: func(g *StatefulTargetGuard) {
g.RecordBaseline("task-1", "target.lab.local")
ok, _ := g.AcquireMutationLease("task-1", "target.lab.local", 1)
if !ok {
t.Fatal("setup lease failed")
}
},
intentID: 2,
tool: "custom_http_post",
rendered: "https://target.lab.local/api/v1/deploy",
method: "POST",
wantErrSub: "mutation lease for host target.lab.local is held by intent #1",
},
{
name: "readonly_runs_in_parallel_while_mutation_lease_held",
setup: func(g *StatefulTargetGuard) {
g.RecordBaseline("task-1", "target.lab.local")
g.AcquireMutationLease("task-1", "target.lab.local", 1)
},
intentID: 2,
tool: "WebFetch",
input: `{"url":"https://target.lab.local/docs"}`,
},
{
name: "custom_script_tool_post_blocked_without_baseline",
intentID: 3,
tool: "custom_py_script",
input: `{"url":"https://script.lab.local/api/v1/upload"}`,
rendered: `import requests; requests.post(params["url"], json={})`,
wantErrSub: "pre-mutation baseline required for host script.lab.local",
},
{
name: "custom_script_tool_post_allowed_after_baseline",
setup: func(g *StatefulTargetGuard) {
g.RecordBaseline("task-1", "script.lab.local")
},
intentID: 3,
tool: "custom_py_script",
input: `{"url":"https://script.lab.local/api/v1/upload"}`,
rendered: `import requests; requests.post(params["url"], json={})`,
},
{
name: "release_intent_frees_lease_for_next_intent",
setup: func(g *StatefulTargetGuard) {
g.RecordBaseline("task-1", "target.lab.local")
g.AcquireMutationLease("task-1", "target.lab.local", 1)
g.ReleaseIntent("task-1", 1)
},
intentID: 2,
tool: "custom_http_post",
rendered: "https://target.lab.local/api/v1/deploy",
method: "POST",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
g := NewStatefulTargetGuard()
if tc.setup != nil {
tc.setup(g)
}
ctx := WithStatefulActor(WithStatefulGuard(context.Background(), g), "task-1", tc.intentID)
err := CheckStatefulTool(ctx, tc.tool, json.RawMessage(tc.input), tc.rendered, tc.method)
if tc.wantErrSub != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErrSub) {
t.Fatalf("expected error containing %q, got %v", tc.wantErrSub, err)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tc.recordRO {
RecordStatefulReadOnly(ctx, tc.tool, json.RawMessage(tc.input), tc.rendered, tc.method)
if !g.HasBaseline("task-1", "target.lab.local") {
t.Fatalf("expected baseline recorded after read-only call")
}
}
})
}
}
+171
View File
@@ -0,0 +1,171 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
// TestRunIntentPollLoopEmitsAskOperatorActivityAndPausesWithHandoffCause verifies
// end-to-end that when a worker hits 3 identical read-only polls interleaved
// with sleep, the engine itself emits the OPERATOR INPUT REQUESTED activity
// (askOperatorActivity shape), emits a non-error operator_handoff result, and
// settles the intent as paused.
func TestRunIntentPollLoopEmitsAskOperatorActivityAndPausesWithHandoffCause(t *testing.T) {
skipWithoutDSN(t)
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"records":173,"status":"churned"}`))
}))
defer target.Close()
var (
mu sync.Mutex
turn int
)
mockLLM := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
turn++
cur := turn
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
var tcID, tcName, tcArgs string
pollCmd, _ := json.Marshal(map[string]string{"command": "curl -s " + target.URL + "/api/v1/estate"})
switch cur {
case 1:
tcID, tcName, tcArgs = "t1", "Bash", string(pollCmd)
case 2:
tcID, tcName, tcArgs = "t2", "Bash", `{"command":"sleep 0"}`
case 3:
tcID, tcName, tcArgs = "t3", "Bash", string(pollCmd)
case 4:
tcID, tcName, tcArgs = "t4", "Bash", `{"command":"sleep 0"}`
case 5:
tcID, tcName, tcArgs = "t5", "Bash", string(pollCmd)
default:
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "c_end", "object": "chat.completion", "model": "mock-worker",
"choices": []map[string]any{{"index": 0, "message": map[string]any{"role": "assistant", "content": "done"}, "finish_reason": "stop"}},
"usage": map[string]any{"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12},
})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{
"id": "c_" + tcID, "object": "chat.completion", "model": "mock-worker",
"choices": []map[string]any{{
"index": 0,
"message": map[string]any{
"role": "assistant",
"tool_calls": []map[string]any{{
"id": tcID,
"type": "function",
"function": map[string]any{"name": tcName, "arguments": tcArgs},
}},
},
"finish_reason": "tool_calls",
}},
"usage": map[string]any{"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
})
}))
defer mockLLM.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-poll-worker",
Format: "openai",
BaseURL: mockLLM.URL + "/v1",
Model: "mock-worker",
APIKey: "test-key",
Streaming: false,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = m.pg.DeleteProfile(pid) })
task, err := m.CreateTaskWithOptions("poll escalation", "Audit "+target.URL, db.TaskCreateOptions{
LLMProfileIDs: []int64{pid},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
intentID, err := task.Store.AddIntent(map[string]any{"summary": "Poll target estate"}, 5, nil, "planner")
if err != nil {
t.Fatal(err)
}
token, err := task.Store.ClaimIntentToken(intentID, "work#1")
if err != nil {
t.Fatalf("ClaimIntentToken: %v", err)
}
intent, err := task.Store.GetNode(intentID)
if err != nil || intent == nil {
t.Fatalf("GetNode: %v %v", intent, err)
}
_, worker := s.engine.snapshotFor(task)
if worker == nil {
t.Fatal("expected worker snapshot")
}
if !s.engine.beginTaskOperation(task.ID) {
t.Fatal("beginTaskOperation failed")
}
ok := s.engine.runIntent(ctx, task, "work#1", worker, intent, token, "", "")
s.engine.decInflight(task.ID)
if !ok {
t.Fatal("runIntent returned false")
}
node, err := task.Store.GetNode(intentID)
if err != nil || node == nil {
t.Fatal(err)
}
acts, _, err := task.Store.ActivityList(&intentID, 0, 100)
if err != nil {
t.Fatal(err)
}
if node.State != "paused" {
for i, a := range acts {
t.Logf("act[%d]: kind=%s tool=%s err=%v sum=%q detail=%q", i, a.Kind, a.Tool, a.IsError, a.Summary, a.Detail)
}
t.Fatalf("expected intent settled as paused, got %q", node.State)
}
var sawAskOp, sawHandoffResult bool
for _, a := range acts {
if strings.Contains(a.Summary, "OPERATOR INPUT REQUESTED:") && !a.IsError {
sawAskOp = true
}
if a.Kind == "result" && !a.IsError && strings.Contains(a.Summary, agent.AbortOperatorHandoff.Short) {
sawHandoffResult = true
}
}
if !sawAskOp {
t.Fatalf("expected non-error OPERATOR INPUT REQUESTED activity, got: %+v", acts)
}
if !sawHandoffResult {
t.Fatalf("expected non-error operator_handoff result activity, got: %+v", acts)
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func (s *Server) toolAskOperator() actool.CoreTool {
s.engine.emitActivity(t, act)
// The control call runs on a detached context: pausing may cancel the
// run's context, and the pause bookkeeping itself must complete.
if _, err := s.applyIntentControl(context.Background(), t, ri.IntentID, "pause", firstLine(q, 120), ""); err != nil {
if _, err := s.applyIntentControl(context.Background(), t, ri.IntentID, "pause_handoff", firstLine(q, 120), ""); err != nil {
return actool.Errorf("Error: question delivered but pausing the intent failed: " + err.Error()), nil
}
return actool.Text("Question delivered to the operator. This intent is pausing now: finish your current step, record everything you already know as facts, and stop. The operator's reply will resume this run and arrive as your next input."), nil
+17 -1
View File
@@ -453,6 +453,9 @@ func (s *Server) runCommandTool(ctx context.Context, key string, execRaw json.Ra
if res := intercept.GateRenderedCommand(ctx, key, cmd, renderTemplate(spec.Command, params, identity)); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
if err := intercept.CheckStatefulTool(ctx, key, nil, cmd, ""); err != nil {
return actool.Errorf(err.Error()), nil
}
// Reuse the low-level run Bash also uses (via the Bash CoreTool.Call): it
// automatically inherits the safety floor/timeout/proxy env/output overflow. The tool is a peer of Bash sharing that low level, not routed through the Bash tool for the model to call.
bashIn, _ := json.Marshal(map[string]any{"command": cmd})
@@ -461,7 +464,11 @@ func (s *Server) runCommandTool(ctx context.Context, key string, execRaw json.Ra
ctx, cancel = context.WithTimeout(ctx, timeoutOr(spec.TimeoutMs, 120000))
defer cancel()
}
return actool.NewBash().Call(ctx, bashIn, tc)
res, err := actool.NewBash().Call(ctx, bashIn, tc)
if err == nil && !res.IsError {
intercept.RecordStatefulReadOnly(ctx, key, nil, cmd, "")
}
return res, err
}
// ---------- script (Python only): temp file + stdin JSON + env ----------
@@ -484,10 +491,15 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
}
sessionEnv = tc.Env
}
rawParams, _ := json.Marshal(params)
if err := intercept.CheckStatefulTool(ctx, key, rawParams, spec.Code, ""); err != nil {
return actool.Errorf(err.Error()), nil
}
body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000), s.execPriv)
if err != nil {
return actool.Errorf(err.Error()), nil
}
intercept.RecordStatefulReadOnly(ctx, key, rawParams, spec.Code, "")
return actool.Text(actool.Capture(tc, body)), nil
}
@@ -565,6 +577,9 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
if res := intercept.GateRenderedURL(ctx, key, rawURL); res.Code != "" {
return actool.Errorf(guard.TargetBlockMessage(res)), nil
}
if err := intercept.CheckStatefulTool(ctx, key, nil, rawURL, method); err != nil {
return actool.Errorf(err.Error()), nil
}
var bodyReader io.Reader
if spec.Body != "" {
bodyReader = strings.NewReader(renderTemplate(spec.Body, params, identity))
@@ -597,6 +612,7 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
return actool.Errorf("request failed: " + err.Error()), nil
}
defer resp.Body.Close()
intercept.RecordStatefulReadOnly(ctx, key, nil, rawURL, method)
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
out := map[string]any{"status": resp.StatusCode, "body": string(respBody)}
b, _ := json.Marshal(out)
+59 -6
View File
@@ -93,8 +93,10 @@ func retryableWorkerModelError(reason harness.TerminalReason, err error) bool {
// (re)installed at runtime (LLM configured from the UI); the loops always run
// but idle until an LLM is set.
type Engine struct {
m *Manager
debounce time.Duration
statefulGuardOnce sync.Once
statefulGuard *intercept.StatefulTargetGuard
m *Manager
debounce time.Duration
bc *Broadcaster // live activity pub/sub (SSE)
@@ -492,6 +494,12 @@ func (e *Engine) detachWork(intentID int64) (action string, complete func(error)
// worker has fully stopped writing. Cancellation cleanup is performed by the API
// handler after this returns; pause state is committed by runWorkerStep itself.
func (e *Engine) ControlWork(ctx context.Context, intentID int64, action string) error {
return e.ControlWorkWithCause(ctx, intentID, action, nil)
}
// ControlWorkWithCause requests a pause/cancel with an optional explicit AbortCause
// (e.g. agent.AbortOperatorHandoff for ask_operator pauses).
func (e *Engine) ControlWorkWithCause(ctx context.Context, intentID int64, action string, customCause error) error {
if action != "pause" && action != "cancel" {
return fmt.Errorf("unsupported work action %q", action)
}
@@ -510,9 +518,12 @@ func (e *Engine) ControlWork(ctx context.Context, intentID int64, action string)
}
run.action = action
done := run.done
cause := error(agent.AbortWorkPausedByUser)
if action == "cancel" {
cause = agent.AbortWorkCancelledByUser
cause := customCause
if cause == nil {
cause = error(agent.AbortWorkPausedByUser)
if action == "cancel" {
cause = agent.AbortWorkCancelledByUser
}
}
run.cancel(cause)
e.workMu.Unlock()
@@ -1239,6 +1250,11 @@ func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *ag
label := fmt.Sprintf("%s · #%d", name, iid)
workCtx = intercept.WithTaskContext(workCtx, t.ID, label, taskEmit)
workCtx = intercept.WithTargetScope(workCtx, t.targetScope(intercept.DefaultTargetWaitBound))
if sg := e.statefulGuardForTask(); sg != nil {
workCtx = intercept.WithStatefulGuard(workCtx, sg)
workCtx = intercept.WithStatefulActor(workCtx, t.ID, iid)
defer sg.ReleaseIntent(t.ID, iid)
}
// Run budget (off by default): meter this run's calls; its effective budget is
// min(intent budget, task remaining above the wrap-up reserve).
workCtx, meter := e.budgetIntent(workCtx, t.ID)
@@ -1300,7 +1316,7 @@ func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *ag
// still settles the stopped run into a recoverable state.
if action == "" {
switch {
case errors.Is(workCause, agent.AbortWorkPausedByUser):
case errors.Is(workCause, agent.AbortWorkPausedByUser), errors.Is(workCause, agent.AbortOperatorHandoff):
action = "pause"
case errors.Is(workCause, agent.AbortWorkCancelledByUser):
action = "cancel"
@@ -1338,6 +1354,15 @@ func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *ag
log.Printf("[worker %s] task %s intent #%d claim lost to another worker, result discarded", name, t.ID, intent.ID)
return true
}
if errors.Is(err, agent.ErrPollLoopDetected) || errors.Is(workCause, agent.ErrPollLoopDetected) {
workCancel(agent.AbortOperatorHandoff)
e.emitPollLoopOperatorHandoff(t, name, intent.ID)
if perr := t.Store.SettleIntentClaim(intent.ID, token, "paused"); perr != nil {
log.Printf("[worker %s] task %s intent #%d failed to pause after poll loop: %v", name, t.ID, intent.ID, perr)
}
e.touch(t.ID)
return true
}
// if a pause cancelled this run mid-flight, return the intent to the frontier
// so it is re-claimed on resume — the worker will resume the prior LLM
// conversation from its transcript instead of restarting from scratch.
@@ -1505,3 +1530,31 @@ func (e *Engine) claimNext(t *Task, name string) (*db.Node, string) {
}
return nil, ""
}
func (e *Engine) statefulGuardForTask() *intercept.StatefulTargetGuard {
if e == nil {
return nil
}
e.statefulGuardOnce.Do(func() {
e.statefulGuard = intercept.NewStatefulTargetGuard()
})
return e.statefulGuard
}
func (e *Engine) emitPollLoopOperatorHandoff(t *Task, workerName string, intentID int64) {
q := "Repeated identical read-only polls detected (target state appears unchanged or waiting for an external reset). Please reset/restart the instance and reply with the new base URL or instructions to continue."
text := "OPERATOR INPUT REQUESTED: " + q + " (this intent is pausing; reply here to resume it with your answer)"
act := askOperatorActivity(text, nil, targetDerivedHosts(q, goalTargets(t.Goal)))
act.NodeID = &intentID
act.Worker = workerName
act.IsError = false
e.emitActivity(t, act)
e.emitActivity(t, db.Activity{
NodeID: &intentID,
Worker: workerName,
Kind: "result",
IsError: false,
Summary: "(paused for operator input: " + agent.AbortOperatorHandoff.Short + "; waiting for operator reply)",
Detail: agent.AbortOperatorHandoff.Text,
})
}
+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)
}
}
+121
View File
@@ -0,0 +1,121 @@
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/Autumn-27/artex/db"
)
// RetargetTask updates a task when the operator provisions a fresh target
// instance with a new hostname/URL: updates tasks.goal, open goal payloads,
// constraints, and task_scope, kills running/open stale intents targeting
// oldHost, seeds the new URL, and wakes the planner.
func (s *Server) RetargetTask(ctx context.Context, taskID, oldHost, newBaseURL string) (*db.RetargetResult, int, error) {
t, ok := s.m.Task(taskID)
if !ok {
return nil, 0, fmt.Errorf("task %s not found", taskID)
}
idNum, err := strconv.ParseInt(taskID, 10, 64)
if err != nil {
return nil, 0, err
}
res, err := s.m.pg.RetargetTask(ctx, idNum, oldHost, newBaseURL)
if err != nil {
return nil, 0, err
}
s.m.mu.Lock()
t.Goal = res.UpdatedGoal
s.m.mu.Unlock()
// Kill running or open intents still targeting oldHost.
staleCount := 0
oldLower := strings.ToLower(strings.TrimSpace(res.OldHost))
if oldLower != "" && t.Store != nil {
intents, _ := t.Store.ListByKind(db.KindIntent, 500)
for _, in := range intents {
if in.State != "open" && in.State != "running" && in.State != "paused" {
continue
}
var p struct {
Summary string `json:"summary"`
}
_ = json.Unmarshal(in.Payload, &p)
if !strings.Contains(strings.ToLower(p.Summary), oldLower) {
continue
}
if in.State == "running" && s.engine != nil {
_ = s.engine.KillWork(in.ID)
}
if err := t.Store.SetNodeState(in.ID, "stopped"); err == nil {
staleCount++
}
}
}
s.seed(t, newBaseURL)
if s.engine != nil {
s.engine.emitActivity(t, db.Activity{
Worker: "system",
Kind: "text",
Summary: fmt.Sprintf("Task retargeted from %s to %s (%d stale intent(s) stopped)", res.OldHost, res.NewHost, staleCount),
})
}
t.Notify()
log.Printf("[retarget] task %s retargeted %s -> %s (stale_intents=%d)", taskID, res.OldHost, res.NewHost, staleCount)
return res, staleCount, nil
}
// retargetTaskHandler handles POST /api/tasks/{id}/retarget with JSON body
// {"old_host":"...","new_base_url":"https://..."}.
func (s *Server) retargetTaskHandler(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if _, ok := s.m.Task(id); !ok {
writeErr(w, 404, "task not found")
return
}
var req struct {
OldHost string `json:"old_host"`
NewBaseURL string `json:"new_base_url"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, 400, err.Error())
return
}
oldHost := strings.TrimSpace(req.OldHost)
newBaseURL := strings.TrimSpace(req.NewBaseURL)
if oldHost == "" || newBaseURL == "" {
writeErr(w, 400, "old_host and new_base_url are required")
return
}
u, err := url.Parse(newBaseURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
writeErr(w, 400, "new_base_url must be a valid http or https URL")
return
}
if s.engine != nil {
if !s.engine.beginTaskOperation(id) {
writeErr(w, 409, "task is being deleted")
return
}
defer s.engine.decInflight(id)
}
res, staleCount, err := s.RetargetTask(r.Context(), id, oldHost, newBaseURL)
if err != nil {
writeErr(w, 400, err.Error())
return
}
writeJSON(w, 200, map[string]any{
"task_id": id,
"old_host": res.OldHost,
"new_host": res.NewHost,
"updated_goal": res.UpdatedGoal,
"stale_intents": staleCount,
"retargeted": res,
})
}
+126
View File
@@ -0,0 +1,126 @@
package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestRetargetTaskHTTPHandler(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)
}
ctx, cancel := context.WithCancel(context.Background())
s := New(ctx, m, "", m.dir, m.dir)
t.Cleanup(func() { stopTestServer(t, s, cancel) })
task, err := m.CreateTaskWithOptions("retarget-http", "Audit https://old.example.test/api", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
if _, err := task.Store.AddGoal(map[string]any{"summary": "Capture flags on https://old.example.test"}, "operator"); err != nil {
t.Fatal(err)
}
if _, err := task.Store.AddConstraint("allow", "Only test old.example.test", "operator"); err != nil {
t.Fatal(err)
}
intentID, err := task.Store.AddIntent(map[string]any{"summary": "Enumerate old.example.test/docs"}, 5, nil, "planner")
if err != nil {
t.Fatal(err)
}
h := s.Handler()
tok, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
// 1. Unauthenticated request must be rejected with 401.
req401 := httptest.NewRequest("POST", "/api/tasks/"+task.ID+"/retarget", bytes.NewBufferString(`{"old_host":"old.example.test","new_base_url":"https://new.example.test"}`))
req401.Header.Set("Content-Type", "application/json")
rec401 := httptest.NewRecorder()
h.ServeHTTP(rec401, req401)
if rec401.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 without auth, got %d: %s", rec401.Code, rec401.Body.String())
}
// 2. Invalid/missing fields must return 400.
for _, badBody := range []string{
`{}`,
`{"old_host":"old.example.test","new_base_url":"not-a-url"}`,
`{"old_host":"","new_base_url":"https://new.example.test"}`,
} {
req400 := httptest.NewRequest("POST", "/api/tasks/"+task.ID+"/retarget", bytes.NewBufferString(badBody))
req400.Header.Set("Content-Type", "application/json")
req400.Header.Set("Authorization", "Bearer "+tok)
rec400 := httptest.NewRecorder()
h.ServeHTTP(rec400, req400)
if rec400.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for body %s, got %d: %s", badBody, rec400.Code, rec400.Body.String())
}
}
// 3. Unknown task returns 404.
req404 := httptest.NewRequest("POST", "/api/tasks/999999/retarget", bytes.NewBufferString(`{"old_host":"old.example.test","new_base_url":"https://new.example.test"}`))
req404.Header.Set("Content-Type", "application/json")
req404.Header.Set("Authorization", "Bearer "+tok)
rec404 := httptest.NewRecorder()
h.ServeHTTP(rec404, req404)
if rec404.Code != http.StatusNotFound {
t.Fatalf("expected 404 for unknown task, got %d: %s", rec404.Code, rec404.Body.String())
}
// 4. Valid retarget updates goal, constraints, stale intent, and returns 200 JSON.
req200 := httptest.NewRequest("POST", "/api/tasks/"+task.ID+"/retarget", bytes.NewBufferString(`{"old_host":"old.example.test","new_base_url":"https://new.example.test:8443"}`))
req200.Header.Set("Content-Type", "application/json")
req200.Header.Set("Authorization", "Bearer "+tok)
rec200 := httptest.NewRecorder()
h.ServeHTTP(rec200, req200)
if rec200.Code != http.StatusOK {
t.Fatalf("expected 200 on valid retarget, got %d: %s", rec200.Code, rec200.Body.String())
}
var resp struct {
TaskID string `json:"task_id"`
OldHost string `json:"old_host"`
NewHost string `json:"new_host"`
UpdatedGoal string `json:"updated_goal"`
StaleIntents int `json:"stale_intents"`
}
if err := json.Unmarshal(rec200.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp.TaskID != task.ID || resp.OldHost != "old.example.test" || resp.NewHost != "new.example.test" {
t.Fatalf("unexpected retarget response: %+v", resp)
}
if !strings.Contains(resp.UpdatedGoal, "new.example.test") || strings.Contains(resp.UpdatedGoal, "old.example.test") {
t.Fatalf("expected updated_goal to reference new host only, got %q", resp.UpdatedGoal)
}
if resp.StaleIntents != 1 {
t.Fatalf("expected 1 stale intent stopped, got %d", resp.StaleIntents)
}
node, err := task.Store.GetNode(intentID)
if err != nil || node == nil {
t.Fatal(err)
}
if node.State != "stopped" {
t.Fatalf("expected stale intent stopped, got %q", node.State)
}
}
+81
View File
@@ -0,0 +1,81 @@
package server
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestRetargetTaskUpdatesGoalConstraintsScopeAndStopsStaleIntents(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)
}
ctx, cancel := context.WithCancel(context.Background())
s := New(ctx, m, "", m.dir, m.dir)
t.Cleanup(func() { stopTestServer(t, s, cancel) })
task, err := m.CreateTaskWithOptions("retarget", "Capture flags on https://old-0c3f.ctf.local/docs", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) })
// Seed goal node, constraint, scope, and stale + unrelated intents.
gid, err := task.Store.AddNode(db.KindGoal, map[string]any{"text": "Capture flag 2 on old-0c3f.ctf.local"}, 0, "open", "goals", nil)
if err != nil {
t.Fatal(err)
}
if _, err := task.Store.AddConstraint("allow", "only test old-0c3f.ctf.local", "goals"); err != nil {
t.Fatal(err)
}
if _, err := m.Assets().AddAgentScope(mustTaskID(t, task.ID), "subdomain", "old-0c3f.ctf.local", "seed", "manual"); err != nil {
t.Fatal(err)
}
staleID, err := task.Store.AddIntent(map[string]any{"summary": "Poll https://old-0c3f.ctf.local/api/v1/estate"}, 0, nil, "planner")
if err != nil {
t.Fatal(err)
}
keepID, err := task.Store.AddIntent(map[string]any{"summary": "Analyze offline docs"}, 0, nil, "planner")
if err != nil {
t.Fatal(err)
}
res, stopped, err := s.RetargetTask(ctx, task.ID, "old-0c3f.ctf.local", "https://new-4791.ctf.local")
if err != nil {
t.Fatalf("RetargetTask: %v", err)
}
if stopped != 1 || res.GoalsUpdated != 1 || res.ConstraintsUpdated != 1 {
t.Fatalf("unexpected retarget counts: res=%+v stopped=%d", res, stopped)
}
if !strings.Contains(task.Goal, "new-4791.ctf.local") || strings.Contains(task.Goal, "old-0c3f.ctf.local") {
t.Fatalf("live task.Goal not updated: %q", task.Goal)
}
goalNode, err := task.Store.GetNode(gid)
if err != nil || goalNode == nil {
t.Fatal(err)
}
var gp map[string]any
_ = json.Unmarshal(goalNode.Payload, &gp)
if !strings.Contains(gp["text"].(string), "new-4791.ctf.local") {
t.Fatalf("goal node payload not updated: %+v", gp)
}
cs, _ := task.Store.ListConstraints()
if len(cs) != 1 || !strings.Contains(cs[0].Text, "new-4791.ctf.local") {
t.Fatalf("constraint not updated: %+v", cs)
}
staleNode, _ := task.Store.GetNode(staleID)
keepNode, _ := task.Store.GetNode(keepID)
if staleNode.State != "stopped" || keepNode.State != "open" {
t.Fatalf("intent states mismatch: stale=%s keep=%s", staleNode.State, keepNode.State)
}
}
+1
View File
@@ -851,6 +851,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // constraint management: edit a constraint
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // constraint management: delete a constraint
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
mux.HandleFunc("POST /api/tasks/{id}/retarget", s.retargetTaskHandler)
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
+9 -3
View File
@@ -179,12 +179,18 @@ func (s *Server) applyIntentControl(ctx context.Context, t *Task, iid int64, act
return out, fmt.Errorf("node is not an intent")
}
switch action {
case "pause":
case "pause", "pause_handoff":
if node.State != "running" {
return out, fmt.Errorf("only running intents can be paused")
}
if err := s.engine.ControlWork(ctx, iid, "pause"); err != nil {
return out, err
var ctrlErr error
if action == "pause_handoff" {
ctrlErr = s.engine.ControlWorkWithCause(ctx, iid, "pause", agent.AbortOperatorHandoff)
} else {
ctrlErr = s.engine.ControlWork(ctx, iid, "pause")
}
if ctrlErr != nil {
return out, ctrlErr
}
out.State = "paused"
case "resume":
+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 {