Skip to content

record_fact: tie evidence to recorded activity and proxy captures - #441

Merged
BaaRai merged 2 commits into
BaaRai:mainfrom
00xcyd:row1-provenance
Nov 21, 2026
Merged

BaaRai merged 2 commits into
BaaRai:mainfrom
00xcyd:row1-provenance

Conversation

@00xcyd

@00xcyd 00xcyd commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Implements the rule posted in #124 for row 1 (memory poisoning): a fact's source is declared by the model, so on its own it cannot decide whether prove_goal accepts the claim.

What the server now does

  1. Tie the evidence to recorded work. record_fact matches each substantive evidence line (>=12 runes, <=20 lines, literal and case-sensitive) against the intent's recorded activities and pins provenance=recorded_activity plus provenance_activity_id on the payload.
  2. Classify from the capture. If the same line was captured coming back from the target through the proxy within the activity window, the fact is stored as source=target_response and provenance=captured_traffic with provenance_traffic_id, regardless of the source the model declared. Request-side matches are ignored.
  3. Refuse the untied claim. No activity match stores provenance=unverified, downgrades target_response/tool_output to inference and observed to inferred, and prove_goal refuses it before the confidence check. operator_input stays exempt; legacy facts without provenance keep their old behaviour.

compactNode surfaces provenance wherever facts are shown. ToolSet takes an optional FactTrafficLookup, 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

  • A target_response fact never proves a goal, as before. Captured target text is now classified that way even when the model calls it tool_output.
  • Tools that reformat proxied bytes (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 arrive unverified; their dedupe key now ignores source so re-ingestion does not rewrite them.
  • The capture window is 10 minutes before to 2 minutes after the activity timestamp, a constant rather than a schema field.

Tests

go test ./agent ./db ./traffic and the server fact tests pass against Postgres 14. New: TestFactEvidenceLines, TestFactProvenanceTiedToRecordedActivity, TestFactProvenancePrefersCapturedTraffic, TestResponseContaining. Updated for the deliberate downgrade: TestRecordFactStoresProvenance, TestFactProvenanceSurfaced, TestRecordFactRefusesTopLevelCopiesBesideFacts. The full server package 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)

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.

@auditbenchaibot auditbenchaibot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open in Audit Bench Ai

🤖 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

⚠️ Checks to review: 1 warning

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

Comment thread db/exploration.go Outdated
Comment on lines +1782 to +1794
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
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 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

@00xcyd 00xcyd Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@00xcyd

00xcyd commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Review follow-up on the Audit Bench findings:

  • High (ActivityContainingEvidence) — fixed in 42ce6ea with a single query and a regression test, replied inline.
  • Complexity in completeTaskLLM, streamTaskLLM, CancelIntent — those functions are unchanged by this PR; the review is reading whole files. I am not refactoring them here, per the PR's scope.
  • Untied facts strictly downgraded — deliberate. The downgrade is the mitigation: a paraphrase is not evidence. A tool that reformats proxied bytes (grep, jq) can therefore lose a tie and be refused, which fails safe and is stated in the PR and the writeup. ingest_scan_output facts arrive unverified for the same reason.

Re-ran go test ./agent ./db ./traffic and go test ./server -run 'Fact|Traffic' on Postgres 14 after the fix; all green.

@auditbenchaibot

Copy link
Copy Markdown

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.
Untied facts downgraded: the description explains this is deliberate and fails safe, so it shouldn't have been listed under merge risk. The risk summary now treats explained trade-offs as the author's decision.
ActivityContainingEvidence: the single unnest query in 42ce6ea fixes it. Thanks for adding the regression test.
Your inline reply came through as the literal text @/tmp/reply1.md, so the file's contents didn't post, in case you wanted it on the thread.

@auditbenchaibot auditbenchaibot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open in Audit Bench Ai

🤖 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

@BaaRai

BaaRai commented Nov 21, 2026

Copy link
Copy Markdown
Owner

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:

  • with capture off, a line the target planted and the model labels tool_output still ties to the activity. The tie proves the bytes were in recorded work, not who wrote them; only the capture makes the classification target_response.
  • a tool output the agent produced itself (an echo, a file it wrote, the result of an earlier record_fact) is also recorded activity. The tie raises the bar, it is not a truth proof.

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.

@BaaRai
BaaRai merged commit 2411943 into BaaRai:main Nov 21, 2026
5 checks passed
@BaaRai

BaaRai commented Nov 21, 2026

Copy link
Copy Markdown
Owner

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.

@00xcyd

00xcyd commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for merging, and for naming the two limits precisely. Both are now stated in the public writeup rather than left implicit:

  • with capture off, the tie is to recorded work, not target authorship: a planted line the model labels tool_output still ties, and only capture relabels it target_response;
  • agent-produced output (an echo, a file it wrote, an earlier record_fact) is also recorded activity, so the tie raises the bar rather than proving authorship.

The doc-comment nit is fixed in #469 (comment moved onto factProvenance, no behavior change). Row 3 and row 4 of #124 are audited as negative results: the goal anchor closes every planner message and the bbot path parses typed fields only with inert free text. Writeups: https://cyberd4ch.github.io/blog/rows-three-and-four-goal-anchor-and-bbot-parser/

BaaRai pushed a commit that referenced this pull request Nov 22, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants