Repository navigation
record_fact: tie evidence to recorded activity and proxy captures - #441
Conversation
record_fact trusted a model-written source, so target text labelled tool_output could prove a goal. The server now matches the fact's evidence against the intent's recorded activity and pins the activity id. If the same bytes were captured coming back from the target through the proxy, the fact is stored as target_response with the traffic id, whatever the model declared, and prove_goal refuses it (BaaRai#124 row 1). An untied claim downgrades to inference/inferred and is refused instead of silently trusted.
6de9755 to
c92c784
Compare
auditbenchaibot
left a comment
There was a problem hiding this comment.
🤖 Automated review by Audit Bench Ai, not a personal review. It was posted through the GitHub account connected to Audit Bench Ai. Install the Audit Bench Ai GitHub App to have reviews posted by a separate bot account.
Actionable comments posted: 1
Merge risk: 🟡 Medium · up to c92c784
ActivityContainingEvidence returns the first matching line's newest activity instead of the global newest across all lines, potentially selecting the wrong activity timestamp. Untied facts are also strictly downgraded, which could cause false negatives.
Merge readiness: 🟡 Ready to merge, with notes
Pre-merge checks: ✅ 9 · ⚠️ 1
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Blocking issues | 1 high-severity issue worth fixing first. 📄 db/exploration.go:1782 |
Address the high-severity inline comments, or reply explaining why not. |
✅ Passed checks: 9 passed
| Check name | Status | Explanation |
|---|---|---|
| Merge conflicts | ✅ | Merges cleanly into main. |
| CI checks | ✅ | All 5 passed. |
| Secrets | ✅ | No keys, passwords or tokens in the changed code. |
| Tests | ✅ | Tests were changed alongside the code. |
| PR size | ✅ | 490 lines changed. |
| Title check | ✅ | The title clearly states what the PR implements. |
| Description check | ✅ | The description clearly explains the changes, deliberate consequences, and test coverage. |
| Linked issues check | ✅ | The code directly implements the memory poisoning mitigation rules outlined in issue #124. |
| Out of scope changes check | ✅ | All changes are directly related to implementing fact provenance and tying evidence to activities or traffic. |
📝 Walkthrough
This pull request ties fact provenance to recorded activities and HTTP proxy traffic captures to prevent memory poisoning. Fact evidence is verified against recorded work, automatically classifying captured target data and downgrading untied claims to unverified inferences. It also updates the agent toolsets and scan ingest tools to support traffic lookup and preserve provenance data.
| File | Changes |
|---|---|
agent/fact_input_test.go |
Updates fact payload assertions to expect downgraded confidence and unverified provenance. |
agent/fact_provenance_test.go |
Adds tests covering evidence line filtering, activity-tied provenance, and proxy traffic matching. |
agent/mainagent.go |
Wires fact traffic lookup configuration into the main agent and its toolset. |
agent/planner.go |
Adds fact traffic lookup wiring to the planner agent. |
agent/scan_ingest_tool.go |
Excludes fact source from deduplication keys during scan ingestion to prevent rewrite loops. |
agent/worker.go |
Wires fact traffic lookup configuration into worker toolsets. |
db/exploration.go |
Adds ActivityContainingEvidence to query the activity record containing matching evidence lines. |
server/task_llm.go |
Injects the traffic store into worker, planner, and main agent bundles. |
traffic/evidence_search_test.go |
Adds unit tests verifying target response matching within defined time bounds. |
ℹ️ Review info
- Commit:
c92c784 - Verdict:
⚠️ Needs work - Findings: 1 high, 3 low
- Review: local checks plus AI review of the changed lines
- Scope: Reviewed 9/9 selected files (of 9 total): 9 reviewed by AI, 0 from cache, 0 passed local checks with nothing risky enough to send to AI. Found 4 finding(s), No secrets found.
🤖 Prompt to fix review comments
Verify each finding against the current code and only fix it if it still applies.
In `@server/task_llm.go` around lines 355 - 431: Very large number of branches in completeTaskLLM(). completeTaskLLM() (lines 355-431) has 29 paths through it. The branches are not deeply nested, so this is only worth changing if they handle unrelated jobs or the function keeps growing. Suggested fix: If the branches map inputs to outputs, a lookup table can replace them. If they do unrelated jobs, separate those jobs. Otherwise no change is needed.
In `@server/task_llm.go` around lines 433 - 591: Very large number of branches in streamTaskLLM(). streamTaskLLM() (lines 433-591) has 52 paths through it. The branches are not deeply nested, so this is only worth changing if they handle unrelated jobs or the function keeps growing. Suggested fix: If the branches map inputs to outputs, a lookup table can replace them. If they do unrelated jobs, separate those jobs. Otherwise no change is needed.
In `@db/exploration.go` around lines 529 - 699: Very large number of branches in CancelIntent(). CancelIntent() (lines 529-699) has 48 paths through it. The branches are not deeply nested, so this is only worth changing if they handle unrelated jobs or the function keeps growing. Suggested fix: If the branches map inputs to outputs, a lookup table can replace them. If they do unrelated jobs, separate those jobs. Otherwise no change is needed.
In `@db/exploration.go` around lines 1782 - 1794: Returns the newest activity for the first matching line rather than the overall newest activity across all lines. The docstring states that ActivityContainingEvidence returns 'the newest activity recorded for nodeID whose summary or full detail contains one of the given evidence lines'. However, the loop executes a query per line and immediately returns upon finding the first line with a match (lines 1786-1793). If line 0 matches an older activity (e.g., ID 10) and line 1 matches a newer activity (e.g., ID 50), the function will return the older activity (ID 10) simply because line 0 was evaluated first. Suggested fix: Either query all lines in a single query matching any of the candidate strings and ordering by id DESC LIMIT 1, or evaluate all lines to find the maximum activity ID across all matches.
💬 Reply to any inline comment and Audit Bench Ai will recheck that code and answer in the thread. Mention @auditbench in the conversation to ask about the whole PR.
🛠️ Open the full report and fix with AI
Thanks for using Audit Bench Ai! Free pull request reviews for open source: paste any public PR at auditbenchai.com/scan.
Reviewed by Audit Bench Ai · Build fast. Check what ships. · Review any public PR free
| 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 | ||
| } |
There was a problem hiding this comment.
🤖 Audit Bench Ai (automated) | 🧠 Logic | 🟠 High
Returns the newest activity for the first matching line rather than the overall newest activity across all lines
The docstring states that ActivityContainingEvidence returns 'the newest activity recorded for nodeID whose summary or full detail contains one of the given evidence lines'. However, the loop executes a query per line and immediately returns upon finding the first line with a match (lines 1786-1793). If line 0 matches an older activity (e.g., ID 10) and line 1 matches a newer activity (e.g., ID 50), the function will return the older activity (ID 10) simply because line 0 was evaluated first.
Why it happens: The function returns early on the first evidence line that matches an activity instead of finding the latest activity across all provided evidence lines.
When it breaks: Given lines = ["older text", "newer text"], where activity #10 contains "older text" and activity #20 contains "newer text". The function processes "older text" first, finds activity #10, and returns it immediately instead of returning activity #20.
Tests: A text search of the repository's test files found no test mentioning: ActivityContainingEvidence.
Suggested fix: Either query all lines in a single query matching any of the candidate strings and ordering by id DESC LIMIT 1, or evaluate all lines to find the maximum activity ID across all matches.
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 {
if line == "" {
continue
}
var candID int64
var candCreated time.Time
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(&candID, &candCreated)
if err == sql.ErrNoRows {
continue
}
if err != nil {
return 0, time.Time{}, false, err
}
if !ok || candID > id {
id = candID
createdAt = candCreated
ok = true
}
}
return id, createdAt, ok, nil
}95% confidence · 💬 Reply here and Audit Bench Ai will recheck the code · 👀 to acknowledge · 👍/👎 teaches it what your team wants
There was a problem hiding this comment.
Fixed in 42ce6ea: the loop is gone and all lines now go through one query (unnest($3::text[]), ORDER BY id DESC LIMIT 1), so the newest matching activity wins regardless of which line matched. TestActivityContainingEvidenceNewestAcrossLines appends the newer match second and asserts the newer id comes back, plus a no-match case.
Good catch. The later activities are the ones whose capture window matters, so the old order could have pinned an activity that made the capture lookup miss.
ActivityContainingEvidence queried one line at a time and returned on the first match, so an older activity matching line 0 beat a newer one matching line 1. A single query over unnest() orders by id and keeps the global newest, and a regression test covers the reversed-order case. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <[email protected]>
|
Review follow-up on the Audit Bench findings:
Re-ran |
|
Thanks @cyberd4ch, this is useful feedback. You're right on both points. Complexity in completeTaskLLM, streamTaskLLM, CancelIntent: those were false positives. The check was reading every function in each changed file, not just the ones this PR touched. That's fixed: complexity is now only reported for functions the diff changes. |
auditbenchaibot
left a comment
There was a problem hiding this comment.
🤖 Automated review by Audit Bench Ai, not a personal review. It was posted through the GitHub account connected to Audit Bench Ai. Install the Audit Bench Ai GitHub App to have reviews posted by a separate bot account.
Findings: 2, listed in the fix prompt below (they couldn't be placed as inline comments).
Merge risk: 🟢 Low · up to 42ce6ea
The change adds stricter validation by downgrading unverified facts. Risk is low as downgrades are deliberate and backward-compatible with legacy facts lacking provenance.
Merge readiness: 🟡 Ready to merge, with notes
Pre-merge checks: ✅ 10
✅ Passed checks: 10 passed
| Check name | Status | Explanation |
|---|---|---|
| Merge conflicts | ✅ | Merges cleanly into main. |
| CI checks | ✅ | All 5 passed. |
| Secrets | ✅ | No keys, passwords or tokens in the changed code. |
| Blocking issues | ✅ | No critical or high-severity issues in the changed lines. |
| Tests | ✅ | Tests were changed alongside the code. |
| PR size | ✅ | 513 lines changed. |
| Title check | ✅ | The title clearly describes tying evidence to recorded activity and proxy captures. |
| Description check | ✅ | The description provides comprehensive details on functionality, design decisions, and testing. |
| Linked issues check | ✅ | Addresses issue #124 regarding row 1 memory poisoning and evidence provenance. |
| Out of scope changes check | ✅ | All changes directly relate to fact provenance tracking, verification, and traffic lookup wiring. |
📝 Walkthrough
This pull request enforces provenance tracking for recorded facts to mitigate memory poisoning. Fact evidence is matched against recorded activities and proxy traffic captures to verify authenticity and classify origin. Untied claims are downgraded to unverified inferences and rejected by prove_goal.
| File | Changes |
|---|---|
agent/fact_input_test.go |
Updates assertions to account for fact downgrade when evidence lacks recorded activity. |
agent/fact_provenance_test.go |
Adds and updates tests covering evidence line extraction, activity tying, and traffic capture provenance. |
agent/mainagent.go |
Adds FactTrafficLookup wiring to MainAgent and passes it to its toolsets. |
agent/planner.go |
Wires FactTrafficLookup into the Planner toolset. |
agent/scan_ingest_tool.go |
Excludes source from deduplication keys to prevent rewriting unverified re-ingested facts. |
agent/worker.go |
Wires FactTrafficLookup into the Worker toolset. |
db/exploration.go |
Implements ActivityContainingEvidence to query the latest matching activity for substantive evidence lines. |
server/task_llm.go |
Passes the traffic store lookup to worker, planner, and main agent instances. |
traffic/evidence_search_test.go |
Adds tests for searching traffic captures by evidence lines. |
ℹ️ Review info
- Commit:
42ce6ea - Verdict: ✅ Pass
- Findings: 2 low
- Review: local checks plus AI review of the changed lines
- Scope: Reviewed 9/9 selected files (of 9 total): 5 reviewed by AI, 4 from cache, 0 passed local checks with nothing risky enough to send to AI. Found 2 finding(s), No secrets found.
🤖 Prompt to fix review comments
Verify each finding against the current code and only fix it if it still applies.
In `@server/task_llm.go` around lines 355 - 431: Very large number of branches in completeTaskLLM(). completeTaskLLM() (lines 355-431) has 29 paths through it. The branches are not deeply nested, so this is only worth changing if they handle unrelated jobs or the function keeps growing. Suggested fix: If the branches map inputs to outputs, a lookup table can replace them. If they do unrelated jobs, separate those jobs. Otherwise no change is needed.
In `@server/task_llm.go` around lines 433 - 591: Very large number of branches in streamTaskLLM(). streamTaskLLM() (lines 433-591) has 52 paths through it. The branches are not deeply nested, so this is only worth changing if they handle unrelated jobs or the function keeps growing. Suggested fix: If the branches map inputs to outputs, a lookup table can replace them. If they do unrelated jobs, separate those jobs. Otherwise no change is needed.
🛠️ Open the full report and fix with AI
Thanks for using Audit Bench Ai! Free pull request reviews for open source: paste any public PR at auditbenchai.com/scan.
Reviewed by Audit Bench Ai · Build fast. Check what ships. · Review any public PR free
|
Merging. The design holds: the tie is server-side, a paraphrase fails safe, captured bytes relabel to target_response, and the refusal tells the agent how to recover. Two limits are worth writing down:
No code change needed for those, but the public description should not claim more. One nit: the factProvenance doc comment sits on the closing brace of factEvidenceLines. |
|
Thanks @cyberd4ch, merged as 2411943. The provenance tie, the target_response relabel and the prove_goal refusal all hold in the tests on main with PostgreSQL. The two limits in my review are the honest scope: with capture off the tie is to recorded work, not to target authorship. |
|
Thanks for merging, and for naming the two limits precisely. Both are now stated in the public writeup rather than left implicit:
The doc-comment nit is fixed in #469 (comment moved onto |
The comment sat on the closing brace of factEvidenceLines, so Go attached it to no declaration and godoc showed it nowhere. Noted in the review of #441. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <[email protected]>
Implements the rule posted in #124 for row 1 (memory poisoning): a fact's
sourceis declared by the model, so on its own it cannot decide whetherprove_goalaccepts the claim.What the server now does
record_factmatches each substantive evidence line (>=12 runes, <=20 lines, literal and case-sensitive) against the intent's recorded activities and pinsprovenance=recorded_activityplusprovenance_activity_idon the payload.source=target_responseandprovenance=captured_trafficwithprovenance_traffic_id, regardless of the source the model declared. Request-side matches are ignored.provenance=unverified, downgradestarget_response/tool_outputtoinferenceandobservedtoinferred, andprove_goalrefuses it before the confidence check.operator_inputstays exempt; legacy facts withoutprovenancekeep their old behaviour.compactNodesurfaces provenance wherever facts are shown.ToolSettakes an optionalFactTrafficLookup, wired from the server's traffic store into the worker, planner and main-agent tool sets; nil or unreachable capture leaves the activity-only classification.Deliberate consequences
target_responsefact never proves a goal, as before. Captured target text is now classified that way even when the model calls ittool_output.grep,jq) fail the tie and downgrade. This is a false negative in the safe direction.ingest_scan_output/ bbot facts have no matching activity, so they arriveunverified; their dedupe key now ignoressourceso re-ingestion does not rewrite them.Tests
go test ./agent ./db ./trafficand the server fact tests pass against Postgres 14. New:TestFactEvidenceLines,TestFactProvenanceTiedToRecordedActivity,TestFactProvenancePrefersCapturedTraffic,TestResponseContaining. Updated for the deliberate downgrade:TestRecordFactStoresProvenance,TestFactProvenanceSurfaced,TestRecordFactRefusesTopLevelCopiesBesideFacts. The fullserverpackage has one failure on this macOS host (listen udp4 127.0.0.2: bind: can't assign requested address), unrelated to this change.Discussion: #124 (comment)