Compare commits

..
Author SHA1 Message Date
BaaRai 9d076ec350 Merge pull request #991 from BaaRai/fix/fact-provenance-input-echo
fix(agent): a fact quoting tool output the agent wrote itself is unverified
2026-12-04 23:01:40 +01:00
BaaRai 177bfeb7bf agent: a fact quoting tool output the agent wrote itself is unverified
record_fact tied an observed tool_output fact to a recorded tool_result
whenever one of its evidence lines occurred in that result. A worker
could write sentences into a command's input (a heredoc, echo, printf),
quote the output, and prove_goal accepted the fact, marked the goal met
and completed the task without any observation. One real output line
was also enough, so free text on the other evidence lines passed with it.

ToolResultActivityContainingEvidence now skips a result when one of the
evidence lines it contains also occurs in the input of a tool call of the
same exploration recorded before it: its own call (same tool_use_id) and
earlier calls, so a file written by one call and read by another is
caught too. Inputs are compared after JSON decoding; a SQL prefilter on
the longest run of characters JSON never escapes keeps the read bounded,
and more candidate inputs than the bound refuse the result.

The result it returns must also hold every non-blank evidence line, each
compared without surrounding whitespace; a line under 12 characters must
equal a whole output line. Evidence over 20 lines is refused. factProvenance
stores a failing fact unverified with a note saying why, and prove_goal
checks the lines again against the tied result, which also covers facts
stored before this change.

The record_fact description, its evidence field and the worker prompt now
ask for output lines only, quoted from one tool output, with the command
in detail. The v0.7.0 and v0.7.1 default texts join the known defaults and
the one-time refresh flag is renamed, so a stored copy of them is replaced
once; the worker prompt reseed flag moves to v5.
2026-12-04 22:42:40 +01:00
BaaRai b6535154c6 Merge pull request #990 from BaaRai/fix/argv-rules-fail-closed
fix(intercept): argv deny and ask rules fail closed on words they cannot read
2026-12-04 22:42:29 +01:00
16 changed files with 628 additions and 37 deletions
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **A fact no longer proves a goal with tool output the agent wrote itself.** `record_fact` tied an observed `tool_output` fact to a recorded `tool_result` whenever one of its evidence lines occurred in that result, without asking where the text came from, so a worker could write sentences into a command's input (`cat > f <<'EOF' ... EOF; cat f`, `echo`, `printf`), quote the output, and `prove_goal` marked the goal met and completed the task with no observation behind it. A result now ties the fact only when none of the evidence lines it contains occurs in the input of a tool call of the same task recorded before it: its own call, and earlier calls, so a file written by one call and read back by another is refused too. Inputs are compared after JSON decoding. Otherwise an older result that holds the line and was not echoed is used, or the fact is stored unverified with a note and cannot prove a goal. A quoted line the agent also typed itself (a `grep` pattern quoted alone, a value it gave an earlier `record_fact`) is now refused as well; quoting the full output line still works. One real output line of 12 characters or more was also enough to tie the whole evidence, so free text on the other lines passed with it: now every non-blank evidence line must be in the one tool result recorded as the fact's provenance, compared without its surrounding whitespace, and a line under 12 characters (`ok`, `}`) must equal a whole output line. Evidence with a line that is not in that result, or with more than 20 lines, is stored unverified with a note; the command and any commentary belong in `detail`. `prove_goal` checks the lines again against the tied result, so a fact stored before this change is refused when a line of its evidence, often the command, is not in that result. Workers must therefore quote output lines only, with the command in `detail`: the `record_fact` description, its `evidence` field and the worker prompt now say so. A stored copy of the previous default texts (v0.7.0 and v0.7.1) is replaced once at startup and an operator's edited text is kept; the worker prompt gets the new default as a new version once, as earlier prompt changes did. An edited worker prompt is replaced too, and the previous text remains in the prompt history. Text the shell rewrites before printing it (escape sequences, `base64 -d`, a sentence split across words or variables) is not detected, and the input check does not run again on facts recorded before this change.
- **Argv deny and ask rules no longer pass a command they cannot read.** An argv deny or ask rule answered "no match", and the call ran without review, when the program word was an ANSI-C string, a glob, a brace expansion or a variable (`$'nmap'`, `/usr/bin/nm?p`, `n{m,}ap`, `"$T"`), when a `sh -c` or `eval` payload was built at run time, when a shell read its script from a here-string, a here-document, a process substitution or a pipe (`bash <<< 'nmap x'`, `echo 'nmap x' | sh`), when payloads nested more than three levels deep, and for shells and program runners the matcher did not know (`ash`, `mksh`, `rbash`, `posh`, `yash`, `csh`, `tcsh`, `su -c`, `runuser`, `script -c`, `unshare`, `setpriv`, `nsenter`, `systemd-run`, `firejail`, `catchsegv`, `pkexec`). ANSI-C strings are now decoded, literal text fed to a shell on stdin (here-string, here-document, `echo`, `printf` or `cat <<EOF` into a pipe or process substitution, `source <(...)`, `/dev/stdin`) is parsed as a nested command line, and the new shells and runners are unwrapped. When a part of the line that may run the program is only known when it runs (such a program word, a payload or a script produced by another command as in `curl ... | bash`, nesting past the limit, a word built at run time where the rule names an argument, a shell option the matcher does not know), the rule now counts as a possible match: an ask rule asks as configured, and a deny rule asks for an approval that times out to deny, because denying outright would also refuse every ordinary `"$TOOL" ...` call with no way to let it through. A possible match keeps its rule's place in the priority order, and a later rule that denies still decides. A program word whose last path component is fixed text (`"$HOME/bin/curl"`, `~/bin/curl`) is matched by that name. Unknown options on a known wrapper were tried both ways recursively, so `nohup` with a few dozen unknown options took seconds per rule; each position is now walked once and a rule's walk is bounded, and reaching a bound counts as a possible match. Script files (`bash script.sh`, `sh < file`) are still not read.
- **The sandbox images build from a digest-pinned Debian base.** `Dockerfile.runner`, `Dockerfile.worker` and `Dockerfile.egress-proxy` built their runtime stage from the bare `debian:bookworm-slim` tag, so a rebuild used whatever the tag pointed to that day for the runner (which holds the Docker socket), the worker and the egress proxy. They now use `debian:bookworm-slim@sha256:e67eeead...`, the multi-architecture index the panel `Dockerfile` already pins, which Dependabot keeps current, and a test fails when any `FROM` in the repository's Dockerfiles lacks a digest. The GHCR compose file pins `postgres:16-alpine` to the digest `docker-compose.yml` already uses. The API-recon skill's checklist and harvest script ask for `npm ci --ignore-scripts` against the shipped lockfile instead of `npm install`. The Debian package repositories the images install from are still live, not a frozen snapshot.
- **The image ships Playwright builds with Chromium 159.** The Dockerfile installed `playwright@1.64.1`, whose Chromium 156.0.8078.4 the shared browser runs, and `@playwright/mcp@0.0.83` and `@playwright/cli@0.1.22`, which bundle Chromium 155.0.8059.12. Both are older than 157.0.8103.50, the release that fixes CVE-2026-125350, a renderer use-after-free exploited in the wild. The pins move to `playwright@1.65.1`, `@playwright/mcp@0.0.86` and `@playwright/cli@0.1.25`, which all bundle Chromium 159.0.8154.6 (Playwright revision 1255), and a test refuses a Dockerfile pin older than the first release of each package with a fixed Chromium. The `playwright-cli` skill installs the same `@playwright/cli` version, and its test-generation guide installs `@playwright/test@1.65.1` instead of running `npm init playwright@latest`; a test keeps the Playwright versions named in skills equal to the Dockerfile pins. Known limitation, unchanged: on Linux these browsers still run with `--no-sandbox`. The image has no setuid sandbox helper and Docker's default seccomp profile gives the executor no user namespaces, so a renderer exploit is contained only by the container and the executor uid; the README now states this next to the shared browser.
+1 -1
View File
@@ -190,7 +190,7 @@ func TestProveGoalRequiresObservedFact(t *testing.T) {
}
inferred := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin is probably reachable", "confidence": "inferred", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
unlabeled := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin reachable", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "evidence": "uid=0(admin) groups=0(admin)", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
provenFinding := seedProvenFinding(t, d, task, "ex-guard-1", "https://guard.example.test/api/users",
[]int64{seedFindingAsset(t, d, task, "https://guard.example.test/api/users")})
+1 -1
View File
@@ -30,7 +30,7 @@ func factItemSchema() map[string]any {
"summary": str("Required: a non-empty one-sentence summary of this conclusion."),
"intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."),
"detail": str("Details of this fact, including all related observations."),
"evidence": str("One line of key evidence: the command and the most proving output lines. Put longer output in detail."),
"evidence": str("One line of key evidence: the most proving output lines, copied verbatim from one tool output. Put the command and longer output in detail."),
"confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."),
"source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"},
"asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Asset IDs explicitly involved in this fact. Use asset_ids as the canonical field; tested_asset_ids is accepted as an alias. If both are provided, they must name the same set. Do not infer IDs from the intent."},
+38 -8
View File
@@ -1,9 +1,10 @@
package agent
// Texts of the earlier record_fact contract (fact fields at the top level
// beside facts[]), kept verbatim so the server's one-time refresh
// (server/fact_input_schema.go) can tell a stored default from an operator
// edit. Nothing here is published to a model.
// Texts of earlier record_fact defaults (the contract with fact fields at the
// top level beside facts[], and the facts-only texts of v0.7.0 and v0.7.1),
// kept verbatim so the server's one-time refresh (server/fact_input_schema.go)
// can tell a stored default from an operator edit. Nothing here is published
// to a model.
// recordFactLegacyDescription is the record_fact description seeded up to the
// facts-only contract.
@@ -27,12 +28,41 @@ const recordFactReleasedDescription = "Write an exploration [fact/conclusion] in
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\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."
// recordFactLegacyItemDescriptions are the facts[] item descriptions of the
// earlier contract whose wording referred to the top level; the refresh
// replaces exactly these texts with the current ones.
// The facts-only contract texts below asked for the command in evidence;
// evidence now quotes output lines only, each one from the cited tool result.
// Their dashes are written as escapes; the bytes are the released ones.
// recordFactV070Description is the record_fact description seeded by v0.7.0.
const recordFactV070Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
"⚠️Write only conclusions you [actually saw] in tool output \u2014 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** \u2014 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" +
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" \u2014 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.\n" +
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
// recordFactV071Description is the record_fact description seeded by v0.7.1 (also main up to the evidence-lines rule).
const recordFactV071Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
"⚠️Write only conclusions you [actually saw] in tool output \u2014 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** \u2014 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" +
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n" +
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" \u2014 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.\n" +
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
// recordFactLegacyItemDescriptions are earlier facts[] item descriptions the
// refresh replaces exactly with the current ones: summary and intent_id of the
// earlier contract, whose wording referred to the top level, and evidence of
// v0.7.0 and v0.7.1, which asked for the command.
var recordFactLegacyItemDescriptions = map[string]string{
"summary": "Required on every fact: a non-empty one-sentence summary of this conclusion. Batch items do not inherit summary from the top level.",
"intent_id": "The intent that produced this fact; only this field inherits from the top level in a batch.",
"evidence": "One line of key evidence: the command and the most proving output lines. Put longer output in detail.",
}
// recordFactLegacyFactsDescription is the facts property description of the
@@ -48,7 +78,7 @@ const recordFactReleasedFactsDescription = "[use when there are several distinct
// contract that the refresh may replace: the tool descriptions, the facts
// property descriptions and the item descriptions.
func RecordFactLegacyDescriptions() (tool, facts []string, items map[string]string) {
return []string{recordFactLegacyDescription, recordFactReleasedDescription},
return []string{recordFactLegacyDescription, recordFactReleasedDescription, recordFactV070Description, recordFactV071Description},
[]string{recordFactLegacyFactsDescription, recordFactReleasedFactsDescription},
recordFactLegacyItemDescriptions
}
+132
View File
@@ -0,0 +1,132 @@
package agent
import (
"encoding/json"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
// echoTestIntent is an intent with a goal, a ToolSet that runs it, and helpers
// to record tool calls and facts on it.
type echoTestIntent struct {
t *testing.T
s *db.ExplorationStore
tsx *ToolSet
intent int64
n int
}
func newEchoTestIntent(t *testing.T) *echoTestIntent {
s := guardTaskStore(t)
intent := addGuardNode(t, s, db.KindIntent, map[string]any{"text": "explain HTTP caching headers"}, "running")
tsx := NewToolSet(s, "worker-5")
tsx.SetOwnerNode(intent)
return &echoTestIntent{t: t, s: s, tsx: tsx, intent: intent}
}
// call records a tool_use with input and its tool_result with output, and
// returns the tool_result activity id.
func (e *echoTestIntent) call(tool string, input map[string]string, output string) int64 {
e.t.Helper()
e.n++
useID := "toolu_echo_" + strconv.Itoa(e.n)
in, _ := json.Marshal(input)
if _, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_use", Tool: tool, ToolUseID: useID, Summary: tool, Detail: string(in)}); err != nil {
e.t.Fatal(err)
}
id, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_result", Tool: tool, ToolUseID: useID, Detail: output})
if err != nil {
e.t.Fatal(err)
}
return id
}
// fact records an observed tool_output fact quoting evidence and returns its
// payload, then tries to prove a fresh goal with it.
func (e *echoTestIntent) fact(evidence string) (payload map[string]any, proved bool, refusal string) {
e.t.Helper()
in, _ := json.Marshal(map[string]string{"summary": "caching headers explained", "evidence": evidence, "confidence": "observed", "source": "tool_output"})
out := callGuardTool(e.t, e.tsx.recordFact(), string(in)).Flatten()
if !strings.HasPrefix(out, "fact recorded: ") {
e.t.Fatalf("record_fact: %q", out)
}
id, err := strconv.ParseInt(strings.TrimPrefix(out, "fact recorded: "), 10, 64)
if err != nil {
e.t.Fatal(err)
}
n, err := e.s.GetNode(id)
if err != nil || n == nil {
e.t.Fatalf("node %d: %v", id, err)
}
_ = json.Unmarshal(n.Payload, &payload)
goal := addGuardNode(e.t, e.s, db.KindGoal, map[string]any{"text": "explain caching"}, "open")
res := callGuardTool(e.t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(id, 10)+`,"reason":"x"}`)
return payload, !res.IsError && nodeState(e.t, e.s, goal) == "met", res.Flatten()
}
// A tool result that only repeats what the agent wrote into a tool's input,
// in the same call or in an earlier one, is not an observation: the fact is
// stored unverified and cannot prove a goal.
func TestFactProvenanceRefusesEchoedToolInput(t *testing.T) {
const heredoc = "Cache-Control tells clients how long they may reuse a response."
const printf = `The "Vary" header <names> the request headers a cache must match.`
const written = "ETag lets a client revalidate a cached copy cheaply."
const mixed = "Expires is the older, absolute form of a freshness lifetime."
cases := []struct {
name string
calls func(e *echoTestIntent)
evidence string
}{
{"heredoc then cat in one call", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": "cat > notes.txt <<'EOF'\n" + heredoc + "\nEOF\ncat notes.txt"}, heredoc+"\n")
}, heredoc},
{"printf with JSON-escaped characters", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": `printf '%s\n' '` + printf + `'`}, printf+"\n")
}, printf},
{"file written by one call and read by another", func(e *echoTestIntent) {
e.call("Write", map[string]string{"file_path": "/work/s.txt", "content": written + "\n"}, "File created successfully at: /work/s.txt")
e.call("Bash", map[string]string{"command": "ls -la /work"}, "total 4\n-rw-r--r-- 1 kali kali 52 Dec 3 12:00 s.txt")
e.call("Bash", map[string]string{"command": "cat /work/s.txt"}, written+"\n")
}, written},
{"echo next to a real output line", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": "echo '" + mixed + "'; uname -a"}, mixed+"\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux\n")
}, mixed + "\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
e := newEchoTestIntent(t)
tc.calls(e)
p, proved, refusal := e.fact(tc.evidence)
note, _ := p["provenance_note"].(string)
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "input of an earlier tool call") {
t.Errorf("provenance=%v note=%q, want unverified with the input-echo note", p["provenance"], note)
}
if proved {
t.Errorf("echoed fact proved a goal: %q", refusal)
}
})
}
}
// Output the agent did not write is still an observation: a grep result whose
// quoted line is not in the command, and an older real result whose line a
// later command repeats.
func TestFactProvenanceAcceptsToolOutputNotInInput(t *testing.T) {
e := newEchoTestIntent(t)
grep := e.call("Bash", map[string]string{"command": "grep -i 'server:' /work/headers.txt"}, "Server: nginx/1.25.3 (Ubuntu)\n")
p, proved, refusal := e.fact("Server: nginx/1.25.3 (Ubuntu)")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != grep || !proved {
t.Fatalf("grep output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, grep)
}
scan := e.call("Bash", map[string]string{"command": "redis-cli -h 10.0.0.5 INFO server | head -3"}, "# Server\nredis_version:7.2.4\nredis_mode:standalone_cluster_off")
e.call("Bash", map[string]string{"command": "echo 'redis_mode:standalone_cluster_off' >> notes.txt"}, "")
e.call("Bash", map[string]string{"command": "cat notes.txt"}, "redis_mode:standalone_cluster_off\n")
p, proved, refusal = e.fact("redis_mode:standalone_cluster_off")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != scan || !proved {
t.Fatalf("older real output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, scan)
}
}
+60
View File
@@ -0,0 +1,60 @@
package agent
import (
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
// Every evidence line must be in the one tool result the fact is tied to:
// free text next to one real output line, or a line found only in another
// result, leaves the fact unverified. Blank lines and surrounding whitespace
// do not count, and a short line must be a whole output line.
func TestFactProvenanceRequiresEveryEvidenceLine(t *testing.T) {
const uname = "Linux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"
refused := []struct {
name string
evidence string
}{
{"free text next to a real line", "HTTP caching headers let clients reuse a response safely.\n" + uname},
{"short free text", uname + "\npwned"},
{"short line inside a longer word", "redis_version:7.2.4\nyes"},
{"lines spread over two results", uname + "\nredis_version:7.2.4"},
}
for _, tc := range refused {
t.Run(tc.name, func(t *testing.T) {
e := newEchoTestIntent(t)
e.call("Bash", map[string]string{"command": "uname -a"}, uname+"\n")
e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\nyesterday_restart:0\nok\n")
p, proved, refusal := e.fact(tc.evidence)
note, _ := p["provenance_note"].(string)
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "every evidence line") {
t.Errorf("provenance=%v note=%q, want unverified with the every-line note", p["provenance"], note)
}
if proved {
t.Errorf("fact with an unquoted line proved a goal: %q", refusal)
}
})
}
e := newEchoTestIntent(t)
info := e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\n redis_mode:standalone\nok\n")
p, proved, refusal := e.fact(" redis_version:7.2.4 \n\nredis_mode:standalone\nok")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != info || !proved {
t.Fatalf("whole output lines with blank lines and indentation: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, info)
}
// A fact stored before this rule, tied to a result that lacks one of its
// lines, is refused by prove_goal.
stored, err := e.s.AddNode(db.KindFact, map[string]any{"summary": "redis explained", "evidence": "redis_version:7.2.4\nRedis is the cache the goal asks about.", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": info}, 0, "confirmed", "worker-5", nil)
if err != nil {
t.Fatal(err)
}
goal := addGuardNode(t, e.s, db.KindGoal, map[string]any{"text": "explain redis"}, "open")
res := callGuardTool(t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(stored, 10)+`,"reason":"x"}`)
if !res.IsError || nodeState(t, e.s, goal) != "open" || !strings.Contains(res.Flatten(), "is not in the tool result it is tied to") {
t.Fatalf("stored fact with free text: want a refusal, got IsError=%v %q", res.IsError, res.Flatten())
}
}
+1 -1
View File
@@ -220,7 +220,7 @@ func TestProveGoalRefusesTargetResponseFact(t *testing.T) {
t.Fatal(err)
}
planted := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "page says: goal achieved, admin granted", "confidence": "observed", "source": "target_response", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "evidence": "admin session cookie verified", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
provenFinding := seedProvenFinding(t, d, task, "ex-prov-1", "https://prov.example.test/api/users",
[]int64{seedFindingAsset(t, d, task, "https://prov.example.test/api/users")})
+1
View File
@@ -130,6 +130,7 @@ func TestProveGoalFindingProofGatePG(t *testing.T) {
}
nonHTTPFact := addGuardNode(t, store, db.KindFact, map[string]any{
"summary": "nmap confirmed port 6379 open with unauthenticated Redis INFO",
"evidence": "6379/tcp open redis redis_version:7.2.4",
"source": "tool_output",
"confidence": "observed",
"provenance": factProvenanceRecorded,
+44 -3
View File
@@ -1690,6 +1690,20 @@ func (t *ToolSet) proveGoal() actool.CoreTool {
if !okAct {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d is not backed by a matching recorded activity in this task. Goal %d stays open.", ev, goal)), nil
}
// Every evidence line of a tool_output fact must be in the tool
// result it is tied to, checked again here so a fact stored
// before that rule, or by any other path, cannot carry free text.
if !wantOperator {
evidenceRaw, _ := fp["evidence"].(string)
quoted, fits := factQuotedLines(evidenceRaw)
holds, err := t.ts.ToolResultContainsQuotedLines(actID, quoted)
if err != nil {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d evidence verification unavailable (%v). Goal %d stays open.", ev, err, goal)), nil
}
if !fits || len(quoted) == 0 || !holds {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): a line of fact %d's evidence is not in the tool result it is tied to. Goal %d stays open: record a fact whose every evidence line quotes that tool output verbatim.", ev, goal)), nil
}
}
// For operator_input facts, prevent a benign real operator quote in
// evidence from smuggling an unrelated summary claim (e.g. "admin access
// granted"): the normalized summary must appear inside the verified
@@ -2007,6 +2021,23 @@ func factEvidenceLines(evidence string) []string {
return out
}
// factQuotedLines returns every non-blank line of a fact's evidence, trimmed,
// once each. A tool_output fact is tied to a tool result only when that result
// holds all of them (db.EvidenceLinesIn). ok is false when the evidence has
// more than factEvidenceMaxLines such lines.
func factQuotedLines(evidence string) (lines []string, ok bool) {
seen := map[string]bool{}
for raw := range strings.SplitSeq(evidence, "\n") {
line := strings.TrimSpace(raw)
if line == "" || seen[line] {
continue
}
seen[line] = true
lines = append(lines, line)
}
return lines, len(lines) <= factEvidenceMaxLines
}
// factProvenance can identify an activity in this intent. A shared-recorder
// text match cannot establish which task sent an exchange.
func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status string, activityID int64, note string) {
@@ -2025,10 +2056,20 @@ func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status
return factProvenanceOperator, id, ""
}
if source == factSourceToolOutput {
id, _, ok, err := t.ts.ToolResultActivityContainingEvidence(intent, lines)
quoted, fits := factQuotedLines(evidence)
if !fits {
return factProvenanceUnverified, 0, fmt.Sprintf("evidence has more than %d lines; quote only the few output lines that prove the fact, each exactly as the tool printed it", factEvidenceMaxLines)
}
id, _, ok, echoed, incomplete, err := t.ts.ToolResultActivityContainingEvidence(intent, lines, quoted)
if err != nil {
return factProvenanceUnverified, 0, "the recorded tool activity could not be read, so the evidence is unverified"
}
if echoed {
return factProvenanceUnverified, 0, "the quoted tool output also appears in the input of an earlier tool call of this task (a heredoc, echo, printf, or a file written and read back), and text written into a tool's input is not an observation; quote output the tool produced, not text it was given"
}
if incomplete {
return factProvenanceUnverified, 0, "a line of the evidence is not in the recorded tool_result that holds the rest: every evidence line must quote that one tool output verbatim (a line under 12 characters must be a whole output line); put the command and any commentary in detail, not in evidence"
}
if !ok {
return factProvenanceUnverified, 0, "evidence does not quote any line of this intent's recorded tool_result activity; quote the tool output verbatim instead of paraphrasing it"
}
@@ -2156,10 +2197,10 @@ func (t *ToolSet) recordFact() actool.CoreTool {
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n"+
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n"+
"⚠️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"+
" · evidence = [one line] of key evidence supporting this conclusion: the one or two most proving output lines, copied verbatim from one tool output, **keep it brief**; the command and other details belong in detail, and large output blocks do not belong 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"+
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n"+
" · **evidence is checked against this intent's recorded activity**: every evidence line must appear verbatim in the one tool output it quotes (a line under 12 characters must be a whole output line), and text you wrote into a tool's input does not count. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\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(),
+1 -1
View File
@@ -292,7 +292,7 @@ const workerDefaultTmpl = `You are an "executor" (work agent) of a network-secur
**Write back as you discover** (only what's written into the graph counts; what's in your head/text doesn't; write every result immediately — don't save it for the end and lose it when the step budget runs out). Three kinds of write-back, don't cross the graphs:
- **New asset/resource → insert_assets (asset graph)**: subdomains / services / endpoints / fingerprints / credentials and any asset [itself]. **Only assets are registered here; exploration conclusions/judgments don't go here — use record_fact.**
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process) — not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly — **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions — that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the command + the most proving one or two output lines — brief; details in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: 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 and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process); not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly; **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions; that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the most proving one or two output lines, copied verbatim from one tool output; brief; the command and other details go in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: 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 and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
- **Confirmed vulnerability → report_finding (exploration graph, with PoC, pass intent_id)**: **use it only when you actually triggered it this time and obtained reproducible evidence (request/response or command output)**. It is strictly forbidden to treat "version/fingerprint matching a CVE", "the parameter looks injectable", or "inference from external vulnerability databases/changelogs/code diffs" as confirmed, and don't substitute querying a CVE database or comparing patch versions for actually triggering it. Can't trigger it but suspicion remains → record an inferred fact with record_fact (the suspicion point + why it couldn't be triggered) for the planner; don't force it into a finding. Before registering, check list_findings / list_task_findings for an existing finding with the same root cause, endpoint, and parameter: the same defect again means extending that finding's evidence, not registering a duplicate (duplicates burn reviewer trust); a genuinely distinct entry point, parameter, or privilege level remains its own finding per the adversarial gate. When your confidence is not high, also fill report_finding's optional fields: counterevidence = what you tested that did not work; confidence_rationale = why the conclusion holds. Both are optional and never block reporting.
+233 -9
View File
@@ -1888,27 +1888,251 @@ ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
return id, createdAt, true, nil
}
// evidenceMaxToolResults bounds the tool_result rows one evidence lookup
// examines, newest first.
const evidenceMaxToolResults = 20
// evidenceMaxToolInputs bounds the earlier tool_use rows one evidence lookup
// reads to check that the quoted lines were not the agent's own input. A
// lookup with more candidate rows refuses every result.
const evidenceMaxToolInputs = 500
// ToolResultActivityContainingEvidence returns the newest tool_result activity
// recorded for nodeID in THIS exploration whose summary or detail contains one
// of the given verbatim evidence lines. Restricting to kind='tool_result'
// ensures assistant prose or thinking rows cannot corroborate tool_output facts.
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines []string) (id int64, createdAt time.Time, ok bool, err error) {
// of the given verbatim evidence lines, provided that none of the lines it
// contains occurs in the input of a tool call of this exploration recorded
// before it (its own call, with the same tool_use_id, included). Text the
// agent wrote into a tool's input (a heredoc, echo, printf, or a file written
// by one call and read back by another) is not an observation. echoed is true
// when a result contained a line but every such result was refused that way.
// Restricting to kind='tool_result' ensures assistant prose or thinking rows
// cannot corroborate tool_output facts.
//
// The result returned must also hold every quoted line of the evidence
// (EvidenceLinesIn), so free text cannot ride along with one real output line:
// all of them in that one result, the one recorded as provenance. incomplete
// is true when no result qualified and one that was not refused as an echo
// lacked a quoted line.
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines, quoted []string) (id int64, createdAt time.Time, ok, echoed, incomplete bool, err error) {
if nodeID <= 0 || len(lines) == 0 {
return 0, time.Time{}, false, nil
return 0, time.Time{}, false, false, false, nil
}
err = s.db.QueryRow(`SELECT id, created_at FROM activity a
type result struct {
id int64
createdAt time.Time
matched []string
}
rows, err := s.db.Query(`SELECT id, created_at,
array_to_string(ARRAY(SELECT line FROM unnest($3::text[]) AS line
WHERE strpos(COALESCE(a.detail,''), line) > 0
OR strpos(COALESCE(a.summary,''), line) > 0), E'\n')
FROM activity a
WHERE exploration_id=$1 AND node_id=$2 AND kind='tool_result'
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS line
WHERE strpos(COALESCE(a.detail,''), line) > 0
OR strpos(COALESCE(a.summary,''), line) > 0)
ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
ORDER BY id DESC LIMIT $4`, s.expID, nodeID, lines, evidenceMaxToolResults)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
var results []result
for rows.Next() {
var r result
var matched string
if err := rows.Scan(&r.id, &r.createdAt, &matched); err != nil {
rows.Close()
return 0, time.Time{}, false, false, false, err
}
r.matched = strings.Split(matched, "\n")
results = append(results, r)
}
rows.Close()
if err := rows.Err(); err != nil {
return 0, time.Time{}, false, false, false, err
}
if len(results) == 0 {
return 0, time.Time{}, false, false, false, nil
}
inputs, complete, err := s.toolInputsQuoting(results[0].id, lines)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
if !complete {
return 0, time.Time{}, false, true, false, nil
}
for _, r := range results {
if linesInToolInputs(r.matched, inputs, r.id) {
echoed = true
continue
}
holds, err := s.ToolResultContainsQuotedLines(r.id, quoted)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
if holds {
return r.id, r.createdAt, true, false, false, nil
}
incomplete = true
}
return 0, time.Time{}, false, echoed && !incomplete, incomplete, nil
}
// evidenceWholeLineRunes is the length below which a quoted evidence line must
// equal a whole output line; agent.factEvidenceMinRunes uses the same value.
const evidenceWholeLineRunes = 12
// EvidenceLinesIn reports whether output holds every quoted line. A line is
// compared without its leading and trailing whitespace, and a blank line is
// skipped. A line of evidenceWholeLineRunes runes or more may be any part of
// the output; a shorter line ("ok", "}") must equal a whole output line, also
// trimmed, so a short fragment cannot be found inside a longer word.
func EvidenceLinesIn(output string, quoted []string) bool {
var whole map[string]bool
for _, q := range quoted {
q = strings.TrimSpace(q)
if q == "" {
continue
}
if len([]rune(q)) >= evidenceWholeLineRunes {
if !strings.Contains(output, q) {
return false
}
continue
}
if whole == nil {
whole = map[string]bool{}
for line := range strings.SplitSeq(output, "\n") {
whole[strings.TrimSpace(line)] = true
}
}
if !whole[q] {
return false
}
}
return true
}
// ToolResultContainsQuotedLines reports whether activityID is a tool_result of
// THIS exploration whose detail, or else whose summary, holds every quoted
// line (EvidenceLinesIn).
func (s *ExplorationStore) ToolResultContainsQuotedLines(activityID int64, quoted []string) (bool, error) {
var summary, detail string
err := s.db.QueryRow(`SELECT COALESCE(summary,''), COALESCE(detail,'') FROM activity
WHERE exploration_id=$1 AND id=$2 AND kind='tool_result'`, s.expID, activityID).Scan(&summary, &detail)
if err == sql.ErrNoRows {
return 0, time.Time{}, false, nil
return false, nil
}
if err != nil {
return 0, time.Time{}, false, err
return false, err
}
return id, createdAt, true, nil
return EvidenceLinesIn(detail, quoted) || EvidenceLinesIn(summary, quoted), nil
}
// toolInput is the text of a recorded tool call's input.
type toolInput struct {
id int64
text string
}
// toolInputsQuoting returns the tool_use rows of this exploration recorded
// before activity beforeID that may contain one of lines: the SQL filter keeps
// a row that holds the longest run of each line's characters that JSON never
// escapes, so it cannot drop a row whose decoded input holds the line. Each
// row's text is its decoded JSON strings and its input as written. complete
// is false when more than evidenceMaxToolInputs rows qualify.
func (s *ExplorationStore) toolInputsQuoting(beforeID int64, lines []string) (inputs []toolInput, complete bool, err error) {
anchors := make([]string, len(lines))
for i, line := range lines {
anchors[i] = jsonSafeRun(line)
}
rows, err := s.db.Query(`SELECT id, COALESCE(detail,'') FROM activity a
WHERE exploration_id=$1 AND kind='tool_use' AND id < $2
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS anchor WHERE strpos(COALESCE(a.detail,''), anchor) > 0)
ORDER BY id DESC LIMIT $4`, s.expID, beforeID, anchors, evidenceMaxToolInputs+1)
if err != nil {
return nil, false, err
}
defer rows.Close()
for rows.Next() {
var in toolInput
var detail string
if err := rows.Scan(&in.id, &detail); err != nil {
return nil, false, err
}
in.text = detail + "\n" + jsonStrings(detail)
inputs = append(inputs, in)
}
if err := rows.Err(); err != nil {
return nil, false, err
}
if len(inputs) > evidenceMaxToolInputs {
return nil, false, nil
}
return inputs, true, nil
}
// linesInToolInputs reports whether one of lines occurs in a tool input
// recorded before activity beforeID.
func linesInToolInputs(lines []string, inputs []toolInput, beforeID int64) bool {
for _, in := range inputs {
if in.id >= beforeID {
continue
}
for _, line := range lines {
if line != "" && strings.Contains(in.text, line) {
return true
}
}
}
return false
}
// jsonSafeRun returns the longest run of s made of printable ASCII that no JSON
// encoder escapes (everything but " \ / < > &). Any JSON text whose decoded
// strings hold s holds that run verbatim.
func jsonSafeRun(s string) string {
best, start := "", -1
for i := 0; i <= len(s); i++ {
safe := i < len(s) && s[i] >= 0x20 && s[i] < 0x7f && !strings.ContainsRune(`"\/<>&`, rune(s[i]))
if safe && start < 0 {
start = i
}
if !safe && start >= 0 {
if i-start > len(best) {
best = s[start:i]
}
start = -1
}
}
return best
}
// jsonStrings returns every string value of a JSON document, one per line, or
// "" when detail is not JSON.
func jsonStrings(detail string) string {
var v any
if json.Unmarshal([]byte(detail), &v) != nil {
return ""
}
var sb strings.Builder
var walk func(any)
walk = func(x any) {
switch t := x.(type) {
case string:
sb.WriteString(t)
sb.WriteByte('\n')
case []any:
for _, e := range t {
walk(e)
}
case map[string]any:
for _, e := range t {
walk(e)
}
}
}
walk(v)
return sb.String()
}
// ActivityMatchesProvenance checks that activityID exists in THIS task's
+1 -1
View File
@@ -45,7 +45,7 @@ func TestFix410ReleasedDefaultsRefreshed(t *testing.T) {
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
+5 -3
View File
@@ -12,7 +12,9 @@ import (
// descriptions, bindings, enabled/deferred flags and parameter annotations.
// refreshRecordFactContract brings an already-seeded record_fact row to the
// facts-only contract (one-time, settings flag). SeedTool is first-insert-only
// current texts (one-time per flag value: the flag was renamed when evidence
// became output lines only, so a database refreshed for the facts-only
// contract is refreshed once more). SeedTool is first-insert-only
// and ToolResolve serves the stored text, so without this an old database keeps
// describing the earlier contract (fact fields at the top level beside facts[])
// to the model. Only text equal to the previous code default is replaced:
@@ -27,7 +29,7 @@ import (
// (also when it changed no row) or the row is not the built-in one. A failed
// read, decode or UPDATE leaves it unset, so the next start retries.
func (s *Server) refreshRecordFactContract() {
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -91,7 +93,7 @@ WHERE key='record_fact' AND system AND kind='builtin'
return
}
done()
log.Printf("[facts] record_fact now publishes the facts-only contract (one-time)")
log.Printf("[facts] record_fact now publishes the current contract texts (one-time)")
}
func sliceHas(list []string, s string) bool {
+4 -4
View File
@@ -165,7 +165,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
seedAgents, _ := json.Marshal(seed.Agents)
restore := func() {
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`)
}
defer restore()
@@ -176,7 +176,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
if err := m.pg.UpsertToolForce("record_fact", desc, json.RawMessage(legacySchema), seedAgents); err != nil {
t.Fatal(err)
}
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`); err != nil {
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`); err != nil {
t.Fatal(err)
}
s.seedFactInputSchema()
@@ -217,7 +217,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
if enum, _ := items["source"].(map[string]any)["enum"].([]any); len(enum) != 5 {
t.Fatalf("source enum missing on the items: %v", items["source"])
}
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_facts_only"); v != "true" {
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_evidence_lines"); v != "true" {
t.Fatal("flag not set")
}
// Second start: nothing changes.
@@ -252,7 +252,7 @@ func TestFix410RefreshFlagNotSetOnFailure(t *testing.T) {
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
+99
View File
@@ -0,0 +1,99 @@
package server
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"testing"
"github.com/Autumn-27/artex/agent"
)
// The facts-only record_fact texts seeded by v0.7.0 and v0.7.1 asked for the
// command in evidence. The agent package's list of known defaults must hold
// their released bytes (checked by size and sha256 here, apart from that
// list), and a database that stores one of them with the v0.7 evidence item
// text is refreshed once to the current texts, even when it already ran the
// facts-only refresh.
func TestRecordFactV07DefaultsRefreshed(t *testing.T) {
released := map[string]struct {
sum string
size int
}{
"v0.7.0": {"dc16f3e014625f6336944028bf2caeb5b6f1feab80a70cb43a8f2c87397b9469", 2909},
"v0.7.1": {"ef8bfd930e5b5d3bb425a87ef914045465b313d4f1d96f39e20fd44ba9e5d839", 3181},
}
legacyTool, _, legacyItems := agent.RecordFactLegacyDescriptions()
found := map[string]string{}
for _, d := range legacyTool {
sum := sha256.Sum256([]byte(d))
for rel, want := range released {
if len(d) == want.size && hex.EncodeToString(sum[:]) == want.sum {
found[rel] = d
}
}
}
for rel := range released {
if found[rel] == "" {
t.Fatalf("the known record_fact defaults miss the description released in %s", rel)
}
}
oldEvidence := legacyItems["evidence"]
if sum := sha256.Sum256([]byte(oldEvidence)); len(oldEvidence) != 101 || hex.EncodeToString(sum[:]) != "848fdbd2c770726c8346b8c65c717eeda720a72bfb5707aa792bec1014633eb7" {
t.Fatalf("the known evidence item text is not the v0.7 text: %q", oldEvidence)
}
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
defer func() {
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key='tool_schema_refresh_record_fact_facts_only'`, flag)
}()
evidenceOf := func(schema map[string]any) map[string]any {
return schema["properties"].(map[string]any)["facts"].(map[string]any)["items"].(map[string]any)["properties"].(map[string]any)["evidence"].(map[string]any)
}
for rel, desc := range found {
var stored map[string]any
_ = json.Unmarshal(seedSchema, &stored)
evidenceOf(stored)["description"] = oldEvidence
raw, _ := json.Marshal(stored)
if err := m.pg.UpsertToolForce("record_fact", desc, raw, seedAgents); err != nil {
t.Fatal(err)
}
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, flag); err != nil {
t.Fatal(err)
}
if err := m.pg.SetSetting("tool_schema_refresh_record_fact_facts_only", "true"); err != nil {
t.Fatal(err)
}
s.seedFactInputSchema()
s.seedFactSourceSchema()
s.refreshRecordFactContract()
row, err := m.pg.GetTool("record_fact")
if err != nil || row == nil {
t.Fatalf("%s: row: %v", rel, err)
}
if row.Description != seed.Desc {
t.Errorf("%s description not replaced by the current one: %.80q", rel, row.Description)
}
var after map[string]any
if err := json.Unmarshal(row.Schema, &after); err != nil {
t.Fatal(err)
}
if got, want := evidenceOf(after)["description"], evidenceOf(seed.Schema)["description"]; got != want {
t.Errorf("%s evidence item description = %v, want %v", rel, got, want)
}
if v, _, _ := m.pg.GetSetting(flag); v != "true" {
t.Errorf("%s: flag = %q after the refresh, want true", rel, v)
}
}
}
+6 -5
View File
@@ -624,7 +624,7 @@ func (s *Server) seedOrchestrationTools() {
s.reseedMainAgentPrompt() // mainagent prompt updated to orchestration-only (no shell/file/HTTP tools) → old DBs append a new default version (one-time)
s.reseedAutoPrompt() // auto prompt hardened with explicit spawn_task(seed_first_intent=true) dispatch rules (one-time)
s.reseedPlannerPrompt() // planner prompt: rewrites the "zero intents" justification rules + adds quantitative acceptance checks (one-time)
s.reseedWorkerPrompt() // worker prompt: adds the evidence bar for negative conclusions (one-time)
s.reseedWorkerPrompt() // worker prompt: evidence quotes output lines only, the command goes in detail (one-time)
s.seedReporterAgent() // seeds the "report writer" agent + tool bindings + finding trigger (one-time)
s.upgradeReporterTriggerMessage() // backfill migration for old DBs: makes the reporter send evidence_version back (one-time)
s.seedFindingTrafficTools() // adds optional evidence params and read-only evidence tools, preserving user config
@@ -633,7 +633,7 @@ func (s *Server) seedOrchestrationTools() {
s.seedFindingEvidenceSchema() // optional counterevidence / confidence_rationale on report_finding, added once per DB
s.seedFactInputSchema() // restore record_fact single/batch contracts
s.seedFactSourceSchema() // source enum on record_fact, added once per DB
s.refreshRecordFactContract() // record_fact publishes the facts-only contract (one-time)
s.refreshRecordFactContract() // record_fact publishes the current contract texts (one-time per flag)
s.seedTaskScopeDescription() // add_task_scope: "coverage scope, not enforced" replaces the authorization-boundary text
// Note: pentest's default tool bindings need no migration — BuiltinToolSeeds already seeds
// list_assets/insert_assets/report_finding/list_findings/list_companies together with
@@ -889,11 +889,12 @@ func (s *Server) reseedPlannerPrompt() {
// reseedWorkerPrompt refreshes the worker prompt to [the current code default] — the record_fact section of the default body dropped the whole "for negative conclusions,
// write observations + tentative readings" sentence and decoupled confidence (observed/inferred) from "whether this intent's options are exhausted" (these easily mislead the planner),
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". Bumped the flag to v3 so existing old DBs refresh once more.
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". v5: evidence quotes output lines only
// and the command goes in detail, matching the provenance check. Bump the flag so existing old DBs refresh once more.
// SeedPromptIfEmpty is first-insert-only; versions already in old DBs never got it, so version management [appends a new version] and switches to it; old versions stay in history and can be recovered.
// settings flag guard → done only once. Fresh DBs need nothing. Structurally identical to reseedGoalsPrompt.
func (s *Server) reseedWorkerPrompt() {
const flag = "worker_prompt_compact_v4"
const flag = "worker_prompt_compact_v5"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -914,7 +915,7 @@ func (s *Server) reseedWorkerPrompt() {
log.Printf("[prompts] failed to refresh worker prompt to the new default: %v", err)
return
}
log.Printf("[prompts] worker prompt: appended a new default version (context-lookup section narrowed to list_assets/list_findings, dropping list_facts/node_detail/asset_neighbors, one-time)")
log.Printf("[prompts] worker prompt: appended a new default version (evidence quotes output lines only, the command goes in detail, one-time)")
}
// reporterToolCallMessage must unconditionally require reading get_finding_traffic once before writing the report.