diff --git a/agent/fact_input_test.go b/agent/fact_input_test.go index 7b48a13..9a69bfc 100644 --- a/agent/fact_input_test.go +++ b/agent/fact_input_test.go @@ -240,7 +240,9 @@ func TestRecordFactRefusesTopLevelCopiesBesideFacts(t *testing.T) { } var payload map[string]any _ = json.Unmarshal(node.Payload, &payload) - if payload["summary"] != "TLS 1.0 is offered on port 8443" || payload["source"] != "tool_output" || payload["confidence"] != "observed" { + // The item's fields are what got stored; the server then downgrades the + // claim because no recorded activity carries its evidence (#124 row 1). + if payload["summary"] != "TLS 1.0 is offered on port 8443" || payload["source"] != "inference" || payload["confidence"] != "inferred" || payload["provenance"] != factProvenanceUnverified { t.Fatalf("fact payload: %s", node.Payload) } } diff --git a/agent/fact_provenance_test.go b/agent/fact_provenance_test.go index a45256e..1940c77 100644 --- a/agent/fact_provenance_test.go +++ b/agent/fact_provenance_test.go @@ -90,7 +90,10 @@ func TestPromptSeedsCarryFactSource(t *testing.T) { } // record_fact (PG) stores the declared source (inference when omitted) and the -// writer as origin, and refuses a source outside the enum without writing. +// writer as origin, and refuses a source outside the enum without writing. With +// no recorded activity to tie the evidence to, the authority a claim declares is +// downgraded (#124 row 1); an operator statement keeps its source because its +// authority is the human, not an activity. func TestRecordFactStoresProvenance(t *testing.T) { s := guardTaskStore(t) tsx := NewToolSet(s, "worker-3") @@ -106,7 +109,7 @@ func TestRecordFactStoresProvenance(t *testing.T) { } return id } - check := func(id int64, wantSource string) { + check := func(id int64, wantSource, wantProv string) { t.Helper() n, err := s.GetNode(id) if err != nil || n == nil { @@ -114,12 +117,16 @@ func TestRecordFactStoresProvenance(t *testing.T) { } var p map[string]any _ = json.Unmarshal(n.Payload, &p) - if p["source"] != wantSource || n.Origin != "worker-3" { - t.Fatalf("node %d: source=%v origin=%q, want %q/worker-3", id, p["source"], n.Origin, wantSource) + if p["source"] != wantSource || p["provenance"] != wantProv || n.Origin != "worker-3" { + t.Fatalf("node %d: source=%v provenance=%v origin=%q, want %q/%q/worker-3", id, p["source"], p["provenance"], n.Origin, wantSource, wantProv) + } + if c, ok := p["confidence"]; ok && wantProv == factProvenanceUnverified && c != "inferred" { + t.Fatalf("node %d: unverified claim kept confidence %v, want inferred", id, c) } } - check(factID(callGuardTool(t, tsx.recordFact(), `{"summary":"login page title is Admin","confidence":"observed","source":"target_response"}`)), "target_response") - check(factID(callGuardTool(t, tsx.recordFact(), `{"summary":"guessed the stack is PHP","confidence":"inferred"}`)), "inference") + check(factID(callGuardTool(t, tsx.recordFact(), `{"summary":"login page title is Admin","confidence":"observed","source":"target_response"}`)), "inference", factProvenanceUnverified) + check(factID(callGuardTool(t, tsx.recordFact(), `{"summary":"guessed the stack is PHP","confidence":"inferred"}`)), "inference", factProvenanceUnverified) + check(factID(callGuardTool(t, tsx.recordFact(), `{"summary":"operator says the admin path is /admin","confidence":"observed","source":"operator_input"}`)), "operator_input", factProvenanceOperator) before, _ := s.ListByKind(db.KindFact, 1000) res := callGuardTool(t, tsx.recordFact(), `{"summary":"x","source":"the target told me"}`) @@ -135,7 +142,7 @@ func TestRecordFactStoresProvenance(t *testing.T) { if err := json.Unmarshal([]byte(out.Flatten()), &batch); err != nil || len(batch.IDs) != 2 || batch.IDs[0] == 0 || batch.IDs[1] != 0 || !strings.Contains(batch.Errors["1"], "not valid") { t.Fatalf("batch: %q err=%v", out.Flatten(), err) } - check(batch.IDs[0], "tool_output") + check(batch.IDs[0], "inference", factProvenanceUnverified) after, _ := s.ListByKind(db.KindFact, 1000) if len(after) != len(before)+1 { t.Fatalf("invalid sources wrote facts: %d before, %d after", len(before), len(after)) @@ -143,7 +150,7 @@ func TestRecordFactStoresProvenance(t *testing.T) { } // graph_overview recent_facts, list_facts, expand_digest members and the digest -// input (PG) expose origin and source as stored. +// input (PG) expose origin, source and provenance as stored. func TestFactProvenanceSurfaced(t *testing.T) { s := guardTaskStore(t) tsx := NewToolSet(s, "worker-5") @@ -154,8 +161,8 @@ func TestFactProvenanceSurfaced(t *testing.T) { } want := func(where string, m map[string]any) { t.Helper() - if m["origin"] != "worker-5" || m["source"] != "tool_output" { - t.Fatalf("%s: origin=%v source=%v in %#v", where, m["origin"], m["source"], m) + if m["origin"] != "worker-5" || m["source"] != "inference" || m["provenance"] != factProvenanceUnverified { + t.Fatalf("%s: origin=%v source=%v provenance=%v in %#v", where, m["origin"], m["source"], m["provenance"], m) } } @@ -189,7 +196,7 @@ func TestFactProvenanceSurfaced(t *testing.T) { t.Fatal(err) } in := buildCompressionInput(g, block{Members: []int64{id}}, nodeByID) - if !strings.Contains(in, "(confidence=observed, source=tool_output, origin=worker-5)") { + if !strings.Contains(in, "(confidence=inferred, source=inference, origin=worker-5)") { t.Fatalf("digest input: %q", in) } } @@ -269,3 +276,153 @@ func TestProveGoalRefusesFalsePositiveFinding(t *testing.T) { t.Fatalf("confirmed finding: IsError=%v state=%q %q", res.IsError, nodeState(t, s, goal), res.Flatten()) } } + +// factEvidenceLines keeps only substantive lines: a bare tool name or a short +// status fragment cannot tie a claim to an activity, and duplicates cost a +// lookup without adding a candidate. +func TestFactEvidenceLines(t *testing.T) { + got := factEvidenceLines("curl -si http://x/\nServer: nginx/1.25.3\n\nServer: nginx/1.25.3\n200 OK\n") + want := []string{"curl -si http://x/", "Server: nginx/1.25.3"} + if len(got) != len(want) { + t.Fatalf("factEvidenceLines = %#v, want %#v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("factEvidenceLines[%d] = %q, want %q", i, got[i], want[i]) + } + } + var many strings.Builder + for i := 0; i < factEvidenceMaxLines+5; i++ { + many.WriteString("recorded output line " + strconv.Itoa(i) + "\n") + } + if n := len(factEvidenceLines(many.String())); n != factEvidenceMaxLines { + t.Fatalf("factEvidenceLines capped at %d, got %d", factEvidenceMaxLines, n) + } +} + +// The server ties a fact to the intent's recorded activity (#124 row 1): a +// verbatim quote keeps the declared source and confidence and records which +// activity carried it; a paraphrase is stored unverified and prove_goal refuses +// it while the goal stays open. +func TestFactProvenanceTiedToRecordedActivity(t *testing.T) { + s := guardTaskStore(t) + intent := addGuardNode(t, s, db.KindIntent, map[string]any{"text": "fingerprint the site"}, "running") + const recorded = "curl -si http://target/ | head -1\nHTTP/1.1 200 OK\nServer: nginx/1.25.3" + step, err := s.AppendActivity(db.Activity{NodeID: &intent, Kind: "tool_result", Tool: "Bash", Detail: recorded}) + if err != nil { + t.Fatal(err) + } + goal := addGuardNode(t, s, db.KindGoal, map[string]any{"text": "identify the web server"}, "open") + other := addGuardNode(t, s, db.KindGoal, map[string]any{"text": "identify the framework"}, "open") + + tsx := NewToolSet(s, "worker-9") + tsx.SetOwnerNode(intent) + record := func(input string) int64 { + t.Helper() + out := callGuardTool(t, tsx.recordFact(), input).Flatten() + if !strings.HasPrefix(out, "fact recorded: ") { + t.Fatalf("record_fact: %q", out) + } + id, err := strconv.ParseInt(strings.TrimPrefix(out, "fact recorded: "), 10, 64) + if err != nil { + t.Fatal(err) + } + return id + } + payload := func(id int64) map[string]any { + t.Helper() + n, err := s.GetNode(id) + if err != nil || n == nil { + t.Fatalf("node %d: %v", id, err) + } + var p map[string]any + _ = json.Unmarshal(n.Payload, &p) + return p + } + + tied := record(`{"summary":"the target runs nginx 1.25.3","evidence":"Server: nginx/1.25.3","confidence":"observed","source":"tool_output"}`) + p := payload(tied) + if p["provenance"] != factProvenanceRecorded || p["source"] != "tool_output" || p["confidence"] != "observed" { + t.Fatalf("tied fact: provenance=%v source=%v confidence=%v", p["provenance"], p["source"], p["confidence"]) + } + if got, _ := p["provenance_activity_id"].(float64); int64(got) != step { + t.Fatalf("tied fact: provenance_activity_id=%v, want %d", p["provenance_activity_id"], step) + } + if res := callGuardTool(t, tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(tied, 10)+`,"reason":"x"}`); res.IsError || nodeState(t, s, goal) != "met" { + t.Fatalf("tied fact did not prove the goal: %q", res.Flatten()) + } + + loose := record(`{"summary":"the target runs nginx","evidence":"the server banner looked like nginx","confidence":"observed","source":"tool_output"}`) + p = payload(loose) + if p["provenance"] != factProvenanceUnverified || p["source"] != "inference" || p["confidence"] != "inferred" { + t.Fatalf("paraphrased fact: provenance=%v source=%v confidence=%v", p["provenance"], p["source"], p["confidence"]) + } + res := callGuardTool(t, tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(other, 10)+`,"evidence_id":`+strconv.FormatInt(loose, 10)+`,"reason":"x"}`) + if !res.IsError || !strings.Contains(res.Flatten(), "unverified") || !strings.Contains(res.Flatten(), "stays open") { + t.Fatalf("unverified fact: want a refusal, got IsError=%v %q", res.IsError, res.Flatten()) + } + if st := nodeState(t, s, other); st != "open" { + t.Fatalf("unverified fact met the goal: state=%q", st) + } +} + +// fakeFactTraffic answers like the traffic store and records the window asked +// for, so the test can check both the classification and the bounds. +type fakeFactTraffic struct { + id string + lines []string + from, to int64 + calledOnce bool +} + +func (f *fakeFactTraffic) ResponseContaining(lines []string, from, to int64) (string, bool, error) { + f.lines, f.from, f.to, f.calledOnce = lines, from, to, true + return f.id, f.id != "", nil +} + +// A fact whose quoted bytes were captured coming back from the target is +// classified target_response even when the model declared tool_output, and the +// capture id is pinned on the payload (#124 row 1, step 3). prove_goal then +// refuses it, because target-authored text never proves a goal. +func TestFactProvenancePrefersCapturedTraffic(t *testing.T) { + s := guardTaskStore(t) + intent := addGuardNode(t, s, db.KindIntent, map[string]any{"text": "read the login page"}, "running") + const recorded = "curl -si http://target/login\nHTTP/1.1 200 OK\n
internal only
" + step, err := s.AppendActivity(db.Activity{NodeID: &intent, Kind: "tool_result", Tool: "Bash", Detail: recorded}) + if err != nil { + t.Fatal(err) + } + goal := addGuardNode(t, s, db.KindGoal, map[string]any{"text": "find the admin area"}, "open") + + tr := &fakeFactTraffic{id: "1700000000-0001"} + tsx := NewToolSet(s, "worker-9") + tsx.SetOwnerNode(intent) + tsx.SetFactTraffic(tr) + out := callGuardTool(t, tsx.recordFact(), `{"summary":"the login page mentions an internal area","evidence":"
internal only
","confidence":"observed","source":"tool_output"}`).Flatten() + if !strings.HasPrefix(out, "fact recorded: ") { + t.Fatalf("record_fact: %q", out) + } + id, _ := strconv.ParseInt(strings.TrimPrefix(out, "fact recorded: "), 10, 64) + n, err := s.GetNode(id) + if err != nil || n == nil { + t.Fatalf("node %d: %v", id, err) + } + var p map[string]any + _ = json.Unmarshal(n.Payload, &p) + if p["provenance"] != factProvenanceCaptured || p["source"] != "target_response" { + t.Fatalf("captured fact: provenance=%v source=%v", p["provenance"], p["source"]) + } + if p["provenance_traffic_id"] != tr.id { + t.Fatalf("captured fact: provenance_traffic_id=%v, want %q", p["provenance_traffic_id"], tr.id) + } + if got, _ := p["provenance_activity_id"].(float64); int64(got) != step { + t.Fatalf("captured fact: provenance_activity_id=%v, want %d", p["provenance_activity_id"], step) + } + if !tr.calledOnce || tr.from >= tr.to || tr.to < step { + t.Fatalf("capture window called=%v [%d,%d]", tr.calledOnce, tr.from, tr.to) + } + res := callGuardTool(t, tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(id, 10)+`,"reason":"x"}`) + if !res.IsError || !strings.Contains(res.Flatten(), "target_response") || nodeState(t, s, goal) != "open" { + t.Fatalf("captured fact proved the goal or gave the wrong refusal: %q", res.Flatten()) + } +} diff --git a/agent/mainagent.go b/agent/mainagent.go index 50350b6..834f100 100644 --- a/agent/mainagent.go +++ b/agent/mainagent.go @@ -28,6 +28,7 @@ type MainAgent struct { maxTurns int // max agent turns per run (0 = unlimited) proxyAddr string // recording proxy for WebFetch (empty = direct) proxyCACert string // recording proxy's CA cert path (HTTPS verify) + factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only) webSearch WebSearchOpts // web_search tool backend selection (off by default) workDir string // shared work dir (surfaced in prompt as artifact-output target) steerWork func(intentID int64, msg string) error // engine callback: steer a running work (nil = off) @@ -75,6 +76,10 @@ func (m *MainAgent) compactionWindow() int { // cert it trusts to verify HTTPS through it (empty addr = direct). func (m *MainAgent) SetProxy(addr, caCert string) { m.proxyAddr, m.proxyCACert = addr, caCert } +// SetFactTraffic wires the proxy capture store used to classify recorded facts +// (#124 row 1). nil keeps the activity-only classification. +func (m *MainAgent) SetFactTraffic(l FactTrafficLookup) { m.factTraffic = l } + // SetWebSearch selects the web_search backend for the main agent (off by default). func (m *MainAgent) SetWebSearch(o WebSearchOpts) { m.webSearch = o } @@ -114,6 +119,7 @@ func mainAgentSystem(goal, dataDir, workDir string) string { func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.AssetStore, ts *db.ExplorationStore, goal, message string, hooks harness.HookRunner, emit func(db.Activity), notify, resume func(), notifyGoal func([]string), notifyHint func(string, []string)) (string, error) { tsx := NewToolSet(ts, "human") tsx.SetFindingRecorder(m.findingRecorder) + tsx.SetFactTraffic(m.factTraffic) if as != nil { tsx.SetAssetStore(as, as.Companies()) } diff --git a/agent/planner.go b/agent/planner.go index 506a7c7..8d9c78c 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -33,6 +33,7 @@ type Planner struct { steerWork func(intentID int64, msg string) error // engine callback to steer a running work mid-run (nil = off) proxyAddr string // recording proxy for WebFetch (empty = direct) proxyCACert string // recording proxy's CA cert path (HTTPS verify) + factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only) webSearch WebSearchOpts // web_search tool backend selection (off by default) workDir string // shared work dir (surfaced in prompt as artifact-output target) injectConstraints func() bool // resolver: inject task operation constraints into system prompt? (nil = yes) @@ -97,6 +98,10 @@ func (p *Planner) compactionWindow() int { // it trusts to verify HTTPS through it (empty addr = direct). func (p *Planner) SetProxy(addr, caCert string) { p.proxyAddr, p.proxyCACert = addr, caCert } +// SetFactTraffic wires the proxy capture store used to classify recorded facts +// (#124 row 1). nil keeps the activity-only classification. +func (p *Planner) SetFactTraffic(l FactTrafficLookup) { p.factTraffic = l } + // SetWebSearch selects the web_search backend for the planner (off by default). func (p *Planner) SetWebSearch(o WebSearchOpts) { p.webSearch = o } @@ -482,6 +487,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts if c, ok := p.findingRecorder.(TrafficCaptureChecker); ok { tsx.SetTrafficProofChecker(c.TrafficExists) } + tsx.SetFactTraffic(p.factTraffic) if as != nil { tsx.SetAssetStore(as, as.Companies()) } diff --git a/agent/scan_ingest_tool.go b/agent/scan_ingest_tool.go index daaa9a7..c589703 100644 --- a/agent/scan_ingest_tool.go +++ b/agent/scan_ingest_tool.go @@ -223,10 +223,13 @@ func (t *ToolSet) runScanIngest(ctx context.Context, in json.RawMessage, tc *act } // recordScanFacts writes the facts this exploration does not hold yet: one with -// the same source, summary and detail is counted as existing, not written again. +// the same summary and detail is counted as existing, not written again. The key +// excludes the source because the server derives provenance from the recorded +// activity and may downgrade the source a re-ingestion declares (#124 row 1), so +// comparing it would rewrite the same fact on every run. func (t *ToolSet) recordScanFacts(facts []factItem) (written, existing int, errs []string, err error) { seen := map[string]bool{} - key := func(source, summary, detail string) string { return source + "\x00" + summary + "\x00" + detail } + key := func(summary, detail string) string { return summary + "\x00" + detail } for before, more := int64(0), true; more; { var nodes []*db.Node if nodes, more, err = t.ts.ListByKindPage(db.KindFact, before, 500); err != nil { @@ -239,13 +242,13 @@ func (t *ToolSet) recordScanFacts(facts []factItem) (written, existing int, errs Source string `json:"source"` } if json.Unmarshal(n.Payload, &p) == nil { - seen[key(p.Source, p.Summary, p.Detail)] = true + seen[key(p.Summary, p.Detail)] = true } before = n.ID } } for _, f := range facts { - k := key(f.Source, f.Summary, f.Detail) + k := key(f.Summary, f.Detail) if seen[k] { existing++ continue diff --git a/agent/tools.go b/agent/tools.go index be0613f..b545bda 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -6,6 +6,7 @@ import ( "fmt" "strconv" "strings" + "time" "github.com/Autumn-27/artex/db" acperm "github.com/Autumn-27/norma/permission" @@ -145,6 +146,7 @@ type ToolSet struct { as *db.AssetStore // asset store (optional; nil = asset tools not available) cs *db.CompanyStore // company store (optional) ts *db.ExplorationStore + factTraffic FactTrafficLookup // proxy capture store for fact classification; nil = activity-only worker string taskID int64 // PG tasks.id; 0 when unknown (tests / orchestrator cross-task reads) // coverageDisabled mirrors tasks.coverage_enabled=false. Stored inverted so the @@ -260,6 +262,11 @@ func NewToolSet(ts *db.ExplorationStore, worker string) *ToolSet { return &ToolSet{ts: ts, worker: worker} } +// SetFactTraffic wires the proxy capture store used to relabel facts whose +// evidence came back from the target (#124 row 1, step 3). Callers pass the +// process traffic store; nil leaves classification activity-only. +func (t *ToolSet) SetFactTraffic(l FactTrafficLookup) { t.factTraffic = l } + // SetTaskID sets the PG task id on this ToolSet so that report_finding can // dual-write to the standalone findings table (which survives task deletion). func (t *ToolSet) SetTaskID(id int64) { t.taskID = id } @@ -1052,6 +1059,15 @@ func compactNode(n *db.Node) map[string]any { if s, ok := p["source"].(string); ok && s != "" { m["source"] = s } + if prov, ok := p["provenance"].(string); ok && prov != "" { + m["provenance"] = prov + if id, ok := p["provenance_activity_id"]; ok && id != nil { + m["provenance_activity_id"] = id + } + if tid, ok := p["provenance_traffic_id"].(string); ok && tid != "" { + m["provenance_traffic_id"] = tid + } + } if n.Inherited { inheritedMap(m, n.SourceTaskID) } @@ -1409,6 +1425,17 @@ func (t *ToolSet) proveGoal() actool.CoreTool { if evidenceNode.Kind == db.KindFact { var fp map[string]any _ = json.Unmarshal(evidenceNode.Payload, &fp) + // A fact the server could not tie to recorded work is not authority + // (#124 row 1): the declared source alone does not make it one. Legacy + // facts written before provenance existed carry no key and keep their + // old behaviour; every new fact carries one. + if prov, ok := fp["provenance"].(string); ok && prov == factProvenanceUnverified { + note, _ := fp["provenance_note"].(string) + if note == "" { + note = "its evidence is not tied to a recorded activity" + } + return actool.Errorf(fmt.Sprintf("prove_goal refused: fact %d is unverified (%s). Goal %d stays open: prove it with a finding or with a fact whose evidence quotes this intent's recorded activity.", ev, note, goal)), nil + } confidence, _ := fp["confidence"].(string) if strings.ToLower(strings.TrimSpace(confidence)) != "observed" { if confidence == "" { @@ -1608,6 +1635,95 @@ const ( var factSources = []string{factSourceTargetResponse, factSourceToolOutput, factSourceThirdPartyIntel, factSourceOperatorInput, factSourceInference} +// Fact provenance (#124, row 1): the source above is declared by the agent, so +// on its own it cannot distinguish an observation from a claim. The server ties +// each fact to a recorded activity of its intent and stores the result beside +// the payload; only a tie (or an explicit operator statement) is authoritative. +const ( + factProvenanceRecorded = "recorded_activity" // evidence quoted from this intent's activity + factProvenanceCaptured = "captured_traffic" // the quoted bytes came back from the target through the proxy + factProvenanceOperator = "operator_input" // told to the agent by the human operator + factProvenanceUnverified = "unverified" // no recorded activity carries the evidence +) + +// factCaptureWindowBefore/After bound the proxy captures considered part of one +// recorded activity. The activity row is written when the tool call returns, so +// the matching response lands just before it; the margins absorb slow calls and +// small clock differences between the two stores. +const ( + factCaptureWindowBefore = 10 * time.Minute + factCaptureWindowAfter = 2 * time.Minute +) + +// FactTrafficLookup is the proxy capture store seen from the fact layer. Kept as +// an interface so the agent does not depend on the traffic package. nil = no +// capture available, and facts keep the activity-only classification. +type FactTrafficLookup interface { + ResponseContaining(lines []string, fromTS, toTS int64) (id string, ok bool, err error) +} + +// factEvidenceMinRunes keeps trivial fragments (a bare tool name, "200 OK") +// from tying a fact to unrelated activity. A real evidence line quotes the +// output; a paraphrase matches nothing, which fails safe (unverified, not +// authoritative). +const factEvidenceMinRunes = 12 + +// factEvidenceMaxLines bounds the lookup cost of one record_fact item. +const factEvidenceMaxLines = 20 + +// factEvidenceLines splits a fact's one-line evidence into the substantive lines +// the server can look for verbatim in the intent's recorded activity. +func factEvidenceLines(evidence string) []string { + out := make([]string, 0, 4) + seen := map[string]bool{} + for _, raw := range strings.Split(evidence, "\n") { + line := strings.TrimSpace(raw) + if len([]rune(line)) < factEvidenceMinRunes || seen[line] { + continue + } + seen[line] = true + out = append(out, line) + if len(out) == factEvidenceMaxLines { + break + } + } + return out +} // factProvenance classifies one fact against the intent's recorded activity. +// Beyond the activity tie it checks whether the quoted bytes were captured +// coming back from the target through the proxy, in which case the target +// authored them and the fact is classified target_response even when the model +// wrote tool_output (#124 row 1, step 3). A database error keeps the fact +// (writes must not fail on the check) but marks it unverified, so the +// conservative outcome is the one that survives. +func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status string, activityID int64, trafficID string, note string) { + if source == factSourceOperatorInput { + return factProvenanceOperator, 0, "", "" + } + if intent <= 0 || t.ts == nil { + return factProvenanceUnverified, 0, "", "no intent was recorded, so no activity could corroborate the evidence" + } + lines := factEvidenceLines(evidence) + if len(lines) == 0 { + return factProvenanceUnverified, 0, "", "evidence is missing or too short to quote a recorded activity; a fact proves a goal only when its evidence is tied to one" + } + id, at, ok, err := t.ts.ActivityContainingEvidence(intent, lines) + if err != nil { + return factProvenanceUnverified, 0, "", "the recorded activity could not be read, so the evidence is unverified" + } + if !ok { + return factProvenanceUnverified, 0, "", "evidence does not quote any line of this intent's recorded activity; quote the output verbatim instead of paraphrasing it" + } + if t.factTraffic != nil && !at.IsZero() { + from, to := at.Add(-factCaptureWindowBefore).Unix(), at.Add(factCaptureWindowAfter).Unix() + // A capture miss or an unreadable capture store is not a write failure: + // the activity tie stands and the fact stays classified as tool output. + if tid, hit, _ := t.factTraffic.ResponseContaining(lines, from, to); hit && tid != "" { + return factProvenanceCaptured, id, tid, "" + } + } + return factProvenanceRecorded, id, "", "" +} + // normalizeFactSource returns the stored source for a record_fact input: empty // means inference, a value outside factSources is an error. func normalizeFactSource(s string) (string, error) { @@ -1638,16 +1754,6 @@ func (t *ToolSet) recordOneFact(it factItem, defaultIntent int64) (int64, error) if err != nil { return 0, err } - payload := map[string]any{"summary": it.Summary, "source": source} - if it.Detail != "" { - payload["detail"] = it.Detail - } - if e := strings.TrimSpace(it.Evidence); e != "" { - payload["evidence"] = e - } - if c := strings.TrimSpace(it.Confidence); c != "" { - payload["confidence"] = c - } intent := pid(it.IntentID) if intent <= 0 { intent = defaultIntent @@ -1658,6 +1764,44 @@ func (t *ToolSet) recordOneFact(it factItem, defaultIntent int64) (int64, error) return 0, fmt.Errorf("intent_id must be an intent of this task (related-task intents are read-only)") } } + // Tie the claim to recorded work before storing it (#124 row 1). A fact the + // server cannot corroborate loses the authority its declared source and + // confidence imply: it is stored as inference/inferred and marked unverified, + // so prove_goal refuses it even if the model labelled it observed. + confidence := strings.TrimSpace(it.Confidence) + prov, provActivity, provTraffic, provNote := t.factProvenance(source, it.Evidence, intent) + if prov == factProvenanceUnverified { + if source == factSourceTargetResponse || source == factSourceToolOutput { + source = factSourceInference + } + if strings.EqualFold(confidence, "observed") { + confidence = "inferred" + } + } + if prov == factProvenanceCaptured { + // The matched bytes came back from the target, whichever tool carried + // them: relabel from the capture rather than trusting the declaration. + source = factSourceTargetResponse + } + payload := map[string]any{"summary": it.Summary, "source": source, "provenance": prov} + if it.Detail != "" { + payload["detail"] = it.Detail + } + if e := strings.TrimSpace(it.Evidence); e != "" { + payload["evidence"] = e + } + if confidence != "" { + payload["confidence"] = confidence + } + if provActivity > 0 { + payload["provenance_activity_id"] = provActivity + } + if provTraffic != "" { + payload["provenance_traffic_id"] = provTraffic + } + if provNote != "" { + payload["provenance_note"] = provNote + } // a fact is its OWN node kind (distinct from a vuln finding). id, err := t.ts.AddNode(db.KindFact, payload, 5, "confirmed", t.worker, anchors) if err != nil { @@ -1691,7 +1835,8 @@ func (t *ToolSet) recordFact() actool.CoreTool { "⚠️Write only conclusions you [actually saw] in tool output — don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n"+ " · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** — details belong in detail; don't paste large output blocks here.\n"+ " · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n"+ - " · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n"+ + " · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n"+ + " · **evidence is checked against this intent's recorded activity**: quote the output verbatim rather than paraphrasing it. A fact whose evidence matches no recorded activity is stored as provenance=unverified, its source is downgraded to inference, an observed confidence becomes inferred, and prove_goal refuses it. If the quoted bytes were also captured coming back from the target through the proxy, the server stores source=target_response (provenance=captured_traffic) regardless of the source you declared, because the target authored them.\n"+ " · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" — state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen."+ recordFactContractNote, recordFactSchema(), diff --git a/agent/worker.go b/agent/worker.go index d677415..f7d8aa8 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -67,6 +67,7 @@ type Worker struct { workDir string proxyAddr string proxyCACert string // recording proxy's CA cert path (for WebFetch HTTPS verify) + factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only) webSearch WebSearchOpts // web_search tool backend selection (off by default) tx *transcript.Store // raw LLM conversation persistence (nil = off) window int // context window in tokens (for compaction) @@ -206,6 +207,10 @@ func (w *Worker) compactionWindow() int { // that MITM proxy. Empty addr disables the hint. func (w *Worker) SetProxy(addr, caCert string) { w.proxyAddr, w.proxyCACert = addr, caCert } +// SetFactTraffic wires the proxy capture store used to classify recorded facts +// (#124 row 1). nil keeps the activity-only classification. +func (w *Worker) SetFactTraffic(l FactTrafficLookup) { w.factTraffic = l } + // SetWebSearch selects the web_search backend for this worker (off by default). func (w *Worker) SetWebSearch(o WebSearchOpts) { w.webSearch = o } @@ -527,6 +532,7 @@ func (w *Worker) ExecuteWithMessage(ctx context.Context, name string, taskID int func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, intent *db.Node, hooks harness.HookRunner, emit func(db.Activity), enr EnrichTrigger, notifyFinding func(int64, string), requestID, message string) (harness.TerminalReason, WriteCounts, error) { tsx := NewToolSet(ts, name) tsx.SetFindingRecorder(w.findingRecorder) + tsx.SetFactTraffic(w.factTraffic) tsx.SetTaskID(taskID) coverageEnabled := coverageOn(as, taskID) tsx.SetCoverageEnabled(coverageEnabled) diff --git a/db/exploration.go b/db/exploration.go index 055ee54..3a30135 100644 --- a/db/exploration.go +++ b/db/exploration.go @@ -1768,6 +1768,33 @@ FROM activity WHERE exploration_id=$1 AND id>$2 ORDER BY id LIMIT $3`, s.expID, return out, cursor, rows.Err() } +// ActivityContainingEvidence returns the newest activity recorded for nodeID +// whose summary or full detail contains one of the given evidence lines (#124 +// row 1). ok is false when no recorded activity carries any of them. The match +// is literal and case-sensitive: evidence has to quote the recorded output, not +// paraphrase it. Callers pass only substantive lines, so a command name alone +// cannot tie a claim to an activity. The activity's timestamp bounds the search +// for a proxy capture of the same bytes. +func (s *ExplorationStore) ActivityContainingEvidence(nodeID int64, lines []string) (id int64, createdAt time.Time, ok bool, err error) { + if nodeID <= 0 || len(lines) == 0 { + return 0, time.Time{}, false, nil + } + for _, line := range lines { + err := s.db.QueryRow(`SELECT id, created_at FROM activity +WHERE exploration_id=$1 AND node_id=$2 + AND (strpos(COALESCE(detail,''), $3) > 0 OR strpos(COALESCE(summary,''), $3) > 0) +ORDER BY id DESC LIMIT 1`, s.expID, nodeID, line).Scan(&id, &createdAt) + if err == sql.ErrNoRows { + continue + } + if err != nil { + return 0, time.Time{}, false, err + } + return id, createdAt, true, nil + } + return 0, time.Time{}, false, nil +} + // ActivityListForTerminalIntent is the inherited, incremental-read boundary. // The intent state check and activity read happen in one statement so a source // intent reopened between API-level checks cannot expose its new in-flight trace. diff --git a/server/task_llm.go b/server/task_llm.go index 6fc7b1a..29871f5 100644 --- a/server/task_llm.go +++ b/server/task_llm.go @@ -807,6 +807,7 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle { wk.SetNoaEnabled(s.m.NoaCompactionEnabled) // experimental: noa context compaction (platform-level switch, read every run) wk.SetRunTimeout(time.Duration(s.agentRunSeconds("worker")) * time.Second) wk.SetProxy(s.m.ProxyAddr(), s.m.ProxyCACert()) + wk.SetFactTraffic(s.m.traffic) // fact provenance: relabel bytes captured from the target (#124 row 1) wk.SetWebSearch(s.webSearchFor("worker")) wk.SetConstraintInject(s.constraintInjectWorker) // operation-constraint injection into the worker (configurable, on by default) pl := agent.NewPlanner(plannerRuntime, "task-router", s.m.dir, tx, plannerRuntime.CompactionWindow(), s.agentMaxTurns("planner")) @@ -818,6 +819,7 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle { pl.SetKillWork(s.engine.KillWork) pl.SetSteerWork(s.engine.SteerWork) pl.SetProxy(s.m.ProxyAddr(), s.m.ProxyCACert()) + pl.SetFactTraffic(s.m.traffic) pl.SetWebSearch(s.webSearchFor("planner")) pl.SetConstraintInject(s.constraintInjectPlanner) // operation-constraint injection into the planner (configurable, on by default) // cold-digest §7: background compaction of cold nodes. This per-task planner set @@ -834,6 +836,7 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle { main.SetMaxTokens(mainRuntime.maxTokens) main.SetNoaEnabled(s.m.NoaCompactionEnabled) // experimental: noa context compaction (platform-level switch, read every run) main.SetProxy(s.m.ProxyAddr(), s.m.ProxyCACert()) + main.SetFactTraffic(s.m.traffic) main.SetWebSearch(s.webSearchFor("mainagent")) main.SetSteerWork(s.engine.SteerWork) // steer_work: real-time course correction on running work by a human bundle := &taskAgentBundle{ diff --git a/traffic/evidence_search_test.go b/traffic/evidence_search_test.go new file mode 100644 index 0000000..37e07fb --- /dev/null +++ b/traffic/evidence_search_test.go @@ -0,0 +1,36 @@ +package traffic + +import ( + "testing" + "time" +) + +// ResponseContaining matches only the response side, inside the time window: +// a line that appears only in a request, or a capture outside the window, must +// not classify a fact as target-authored (#124 row 1, step 3). +func TestResponseContaining(t *testing.T) { + tr, _ := openTraffic(t) + tr.record(newFlow("target.example", "GET", "/login", + []byte("request-only-marker-abc"), + []byte(`welcome, internal only`))) + id := onlyExchangeID(t, tr) + + now := time.Now().Unix() + got, ok, err := tr.ResponseContaining([]string{"internal only"}, now-60, now+60) + if err != nil || !ok || got != id { + t.Fatalf("response match = %q, %v, %v; want %q, true", got, ok, err, id) + } + if _, ok, err := tr.ResponseContaining([]string{"request-only-marker-abc"}, now-60, now+60); err != nil || ok { + t.Fatalf("request-side match: ok=%v err=%v, want false", ok, err) + } + if _, ok, err := tr.ResponseContaining([]string{"internal only"}, now+600, now+900); err != nil || ok { + t.Fatalf("out-of-window match: ok=%v err=%v, want false", ok, err) + } + if _, ok, err := tr.ResponseContaining([]string{"never recorded anywhere"}, now-60, now+60); err != nil || ok { + t.Fatalf("absent match: ok=%v err=%v, want false", ok, err) + } + var nilStore *Traffic + if _, ok, err := nilStore.ResponseContaining([]string{"internal only"}, now-60, now+60); err != nil || ok { + t.Fatalf("nil store: ok=%v err=%v, want false", ok, err) + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index f886877..8eba165 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -1156,6 +1156,51 @@ func (t *Traffic) Search(host string, page, size int) ([]ExchangeMeta, error) { return out, rows.Err() } +// ResponseContaining reports the newest capture recorded in [fromTS,toTS] +// (unix seconds) whose response side contains one of lines. Request-side matches +// are ignored after the index lookup: what classifies a fact is what came back +// from the target. ok is false when no capture matches, when this build has no +// full-text index, or when the store is unavailable; callers keep the +// activity-only classification in that case. +func (t *Traffic) ResponseContaining(lines []string, fromTS, toTS int64) (id string, ok bool, err error) { + if t == nil || len(lines) == 0 { + return "", false, nil + } + for _, line := range lines { + cond, arg, hasFTS := t.ftsFilter(line) + if !hasFTS { + return "", false, nil + } + rows, qerr := t.db.Query(`SELECT id FROM exchanges +WHERE ts>=? AND ts<=? AND `+cond+` +ORDER BY ts DESC LIMIT 8`, fromTS, toTS, arg) + if qerr != nil { + return "", false, qerr + } + ids := make([]string, 0, 8) + for rows.Next() { + var cand string + if serr := rows.Scan(&cand); serr != nil { + rows.Close() + return "", false, serr + } + ids = append(ids, cand) + } + rows.Close() + if err := rows.Err(); err != nil { + return "", false, err + } + for _, cand := range ids { + _, resp, gerr := t.Get(cand) + if gerr != nil || !strings.Contains(resp, line) { + continue + } + return cand, true, nil + } + } + return "", false, nil +} + // ftsFilter builds the SQL condition restricting rows to those whose indexed // text matches term. ok is false when full-text search cannot serve the term — // no FTS index on this build, or fewer than three characters, which the trigram