mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-28 10:50:53 +08:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20042ed2cf | ||
|
|
8ef89e32c5 | ||
|
|
b90474f1e7 | ||
|
|
771c241831 | ||
|
|
e3a83d7c74 | ||
|
|
ee763fc526 | ||
|
|
da7015f6e8 | ||
|
|
82af66cdd8 | ||
|
|
935f629acf | ||
|
|
a7e63c5db4 | ||
|
|
e5c7bfcbdd | ||
|
|
10fb8d389d | ||
|
|
066b978687 | ||
|
|
cc25ad55c4 | ||
|
|
30d5b96a51 | ||
|
|
1f558d8681 | ||
|
|
478bdcae82 | ||
|
|
efe588a526 |
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
var capabilityStrictOverride atomic.Int32 // 0=env, 1=shadow(false), 2=strict(true)
|
||||
|
||||
// SetCapabilityStrictMode overrides shadow vs strict enforcement for tests.
|
||||
func SetCapabilityStrictMode(strict bool) {
|
||||
if strict {
|
||||
capabilityStrictOverride.Store(2)
|
||||
} else {
|
||||
capabilityStrictOverride.Store(1)
|
||||
}
|
||||
}
|
||||
|
||||
// ResetCapabilityStrictMode restores env-based capability mode (default shadow).
|
||||
func ResetCapabilityStrictMode() {
|
||||
capabilityStrictOverride.Store(0)
|
||||
}
|
||||
|
||||
func capabilityStrictEnabled() bool {
|
||||
switch capabilityStrictOverride.Load() {
|
||||
case 1:
|
||||
return false
|
||||
case 2:
|
||||
return true
|
||||
default:
|
||||
return os.Getenv("ARTEX_CAPABILITY_STRICT") == "1"
|
||||
}
|
||||
}
|
||||
|
||||
type capabilityPayload struct {
|
||||
Subtype string `json:"subtype"`
|
||||
Status string `json:"status"` // held | required | closed
|
||||
Holder string `json:"holder"`
|
||||
Verb string `json:"verb"`
|
||||
Object string `json:"object"`
|
||||
Precondition string `json:"precondition,omitempty"`
|
||||
Evidence string `json:"evidence"`
|
||||
Confidence string `json:"confidence"`
|
||||
Verified bool `json:"verified"`
|
||||
CloseReason string `json:"close_reason,omitempty"`
|
||||
ProvingIDs []int64 `json:"proving_ids,omitempty"`
|
||||
TrafficRefs []string `json:"traffic_refs,omitempty"`
|
||||
}
|
||||
|
||||
func isCapabilityNode(n *db.Node) (capabilityPayload, bool) {
|
||||
if n == nil || n.Kind != db.KindFact {
|
||||
return capabilityPayload{}, false
|
||||
}
|
||||
var p capabilityPayload
|
||||
if json.Unmarshal(n.Payload, &p) != nil || p.Subtype != db.FactSubtypeCapability {
|
||||
return capabilityPayload{}, false
|
||||
}
|
||||
if p.Status == "" {
|
||||
p.Status = "held"
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func (t *ToolSet) recordCapability() actool.CoreTool {
|
||||
return t.writeExpTool("record_capability",
|
||||
"Record an exploitation capability (held, required by an open goal, or closed/unreachable) in the exploitation capability ledger (#613). A capability is a power the operator has obtained over the target (an actor can now do an action on an object), not a permission granted to this agent: scope, constraints and the intercept gate remain the agent's permission model. Evidence and confidence are mandatory; held capabilities without a proving finding/fact/traffic reference are stored as unverified and cannot satisfy a goal.",
|
||||
obj(map[string]any{
|
||||
"status": map[string]any{"type": "string", "enum": []string{"held", "required", "closed"}, "description": "held (acquired), required (needed by open goal), or closed (proven unreachable)"},
|
||||
"holder": str("actor/principal holding or needing the capability (e.g. member_session, edge_peer)"),
|
||||
"verb": str("action verb (e.g. retire_cert, read_enrolment, impersonate_edge)"),
|
||||
"object": str("target object/resource"),
|
||||
"precondition": str("optional precondition"),
|
||||
"evidence": str("mandatory: observed evidence or goal requirement rationale"),
|
||||
"confidence": map[string]any{"type": "string", "enum": []string{"observed", "inferred"}, "description": "mandatory confidence level"},
|
||||
"proving_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "optional: finding/fact node IDs proving this capability"},
|
||||
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "optional: related asset IDs"},
|
||||
"traffic_refs": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "optional: proving traffic IDs"},
|
||||
"close_reason": str("required when status=closed"),
|
||||
}, "holder", "verb", "object", "evidence", "confidence"),
|
||||
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
Status string `json:"status"`
|
||||
Holder string `json:"holder"`
|
||||
Verb string `json:"verb"`
|
||||
Object string `json:"object"`
|
||||
Precondition string `json:"precondition"`
|
||||
Evidence string `json:"evidence"`
|
||||
Confidence string `json:"confidence"`
|
||||
ProvingIDs []json.RawMessage `json:"proving_ids"`
|
||||
AssetIDs []json.RawMessage `json:"asset_ids"`
|
||||
TrafficRefs []string `json:"traffic_refs"`
|
||||
CloseReason string `json:"close_reason"`
|
||||
}
|
||||
if err := json.Unmarshal(in, &a); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
status := strings.ToLower(strings.TrimSpace(a.Status))
|
||||
if status == "" {
|
||||
status = "held"
|
||||
}
|
||||
if status != "held" && status != "required" && status != "closed" {
|
||||
return actool.Errorf("status must be held, required, or closed"), nil
|
||||
}
|
||||
if strings.TrimSpace(a.Holder) == "" || strings.TrimSpace(a.Verb) == "" || strings.TrimSpace(a.Object) == "" {
|
||||
return actool.Errorf("holder, verb, and object are required"), nil
|
||||
}
|
||||
if strings.TrimSpace(a.Evidence) == "" || strings.TrimSpace(a.Confidence) == "" {
|
||||
return actool.Errorf("evidence and confidence are mandatory on a capability"), nil
|
||||
}
|
||||
if status == "closed" && strings.TrimSpace(a.CloseReason) == "" {
|
||||
return actool.Errorf("close_reason is required when status=closed"), nil
|
||||
}
|
||||
|
||||
provingIDs := pidList(a.ProvingIDs)
|
||||
validProving := make([]int64, 0, len(provingIDs))
|
||||
for _, pidv := range provingIDs {
|
||||
n, err := t.ts.GetNodeWithSources(pidv)
|
||||
if err != nil || n == nil || (n.Kind != db.KindFinding && n.Kind != db.KindFact) {
|
||||
return actool.Errorf(fmt.Sprintf("proving_id %d must be an existing finding or fact node", pidv)), nil
|
||||
}
|
||||
validProving = append(validProving, pidv)
|
||||
}
|
||||
verified := len(validProving) > 0 || len(a.TrafficRefs) > 0
|
||||
if status != "held" {
|
||||
verified = false
|
||||
}
|
||||
|
||||
p := map[string]any{
|
||||
"subtype": db.FactSubtypeCapability,
|
||||
"status": status,
|
||||
"holder": strings.TrimSpace(a.Holder),
|
||||
"verb": strings.TrimSpace(a.Verb),
|
||||
"object": strings.TrimSpace(a.Object),
|
||||
"precondition": strings.TrimSpace(a.Precondition),
|
||||
"evidence": strings.TrimSpace(a.Evidence),
|
||||
"confidence": strings.TrimSpace(a.Confidence),
|
||||
"verified": verified,
|
||||
}
|
||||
if status == "closed" {
|
||||
p["close_reason"] = strings.TrimSpace(a.CloseReason)
|
||||
}
|
||||
if len(validProving) > 0 {
|
||||
p["proving_ids"] = validProving
|
||||
}
|
||||
if len(a.TrafficRefs) > 0 {
|
||||
p["traffic_refs"] = a.TrafficRefs
|
||||
}
|
||||
anchors := pidList(a.AssetIDs)
|
||||
id, err := t.ts.AddNode(db.KindFact, p, 0, "confirmed", "planner", anchors)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
for _, provID := range validProving {
|
||||
_ = t.ts.Link(provID, db.RelDerivedFrom, id)
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"id": id,
|
||||
"status": status,
|
||||
"verified": verified,
|
||||
"holder": p["holder"],
|
||||
"verb": p["verb"],
|
||||
"object": p["object"],
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (t *ToolSet) checkIntentCapabilities(it intentItem) (warning string, err error) {
|
||||
// Reject/flag assuming a closed capability.
|
||||
if t.ts != nil && len(it.Consumes) > 0 {
|
||||
nodes, _ := t.ts.ListByKind(db.KindFact, 500)
|
||||
closedByID := map[int64]capabilityPayload{}
|
||||
for _, n := range nodes {
|
||||
if p, ok := isCapabilityNode(n); ok && p.Status == "closed" {
|
||||
closedByID[n.ID] = p
|
||||
}
|
||||
}
|
||||
for _, raw := range it.Consumes {
|
||||
if id := pid(raw); id > 0 {
|
||||
if cp, closed := closedByID[id]; closed {
|
||||
msg := fmt.Sprintf("intent consumes closed capability #%d (%s %s: %s)", id, cp.Verb, cp.Object, cp.CloseReason)
|
||||
if capabilityStrictEnabled() {
|
||||
return "", fmt.Errorf("%s", msg)
|
||||
}
|
||||
warning = msg
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(it.Gains) == 0 {
|
||||
msg := "intent declares no capability gains (shadow capability ledger #613)"
|
||||
if capabilityStrictEnabled() {
|
||||
return "", fmt.Errorf("intent rejected: must declare at least one capability in gains")
|
||||
}
|
||||
slog.Warn("[capability] shadow flag on add_intent", "summary", it.Summary, "reason", msg)
|
||||
if warning == "" {
|
||||
warning = msg
|
||||
}
|
||||
}
|
||||
return warning, nil
|
||||
}
|
||||
|
||||
func (t *ToolSet) capabilityOverview() (held, required, closed []map[string]any) {
|
||||
if t.ts == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
nodes, err := t.ts.ListByKind(db.KindFact, 500)
|
||||
if err != nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
for _, n := range nodes {
|
||||
p, ok := isCapabilityNode(n)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
m := map[string]any{
|
||||
"id": n.ID,
|
||||
"holder": p.Holder,
|
||||
"verb": p.Verb,
|
||||
"object": p.Object,
|
||||
"verified": p.Verified,
|
||||
}
|
||||
if p.Precondition != "" {
|
||||
m["precondition"] = p.Precondition
|
||||
}
|
||||
switch p.Status {
|
||||
case "required":
|
||||
required = append(required, m)
|
||||
case "closed":
|
||||
m["close_reason"] = p.CloseReason
|
||||
closed = append(closed, m)
|
||||
default:
|
||||
held = append(held, m)
|
||||
}
|
||||
}
|
||||
return held, required, closed
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"iter"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func TestCapabilityLedgerCreationOverviewStrictRejectionAndUnverifiedGoalBlock(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
tsx := NewToolSet(ts, "planner")
|
||||
ResetCapabilityStrictMode()
|
||||
t.Cleanup(ResetCapabilityStrictMode)
|
||||
|
||||
// 1. Record an unverified capability (no proving_ids or traffic_refs) -> stored verified=false, cannot prove goal.
|
||||
goalID, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Obtain edge peer access"}, 0, "open", "goals", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unverRes := callGuardTool(t, tsx.recordCapability(), `{
|
||||
"status":"held",
|
||||
"holder":"member_session",
|
||||
"verb":"impersonate_edge",
|
||||
"object":"internal-origin",
|
||||
"evidence":"guessed header",
|
||||
"confidence":"observed"
|
||||
}`)
|
||||
if unverRes.IsError {
|
||||
t.Fatalf("record_capability unverified failed: %s", unverRes.Flatten())
|
||||
}
|
||||
var unver struct {
|
||||
ID int64 `json:"id"`
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(unverRes.Flatten()), &unver); err != nil || unver.Verified {
|
||||
t.Fatalf("expected verified=false without proving refs, got: %s", unverRes.Flatten())
|
||||
}
|
||||
proveBody, _ := json.Marshal(map[string]any{
|
||||
"goal_id": goalID,
|
||||
"evidence_id": unver.ID,
|
||||
"reason": "claimed capability",
|
||||
})
|
||||
if res := callGuardTool(t, tsx.proveGoal(), string(proveBody)); !res.IsError || !strings.Contains(res.Flatten(), "unverified") {
|
||||
t.Fatalf("unverified capability must not satisfy a goal, got: %s", res.Flatten())
|
||||
}
|
||||
|
||||
// 2. Record a verified capability linked to a confirmed fact.
|
||||
factID, err := ts.AddNode(db.KindFact, map[string]any{
|
||||
"summary": "supersedes IDOR retired foreign cert",
|
||||
"source": "target_response",
|
||||
}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verBody, _ := json.Marshal(map[string]any{
|
||||
"status": "held",
|
||||
"holder": "member_session",
|
||||
"verb": "supersede_cert",
|
||||
"object": "foreign_cert",
|
||||
"evidence": "POST /api/v1/certificates/upload returned proof",
|
||||
"confidence": "observed",
|
||||
"proving_ids": []int64{factID},
|
||||
})
|
||||
verRes := callGuardTool(t, tsx.recordCapability(), string(verBody))
|
||||
if verRes.IsError {
|
||||
t.Fatalf("verified record_capability failed: %s", verRes.Flatten())
|
||||
}
|
||||
var ver struct {
|
||||
ID int64 `json:"id"`
|
||||
Verified bool `json:"verified"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(verRes.Flatten()), &ver); err != nil || !ver.Verified {
|
||||
t.Fatalf("expected verified=true with proving_ids, got: %s", verRes.Flatten())
|
||||
}
|
||||
|
||||
// Record a required capability so graph_overview shows both held and required.
|
||||
reqRes := callGuardTool(t, tsx.recordCapability(), `{
|
||||
"status":"required",
|
||||
"holder":"edge_peer",
|
||||
"verb":"present_enrolment",
|
||||
"object":"X-Estate-Peer",
|
||||
"evidence":"required for internal origin",
|
||||
"confidence":"observed"
|
||||
}`)
|
||||
if reqRes.IsError {
|
||||
t.Fatalf("required record_capability failed: %s", reqRes.Flatten())
|
||||
}
|
||||
|
||||
ov := tsx.graphOverviewData()
|
||||
held, _ := ov["capabilities_held"].([]map[string]any)
|
||||
req, _ := ov["capabilities_required"].([]map[string]any)
|
||||
if len(held) != 2 || len(req) != 1 {
|
||||
t.Fatalf("unexpected capability overview: held=%+v req=%+v", ov["capabilities_held"], ov["capabilities_required"])
|
||||
}
|
||||
|
||||
// 3. Shadow mode flags missing gains without rejecting; strict mode rejects missing gains.
|
||||
SetCapabilityStrictMode(false)
|
||||
shadowRes := callGuardTool(t, tsx.addIntent(), `{"summary":"Probe /docs without gains"}`)
|
||||
if shadowRes.IsError {
|
||||
t.Fatalf("shadow mode must not reject add_intent: %s", shadowRes.Flatten())
|
||||
}
|
||||
SetCapabilityStrictMode(true)
|
||||
strictRes := callGuardTool(t, tsx.addIntent(), `{"summary":"Probe /docs without gains"}`)
|
||||
if !strictRes.IsError || !strings.Contains(strictRes.Flatten(), "gains") {
|
||||
t.Fatalf("strict mode must reject add_intent without gains: %s", strictRes.Flatten())
|
||||
}
|
||||
}
|
||||
|
||||
type capabilityChainProvider struct {
|
||||
mu sync.Mutex
|
||||
reqs []llm.CompletionRequest
|
||||
round int
|
||||
}
|
||||
|
||||
func (p *capabilityChainProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
|
||||
p.mu.Lock()
|
||||
p.reqs = append(p.reqs, req)
|
||||
idx := len(p.reqs)
|
||||
p.mu.Unlock()
|
||||
var evs []llm.StreamEvent
|
||||
switch idx {
|
||||
case 1:
|
||||
// Round 1, turn 1: planner dispatches Step 1 with gains.
|
||||
evs = []llm.StreamEvent{
|
||||
{Type: llm.SEToolUseStart, ToolID: "c1", ToolName: "add_intent"},
|
||||
{Type: llm.SEToolInputJSON, Text: `{"summary":"Fetch pristine contract and enrolment record","gains":[{"verb":"read_enrolment","object":"estate_client"}]}`},
|
||||
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
|
||||
}
|
||||
case 2:
|
||||
evs = []llm.StreamEvent{{Type: llm.SETextDelta, Text: "Step 1 dispatched."}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}}
|
||||
case 3:
|
||||
// Round 2, turn 1: planner sees held capability and dispatches Step 2 consuming it.
|
||||
evs = []llm.StreamEvent{
|
||||
{Type: llm.SEToolUseStart, ToolID: "c2", ToolName: "add_intent"},
|
||||
{Type: llm.SEToolInputJSON, Text: `{"summary":"Present enrolment record in X-Estate-Peer","consumes":[{"verb":"read_enrolment","object":"estate_client"}],"gains":[{"verb":"access_origin","object":"internal_api"}]}`},
|
||||
{Type: llm.SEMessageDelta, StopReason: "tool_use"},
|
||||
}
|
||||
default:
|
||||
evs = []llm.StreamEvent{{Type: llm.SETextDelta, Text: "Step 2 dispatched."}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}}
|
||||
}
|
||||
return func(yield func(llm.StreamEvent, error) bool) {
|
||||
for _, ev := range evs {
|
||||
if !yield(ev, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *capabilityChainProvider) 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
|
||||
}
|
||||
|
||||
// End-to-end two-step chain planned from a capability gap.
|
||||
func TestPlannerTwoStepChainFromCapabilityGap(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
task, err := d.CreateTaskWithOptions("cap chain", "Acquire internal origin access via enrolment", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
|
||||
ts := d.Exploration(task.ExplorationID)
|
||||
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Access internal origin"}, 0, "open", "goals", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tsx := NewToolSet(ts, "planner")
|
||||
// Seed required capability gap.
|
||||
if res := callGuardTool(t, tsx.recordCapability(), `{"status":"required","holder":"edge_peer","verb":"access_origin","object":"internal_api","evidence":"goal requirement","confidence":"observed"}`); res.IsError {
|
||||
t.Fatal(res.Flatten())
|
||||
}
|
||||
|
||||
prov := &capabilityChainProvider{}
|
||||
pl := NewPlanner(prov, "test-model", t.TempDir(), nil, 0, 3)
|
||||
|
||||
// Round 1: sees capabilities_required gap, dispatches Step 1.
|
||||
if _, _, err := pl.Plan(t.Context(), task.ID, nil, ts, "Access internal origin", nil, nil, nil); err != nil {
|
||||
t.Fatalf("round 1 Plan failed: %v", err)
|
||||
}
|
||||
// Simulate Step 1 completing and granting verified capability.
|
||||
factID, err := ts.AddNode(db.KindFact, map[string]any{"summary": "Captured enrolment record"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
capBody, _ := json.Marshal(map[string]any{
|
||||
"status": "held", "holder": "member_session", "verb": "read_enrolment", "object": "estate_client",
|
||||
"evidence": "GET /api/v1/contract", "confidence": "observed", "proving_ids": []int64{factID},
|
||||
})
|
||||
if res := callGuardTool(t, tsx.recordCapability(), string(capBody)); res.IsError {
|
||||
t.Fatal(res.Flatten())
|
||||
}
|
||||
|
||||
// Round 2: sees capabilities_held + capabilities_required, dispatches Step 2 consuming Step 1's capability.
|
||||
if _, _, err := pl.Plan(t.Context(), task.ID, nil, ts, "Access internal origin", nil, nil, nil); err != nil {
|
||||
t.Fatalf("round 2 Plan failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify Round 2 prompt carried capabilities_held & capabilities_required and 2 chained intents exist.
|
||||
var r2Parts []string
|
||||
for _, msg := range prov.reqs[2].Messages {
|
||||
for _, b := range msg.Content {
|
||||
r2Parts = append(r2Parts, b.Text)
|
||||
}
|
||||
}
|
||||
r2Msg := strings.Join(r2Parts, "\n")
|
||||
if !strings.Contains(r2Msg, "capabilities_held") || !strings.Contains(r2Msg, "capabilities_required") {
|
||||
t.Fatalf("round 2 planner prompt missing capability ledger sections: %s", r2Msg)
|
||||
}
|
||||
intents, err := ts.ListByKind(db.KindIntent, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(intents) != 2 {
|
||||
t.Fatalf("expected 2 chained intents, got %d", len(intents))
|
||||
}
|
||||
if !strings.Contains(string(intents[0].Payload), "consumes") && !strings.Contains(string(intents[1].Payload), "consumes") {
|
||||
t.Fatalf("expected Step 2 intent to declare consumes, got payloads: %s / %s", intents[0].Payload, intents[1].Payload)
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
type hypothesisPayload struct {
|
||||
Subtype string `json:"subtype"`
|
||||
Status string `json:"status"`
|
||||
Hypothesis string `json:"hypothesis"`
|
||||
Direction string `json:"direction,omitempty"`
|
||||
CloseReason string `json:"close_reason,omitempty"`
|
||||
ReopenReason string `json:"reopen_reason,omitempty"`
|
||||
NewEvidence string `json:"new_evidence,omitempty"`
|
||||
}
|
||||
|
||||
func isHypothesisNode(n *db.Node) (hypothesisPayload, bool) {
|
||||
if n == nil || n.Kind != db.KindFact {
|
||||
return hypothesisPayload{}, false
|
||||
}
|
||||
var p hypothesisPayload
|
||||
if json.Unmarshal(n.Payload, &p) != nil || p.Subtype != db.FactSubtypeHypothesis {
|
||||
return hypothesisPayload{}, false
|
||||
}
|
||||
if p.Status == "" {
|
||||
if n.State == "stopped" {
|
||||
p.Status = "closed"
|
||||
} else {
|
||||
p.Status = "open"
|
||||
}
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func (t *ToolSet) upsertHypothesis() actool.CoreTool {
|
||||
return t.writeExpTool("upsert_hypothesis",
|
||||
"Create, update, or close a planner hypothesis. Closed hypotheses must record close_reason; add_intent rejects variants of a closed hypothesis unless both new_evidence and reopen_reason are provided.",
|
||||
obj(map[string]any{
|
||||
"id": idp("optional: existing hypothesis node ID to update/close/reopen"),
|
||||
"hypothesis": str("concise statement of the hypothesis (required when creating)"),
|
||||
"direction": str("optional: normalized attack direction/endpoint pattern used to match duplicate variants"),
|
||||
"status": map[string]any{"type": "string", "enum": []string{"open", "closed"}, "description": "hypothesis status (default open)"},
|
||||
"close_reason": str("required when status=closed: why this hypothesis is closed (e.g. negative_sweep, 403_cloudflare, state_churned)"),
|
||||
"new_evidence": str("required when reopening a closed hypothesis: new fact/finding summary"),
|
||||
"reopen_reason": str("required when reopening a closed hypothesis: why the close_reason no longer holds"),
|
||||
}),
|
||||
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Hypothesis string `json:"hypothesis"`
|
||||
Direction string `json:"direction"`
|
||||
Status string `json:"status"`
|
||||
CloseReason string `json:"close_reason"`
|
||||
NewEvidence string `json:"new_evidence"`
|
||||
ReopenReason string `json:"reopen_reason"`
|
||||
}
|
||||
if err := json.Unmarshal(in, &a); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
status := strings.ToLower(strings.TrimSpace(a.Status))
|
||||
if status == "" {
|
||||
status = "open"
|
||||
}
|
||||
if status != "open" && status != "closed" {
|
||||
return actool.Errorf("status must be open or closed"), nil
|
||||
}
|
||||
if status == "closed" && strings.TrimSpace(a.CloseReason) == "" {
|
||||
return actool.Errorf("close_reason is required when closing a hypothesis"), nil
|
||||
}
|
||||
|
||||
id := pid(a.ID)
|
||||
if id > 0 {
|
||||
n, err := t.ts.GetNode(id)
|
||||
p, ok := isHypothesisNode(n)
|
||||
if err != nil || !ok {
|
||||
return actool.Errorf(fmt.Sprintf("hypothesis #%d not found", id)), nil
|
||||
}
|
||||
if p.Status == "closed" && status == "open" {
|
||||
if strings.TrimSpace(a.NewEvidence) == "" || strings.TrimSpace(a.ReopenReason) == "" {
|
||||
return actool.Errorf("reopening a closed hypothesis requires both new_evidence and reopen_reason"), nil
|
||||
}
|
||||
p.NewEvidence = strings.TrimSpace(a.NewEvidence)
|
||||
p.ReopenReason = strings.TrimSpace(a.ReopenReason)
|
||||
}
|
||||
if h := strings.TrimSpace(a.Hypothesis); h != "" {
|
||||
p.Hypothesis = h
|
||||
}
|
||||
if d := strings.TrimSpace(a.Direction); d != "" {
|
||||
p.Direction = d
|
||||
}
|
||||
if status == "closed" {
|
||||
p.CloseReason = strings.TrimSpace(a.CloseReason)
|
||||
}
|
||||
if err := t.updateHypothesisNode(id, p, status); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
return jsonResult(map[string]any{"id": id, "status": status, "hypothesis": p.Hypothesis, "close_reason": p.CloseReason})
|
||||
}
|
||||
|
||||
hypText := strings.TrimSpace(a.Hypothesis)
|
||||
if hypText == "" {
|
||||
return actool.Errorf("hypothesis is required when creating a new hypothesis"), nil
|
||||
}
|
||||
p := map[string]any{
|
||||
"subtype": db.FactSubtypeHypothesis,
|
||||
"status": status,
|
||||
"hypothesis": hypText,
|
||||
}
|
||||
if d := strings.TrimSpace(a.Direction); d != "" {
|
||||
p["direction"] = d
|
||||
}
|
||||
if status == "closed" {
|
||||
p["close_reason"] = strings.TrimSpace(a.CloseReason)
|
||||
}
|
||||
newID, err := t.ts.AddNode(db.KindFact, p, 0, "confirmed", "planner", nil)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
return jsonResult(map[string]any{"id": newID, "status": status, "hypothesis": hypText, "close_reason": a.CloseReason})
|
||||
})
|
||||
}
|
||||
|
||||
func (t *ToolSet) updateHypothesisNode(id int64, p hypothesisPayload, status string) error {
|
||||
p.Subtype = db.FactSubtypeHypothesis
|
||||
p.Status = status
|
||||
raw, _ := json.Marshal(p)
|
||||
return t.ts.UpdateNodePayload(id, raw)
|
||||
}
|
||||
|
||||
func (t *ToolSet) checkClosedHypothesis(it intentItem) error {
|
||||
if t.ts == nil {
|
||||
return nil
|
||||
}
|
||||
nodes, err := t.ts.ListByKind(db.KindFact, 500)
|
||||
if err != nil || len(nodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
hypID := pid(it.HypothesisID)
|
||||
intentDir := normalizeDirection(it.Summary)
|
||||
var matched *db.Node
|
||||
var matchedPayload hypothesisPayload
|
||||
for _, n := range nodes {
|
||||
p, ok := isHypothesisNode(n)
|
||||
if !ok || p.Status != "closed" {
|
||||
continue
|
||||
}
|
||||
if hypID > 0 && n.ID == hypID {
|
||||
matched = n
|
||||
matchedPayload = p
|
||||
break
|
||||
}
|
||||
if intentDir != "" {
|
||||
hDir := normalizeDirection(p.Direction)
|
||||
if hDir == "" {
|
||||
hDir = normalizeDirection(p.Hypothesis)
|
||||
}
|
||||
if hDir != "" && hDir == intentDir {
|
||||
matched = n
|
||||
matchedPayload = p
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(it.NewEvidence) == "" || strings.TrimSpace(it.ReopenReason) == "" {
|
||||
return fmt.Errorf("hypothesis #%d is closed (%s): variants of a closed hypothesis are blocked unless both new_evidence and reopen_reason are provided", matched.ID, matchedPayload.CloseReason)
|
||||
}
|
||||
matchedPayload.NewEvidence = strings.TrimSpace(it.NewEvidence)
|
||||
matchedPayload.ReopenReason = strings.TrimSpace(it.ReopenReason)
|
||||
_ = t.updateHypothesisNode(matched.ID, matchedPayload, "open")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *ToolSet) hypothesisOverview() (openList, closedList []map[string]any) {
|
||||
if t.ts == nil {
|
||||
return nil, nil
|
||||
}
|
||||
nodes, err := t.ts.ListByKind(db.KindFact, 500)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
for _, n := range nodes {
|
||||
p, ok := isHypothesisNode(n)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
m := map[string]any{
|
||||
"id": n.ID,
|
||||
"hypothesis": p.Hypothesis,
|
||||
}
|
||||
if p.Direction != "" {
|
||||
m["direction"] = p.Direction
|
||||
}
|
||||
if p.Status == "closed" {
|
||||
m["close_reason"] = p.CloseReason
|
||||
closedList = append(closedList, m)
|
||||
} else {
|
||||
openList = append(openList, m)
|
||||
}
|
||||
}
|
||||
return openList, closedList
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHypothesisLedgerOverviewAndClosedVariantRejection(t *testing.T) {
|
||||
ts := guardTaskStore(t)
|
||||
tsx := NewToolSet(ts, "planner")
|
||||
|
||||
// 1. Create an open hypothesis and close it with close_reason.
|
||||
res, err := tsx.upsertHypothesis().Call(context.Background(), json.RawMessage(`{
|
||||
"hypothesis":"X-Estate-Peer accepts seed fingerprint",
|
||||
"direction":"Probe X-Estate-Peer with seed fingerprints",
|
||||
"status":"open"
|
||||
}`), nil)
|
||||
if err != nil || res.IsError {
|
||||
t.Fatalf("create hypothesis failed: %v %s", err, res.Flatten())
|
||||
}
|
||||
var created struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(res.Flatten()), &created); err != nil || created.ID <= 0 {
|
||||
t.Fatalf("parse created hypothesis: %v (%s)", err, res.Flatten())
|
||||
}
|
||||
|
||||
closeBody, _ := json.Marshal(map[string]any{
|
||||
"id": created.ID,
|
||||
"status": "closed",
|
||||
"close_reason": "negative_sweep_identical_responses",
|
||||
})
|
||||
if res := callGuardTool(t, tsx.upsertHypothesis(), string(closeBody)); res.IsError {
|
||||
t.Fatalf("close hypothesis failed: %s", res.Flatten())
|
||||
}
|
||||
|
||||
// 2. graph_overview surfaces closed_hypotheses.
|
||||
ov := tsx.graphOverviewData()
|
||||
closed, _ := ov["closed_hypotheses"].([]map[string]any)
|
||||
if len(closed) != 1 || closed[0]["close_reason"] != "negative_sweep_identical_responses" {
|
||||
t.Fatalf("expected 1 closed hypothesis in overview, got %+v", ov["closed_hypotheses"])
|
||||
}
|
||||
|
||||
// 3. add_intent rejects variants matching by hypothesis_id OR normalized direction.
|
||||
byID, _ := json.Marshal(map[string]any{
|
||||
"summary": "Try another X-Estate-Peer header",
|
||||
"hypothesis_id": created.ID,
|
||||
})
|
||||
if res := callGuardTool(t, tsx.addIntent(), string(byID)); !res.IsError || !strings.Contains(res.Flatten(), "is closed") {
|
||||
t.Fatalf("expected closed hypothesis_id rejection, got: %s", res.Flatten())
|
||||
}
|
||||
|
||||
byDir := `{"summary":"Probe X-Estate-Peer with seed fingerprints"}`
|
||||
if res := callGuardTool(t, tsx.addIntent(), byDir); !res.IsError || !strings.Contains(res.Flatten(), "is closed") {
|
||||
t.Fatalf("expected closed normalized-direction rejection, got: %s", res.Flatten())
|
||||
}
|
||||
|
||||
// 4. Providing both new_evidence and reopen_reason reopens the hypothesis and creates the intent.
|
||||
reopen, _ := json.Marshal(map[string]any{
|
||||
"summary": "Test X-Estate-Peer with enrolment token from contract",
|
||||
"hypothesis_id": created.ID,
|
||||
"new_evidence": "GET /api/v1/contract returned enrolment_token",
|
||||
"reopen_reason": "enrolment record format differs from seed fingerprint",
|
||||
})
|
||||
if res := callGuardTool(t, tsx.addIntent(), string(reopen)); res.IsError {
|
||||
t.Fatalf("reopen add_intent failed: %s", res.Flatten())
|
||||
}
|
||||
ov2 := tsx.graphOverviewData()
|
||||
if openH, _ := ov2["open_hypotheses"].([]map[string]any); len(openH) != 1 {
|
||||
t.Fatalf("expected reopened hypothesis in open_hypotheses, got %+v", ov2["open_hypotheses"])
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -169,7 +169,7 @@ func renderPlannerTodos(items []actool.Todo, env dataEnvelope) string {
|
||||
// the planner's own todos, and last the code-owned goal anchor, so the operator's
|
||||
// goal is the final thing read after all the data.
|
||||
func plannerRoundInput(lead, situational, todos, goal, constraints string) string {
|
||||
return lead + situational + "\n\nJudge the goals from the situation above. When a goal is [truly met] (the goal's deliverable obtained / the goal's vulnerability confirmed), mark each with prove_goal. **Hard floor: as long as the goal is unmet and there are currently no open or running intents (frontier_open=0 and running_intents is empty), this round must produce at least one intent advancing toward the goal — at that point there is no running work to wait for and no queued direction, so producing 0 intents = the task stalls. Only when open/running intents are already advancing, or the goal is met, may this round produce no new intents.**" +
|
||||
return lead + situational + "\n\nJudge the goals from the situation above. When a goal is [truly met] (the goal's deliverable obtained / the goal's vulnerability confirmed), mark each with prove_goal. **Hard floor: as long as the goal is unmet and there are currently no open or running intents (frontier_open=0 and running_intents is empty), this round must produce at least one intent advancing toward the goal — at that point there is no running work to wait for and no queued direction, so producing 0 intents = the task stalls. Only when open/running intents are already advancing, or the goal is met, may this round produce no new intents.** Never generate variants of a hypothesis listed in closed_hypotheses unless new evidence justifies reopening it. Plan from capability gaps (goal -> capabilities_required vs capabilities_held -> intent with gains/consumes); never assume a capability in capabilities_closed. A capability here is an exploitation capability: a power obtained over the target (actor can do action on object), not a permission granted to this agent." +
|
||||
todos + plannerGoalAnchor(goal, constraints)
|
||||
}
|
||||
|
||||
|
||||
+57
-1
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+102
-19
@@ -3,6 +3,7 @@ package agent
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
@@ -645,6 +646,12 @@ func (t *ToolSet) graphOverviewData() map[string]any {
|
||||
if len(recentFacts) >= recentFactsCap {
|
||||
break
|
||||
}
|
||||
if _, isHyp := isHypothesisNode(n); isHyp {
|
||||
continue
|
||||
}
|
||||
if _, isCap := isCapabilityNode(n); isCap {
|
||||
continue
|
||||
}
|
||||
if hidden(n.ID) {
|
||||
continue // folded into a digest and still cold — see cold_digests
|
||||
}
|
||||
@@ -699,6 +706,25 @@ func (t *ToolSet) graphOverviewData() map[string]any {
|
||||
// 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
|
||||
// frontier or get mistaken for locally claimable work.
|
||||
if heldCap, reqCap, closedCap := t.capabilityOverview(); len(heldCap) > 0 || len(reqCap) > 0 || len(closedCap) > 0 {
|
||||
if len(heldCap) > 0 {
|
||||
out["capabilities_held"] = heldCap
|
||||
}
|
||||
if len(reqCap) > 0 {
|
||||
out["capabilities_required"] = reqCap
|
||||
}
|
||||
if len(closedCap) > 0 {
|
||||
out["capabilities_closed"] = closedCap
|
||||
}
|
||||
}
|
||||
if openHyp, closedHyp := t.hypothesisOverview(); len(openHyp) > 0 || len(closedHyp) > 0 {
|
||||
if len(openHyp) > 0 {
|
||||
out["open_hypotheses"] = openHyp
|
||||
}
|
||||
if len(closedHyp) > 0 {
|
||||
out["closed_hypotheses"] = closedHyp
|
||||
}
|
||||
}
|
||||
out["related_tasks"] = t.relatedTaskOverviews()
|
||||
// coverage: a rough reference for asset test coverage — among the assets inside
|
||||
// the scope (task_scope), the share touched by facts + by_type (total/tested per
|
||||
@@ -1306,10 +1332,15 @@ func (t *ToolSet) nodeDetail() actool.CoreTool {
|
||||
|
||||
// intentItem is one exploration direction of an add_intent batch/single call.
|
||||
type intentItem struct {
|
||||
Summary string `json:"summary"`
|
||||
AssetIDs []json.RawMessage `json:"asset_ids"`
|
||||
ParentIDs []json.RawMessage `json:"parent_ids"`
|
||||
Priority int `json:"priority"`
|
||||
Summary string `json:"summary"`
|
||||
AssetIDs []json.RawMessage `json:"asset_ids"`
|
||||
ParentIDs []json.RawMessage `json:"parent_ids"`
|
||||
Priority int `json:"priority"`
|
||||
HypothesisID json.RawMessage `json:"hypothesis_id"`
|
||||
NewEvidence string `json:"new_evidence"`
|
||||
ReopenReason string `json:"reopen_reason"`
|
||||
Gains []json.RawMessage `json:"gains"`
|
||||
Consumes []json.RawMessage `json:"consumes"`
|
||||
}
|
||||
|
||||
// addOneIntent creates one intent node, links its upstream lineage, and returns the id.
|
||||
@@ -1322,6 +1353,13 @@ func (t *ToolSet) addOneIntent(it intentItem) (int64, error) {
|
||||
if strings.TrimSpace(it.Summary) == "" {
|
||||
return 0, fmt.Errorf("summary must not be empty")
|
||||
}
|
||||
if err := t.checkClosedHypothesis(it); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
capWarn, err := t.checkIntentCapabilities(it)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Validate anchors first (before creating the node, so a bad anchor leaves no orphan intent).
|
||||
parents := pidList(it.ParentIDs)
|
||||
for _, pidv := range parents {
|
||||
@@ -1358,6 +1396,15 @@ func (t *ToolSet) addOneIntent(it intentItem) (int64, error) {
|
||||
if len(anchors) > 0 {
|
||||
payload["asset_ids"] = anchors
|
||||
}
|
||||
if len(it.Gains) > 0 {
|
||||
payload["gains"] = it.Gains
|
||||
}
|
||||
if len(it.Consumes) > 0 {
|
||||
payload["consumes"] = it.Consumes
|
||||
}
|
||||
if capWarn != "" {
|
||||
payload["capability_shadow_warning"] = capWarn
|
||||
}
|
||||
id, err := t.ts.AddIntent(payload, priority, anchors, "planner")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -1382,11 +1429,16 @@ func (t *ToolSet) addIntent() actool.CoreTool {
|
||||
return t.writeExpTool("add_intent", "Generate [exploration directions] into the frontier and link them into the exploration graph. An intent is an open exploration direction, not a fixed type — describe freely in one summary sentence what to explore/verify/exploit.\n"+
|
||||
"★Batch preferred: put multiple new directions filtered in one round into the intents array in a single submission (saves round trips vs. one call per item). Returns an ids array, same length and order as intents (failed items get id=0, details in errors). For a single intent, omit intents and pass the top-level summary.",
|
||||
obj(map[string]any{
|
||||
"intents": map[string]any{"type": "array", "description": "[Prefer this] array of exploration directions to add, processed in order. Each element has the same fields as the top-level ones below (summary/asset_ids/parent_ids/priority). The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}},
|
||||
"summary": str("[single] one sentence describing this exploration direction: what to do + why. Just write the direction clearly; asset ids are not required."),
|
||||
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "the [target asset ids] this direction tests/attacks (**pass whenever possible**, 0/1/many; these are asset ids from list_assets, not exploration node ids): which assets (sites/endpoints/parameters/hosts etc.) this direction targets. Whenever the direction revolves around concrete assets, be sure to pass them — it is the structured marker of 'which targets this exploration hits', used for coverage dedup and linking the intent into the asset lineage. Leave empty only for pure global recon with truly no concrete target assets."},
|
||||
"parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "upstream anchor ids (optional, 0/1/many): which [confirmed fact/finding] nodes this direction is synthesized from. **Only existing fact/finding node ids may be passed — not intents/goals/hints** — an intent must anchor on confirmed knowledge, finding-driven rather than planned out of thin air. Pass several when multiple facts jointly produce one new intent; leave empty for a top-level brand-new recon direction (it is automatically attached to the task's origin fact)."},
|
||||
"priority": intp("priority 0-10, default 5"),
|
||||
"intents": map[string]any{"type": "array", "description": "[Prefer this] array of exploration directions to add, processed in order. Each element has the same fields as the top-level ones below (summary/asset_ids/parent_ids/priority). The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}},
|
||||
"summary": str("[single] one sentence describing this exploration direction: what to do + why. Just write the direction clearly; asset ids are not required."),
|
||||
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "the [target asset ids] this direction tests/attacks (**pass whenever possible**, 0/1/many; these are asset ids from list_assets, not exploration node ids): which assets (sites/endpoints/parameters/hosts etc.) this direction targets. Whenever the direction revolves around concrete assets, be sure to pass them — it is the structured marker of 'which targets this exploration hits', used for coverage dedup and linking the intent into the asset lineage. Leave empty only for pure global recon with truly no concrete target assets."},
|
||||
"parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "upstream anchor ids (optional, 0/1/many): which [confirmed fact/finding] nodes this direction is synthesized from. **Only existing fact/finding node ids may be passed — not intents/goals/hints** — an intent must anchor on confirmed knowledge, finding-driven rather than planned out of thin air. Pass several when multiple facts jointly produce one new intent; leave empty for a top-level brand-new recon direction (it is automatically attached to the task's origin fact)."},
|
||||
"priority": intp("priority 0-10, default 5"),
|
||||
"hypothesis_id": idp("optional: hypothesis node id this intent tests"),
|
||||
"new_evidence": str("required when reopening a closed hypothesis"),
|
||||
"reopen_reason": str("required when reopening a closed hypothesis"),
|
||||
"gains": map[string]any{"type": "array", "description": "capabilities this intent aims to acquire (capability ids or {verb,object} objects)", "items": map[string]any{}},
|
||||
"consumes": map[string]any{"type": "array", "description": "capabilities this intent depends on (capability ids or {verb,object} objects)", "items": map[string]any{}},
|
||||
}),
|
||||
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
@@ -1482,6 +1534,9 @@ func (t *ToolSet) proveGoal() actool.CoreTool {
|
||||
// A fact proves a goal only when it was seen directly (#124, F5): an inferred
|
||||
// conclusion, or one without a confidence, is refused and the goal stays open.
|
||||
// The confidence is declared by the agent that recorded the fact.
|
||||
if cp, isCap := isCapabilityNode(evidenceNode); isCap && !cp.Verified {
|
||||
return actool.Errorf(fmt.Sprintf("prove_goal refused: capability #%d is unverified (requires a proving finding, fact, or traffic reference)", ev)), nil
|
||||
}
|
||||
if evidenceNode.Kind == db.KindFact {
|
||||
var fp map[string]any
|
||||
_ = json.Unmarshal(evidenceNode.Payload, &fp)
|
||||
@@ -1616,16 +1671,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
|
||||
@@ -1644,6 +1706,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,
|
||||
@@ -1696,6 +1772,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
|
||||
})
|
||||
@@ -2628,7 +2711,7 @@ func (t *ToolSet) PlannerTools() []actool.CoreTool {
|
||||
t.graphOverview(), t.listFindings(), t.listFacts(), t.nodeDetail(), t.knowledgeLookup(),
|
||||
// cold-digest §6.1: restore folded cold nodes (digest body → members → detail).
|
||||
t.expandDigest(),
|
||||
t.getWorkerOutput(), t.getWorkerTrace(), t.searchAllWorkerTraces(), t.listGoals(), t.addIntent(), t.proveGoal(), t.goalMet(),
|
||||
t.getWorkerOutput(), t.getWorkerTrace(), t.searchAllWorkerTraces(), t.listGoals(), t.upsertHypothesis(), t.recordCapability(), t.addIntent(), t.proveGoal(), t.goalMet(),
|
||||
t.killWorkTool(), t.steerWorkTool(),
|
||||
// report_finding: if the planner itself has confirmed a finding during
|
||||
// situational assessment, it can register it directly (same tool as the worker's).
|
||||
|
||||
@@ -38,3 +38,11 @@ const (
|
||||
RelProves = "proves"
|
||||
RelCovers = "covers" // digest --covers--> member (cold-digest-spec §1); source of truth for "which digest folds node X"
|
||||
)
|
||||
|
||||
// FactSubtypeHypothesis tags kind=fact nodes that represent planner hypotheses
|
||||
// without altering ck_node_kind (zero schema migration).
|
||||
const FactSubtypeHypothesis = "hypothesis"
|
||||
|
||||
// FactSubtypeCapability tags kind=fact nodes that represent capabilities (#613)
|
||||
// without altering ck_node_kind (zero schema migration).
|
||||
const FactSubtypeCapability = "capability"
|
||||
|
||||
@@ -2360,3 +2360,9 @@ func (s *ExplorationStore) ActivityByIDsForTerminalIntents(ids []int64) ([]Activ
|
||||
func (s *ExplorationStore) AddStandaloneFinding(taskID, nodeID int64, vulnclass, name, severity, summary, evidence, worker string, assetIDs []int64) (int64, error) {
|
||||
return s.db.AddFinding(taskID, nodeID, vulnclass, name, severity, summary, evidence, worker, assetIDs)
|
||||
}
|
||||
|
||||
// UpdateNodePayload updates a node's JSON payload and bumps content_version.
|
||||
func (s *ExplorationStore) UpdateNodePayload(id int64, raw json.RawMessage) error {
|
||||
_, err := s.db.Exec(`UPDATE exploration_nodes SET payload=$1, content_version=content_version+1 WHERE id=$2 AND exploration_id=$3`, string(raw), id, s.expID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
+163
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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{}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ var noTargetTools = toolSet(
|
||||
// exploration graph, assets, findings, goals (agent.ToolSet)
|
||||
"graph_overview", "list_findings", "list_facts", "node_detail", "expand_digest",
|
||||
"get_worker_output", "get_worker_trace", "search_all_worker_traces",
|
||||
"add_hint", "add_intent", "steer_work", "kill_work",
|
||||
"add_hint", "add_intent", "upsert_hypothesis", "record_capability", "steer_work", "kill_work",
|
||||
"set_goals", "set_constraints", "list_goals", "prove_goal", "goal_met",
|
||||
"insert_assets", "add_company_scope", "add_task_scope", "list_assets",
|
||||
"list_untested_assets", "list_companies", "report_finding", "record_fact",
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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":
|
||||
|
||||
+5
-1
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user