Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

Merge origin/main into codex/btw-side-question

ji ruof62f1cc1a4a0
diff --cc agent/capture.go
index 27e9681,feb8f1c..4850285
--- a/agent/capture.go
+++ b/agent/capture.go
@@@ -7,7 -7,7 +7,8 @@@ import
"unicode/utf8"
"github.com/Autumn-27/artex/db"
+ "github.com/Autumn-27/artex/intercept"
+ "github.com/Autumn-27/artex/sidequestion"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
diff --cc agent/capture_approval_test.go
index 0000000,ac2d447..04a71e1
mode 000000,100644..100644
--- a/agent/capture_approval_test.go
+++ b/agent/capture_approval_test.go
@@@ -1,0 -1,131 +1,140 @@@
+ package agent
+
+ import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/Autumn-27/artex/db"
+ "github.com/Autumn-27/artex/guard"
+ "github.com/Autumn-27/artex/intercept"
+ "github.com/Autumn-27/norma/agentcore"
+ "github.com/Autumn-27/norma/llm"
+ "github.com/Autumn-27/norma/permission"
+ "github.com/Autumn-27/norma/tool"
+ )
+
+ // Exercise the actual SDK event -> hook -> execution -> result path. No real
+ // model or command is used; the probe tool only returns a fixed string.
+ func TestCaptureApprovalLifecycle(t *testing.T) {
+ dsn, _, err := db.DSN()
+ if err != nil {
+ t.Skip("no test database configured")
+ }
+ d, err := db.Open(dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = d.Close() })
+ ic := intercept.New(d)
+ priorTools, err := ic.GetEnabledTools()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priorConfig := ic.GetJudgeConfig()
+ t.Cleanup(func() { _ = ic.SetEnabledTools(priorTools); _ = ic.SetJudgeConfig(priorConfig) })
+ if err := ic.SetEnabledTools([]string{"ApprovalAuditProbe"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := ic.SetJudgeConfig(intercept.JudgeConfig{Enabled: true, AskTimeoutSeconds: 1, AskTimeoutAction: "allow"}); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, tc := range []struct {
+ name, action, status, execution string
+ manual, approve, toolError bool
+ }{
+ {"model_fallback", "invalid", "allowed", "succeeded", false, false, false},
+ {"model_allow", "allow", "allowed", "succeeded", false, false, false},
+ {"model_deny", "deny", "denied", "not_executed", false, false, false},
+ {"human_allow_tool_error", "ask", "allowed", "failed", true, true, true},
+ {"human_deny", "ask", "denied", "not_executed", true, false, false},
+ {"timeout_allow", "ask", "timeout", "succeeded", false, false, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ic.SetReviewer(func(context.Context, int64, string, string, string) (intercept.Decision, error) {
+ return intercept.Decision{Action: tc.action, Message: "probe review", ProfileID: 7}, nil
+ })
+ g := guard.NewWithInterceptor(ic)
+ taskID := "approval-lifecycle-" + tc.name
+ t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, taskID) })
+ ctx := intercept.WithTaskContext(t.Context(), taskID, "test-agent", func(a db.Activity) {
+ if a.Kind != "intercept_request" || !tc.manual {
+ return
+ }
+ var detail struct {
+ ID int64 `json:"pending_id"`
+ }
+ if err := json.Unmarshal([]byte(a.Detail), &detail); err != nil {
+ t.Error(err)
+ return
+ }
+ if err := ic.Decide(detail.ID, tc.approve); err != nil {
+ t.Error(err)
+ }
+ })
+ turn, executions := 0, 0
+ provider := captureUsageProvider{stream: func(_ context.Context, yield func(llm.StreamEvent, error) bool) {
+ turn++
+ events := []llm.StreamEvent{{Type: llm.SETextDelta, Text: "done"}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}}
+ if turn == 1 {
+ events = []llm.StreamEvent{
+ {Type: llm.SEToolUseStart, ToolID: "probe-call", ToolName: "ApprovalAuditProbe"},
+ {Type: llm.SEToolInputJSON, Text: `{}`}, {Type: llm.SEMessageDelta, StopReason: "tool_use"},
+ }
+ }
+ for _, event := range events {
+ if !yield(event, nil) {
+ return
+ }
+ }
+ }}
+ probe := tool.Build(tool.Spec{Name: "ApprovalAuditProbe", Schema: map[string]any{"type": "object"},
+ Run: func(context.Context, json.RawMessage, *tool.ToolContext) (tool.Result, error) {
+ executions++
+ if tc.toolError {
+ return tool.Errorf("probe failed"), nil
+ }
+ return tool.Text("probe succeeded"), nil
+ },
+ })
+ _, _, err := captureRun(ctx, agentcore.Options{Provider: provider, Tools: []tool.CoreTool{probe}, Hooks: g.Hooks(),
+ PermissionMode: permission.ModeBypass, WorkingDir: t.TempDir(), MaxTurns: 2}, "record this review", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rows, err := d.ListTaskIntercepts(taskID)
+ if err != nil || len(rows) != 1 {
+ t.Fatalf("rows=%d err=%v", len(rows), err)
+ }
+ detail, err := d.GetInterceptDetail(rows[0].ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := detail.Audit
+ initialAction := tc.action
+ if tc.action == "invalid" {
+ initialAction = "allow"
+ }
- if detail.Status != tc.status || detail.DecisionSource != "model" || a == nil || a.ExecutionStatus != tc.execution || a.ToolUseID != "probe-call" || a.UserMessage != "record this review" || a.InitialAction != initialAction || a.ModelFallback != (tc.action == "invalid") || a.ProfileID != 7 {
++ wantUserMessage := "record this review"
++ if initialAction == "allow" {
++ // Routine automatic allows keep decision/execution metadata but
++ // intentionally omit the bulky replay context from the audit row.
++ wantUserMessage = ""
++ }
++ if detail.Status != tc.status || detail.DecisionSource != "model" || a == nil || a.ExecutionStatus != tc.execution || a.ToolUseID != "probe-call" || a.UserMessage != wantUserMessage || a.InitialAction != initialAction || a.ModelFallback != (tc.action == "invalid") || a.ProfileID != 7 {
+ t.Fatalf("unexpected review: row=%+v audit=%+v", detail.InterceptApprovalRow, a)
+ }
++ if initialAction == "allow" && (len(a.Context) != 0 || a.UserTruncated || a.ContextTruncated) {
++ t.Fatalf("routine allow retained replay context: %+v", a)
++ }
+ wantCalls := 1
+ if tc.execution == "not_executed" {
+ wantCalls = 0
+ }
+ if executions != wantCalls {
+ t.Fatalf("tool ran %d times, wanted %d", executions, wantCalls)
+ }
+ })
+ }
+ }
diff --cc server/finding_traffic_test.go
index 0000000,0f82a53..a626c2a
mode 000000,100644..100644
--- a/server/finding_traffic_test.go
+++ b/server/finding_traffic_test.go
@@@ -1,0 -1,473 +1,476 @@@
+ package server
+
+ import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Autumn-27/artex/agent"
+ "github.com/Autumn-27/artex/db"
+ "github.com/Autumn-27/artex/traffic"
+ )
+
+ func trafficEvidenceServer(t *testing.T) (*Server, *db.RecordedFinding, func(string, string, string) *httptest.ResponseRecorder) {
+ t.Helper()
+ m, err := NewManager(t.TempDir(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { m.Close() })
+ m.traffic, err = traffic.Open(filepath.Join(m.dir, "traffic"), ":0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ task, err := m.CreateTask("traffic evidence API", "local evidence", nil, 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tid, _ := strconv.ParseInt(task.ID, 10, 64)
+ t.Cleanup(func() { m.pg.Exec(`DELETE FROM task_archives WHERE task_id=$1`, tid); m.pg.DeleteTask(tid) })
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
+ s.archiveWG.Wait()
++ // The archive test below replaces the cancelled service context. Wait for
++ // the side-question snapshot writer too before reusing this fixture.
++ <-s.side.done
+ token, err := signJWT(s.jwtKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request := func(method, path, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest(method, path, strings.NewReader(body))
+ r.Header.Set("Authorization", "Bearer "+token)
+ r.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, r)
+ return w
+ }
+ input := db.RecordFindingInput{TaskID: tid, ExplorationID: task.ExpID, Worker: "test", VulnClass: "TEST", Summary: "bound evidence", Name: "Evidence API", Severity: "low"}
+ f, err := s.evidenceStore().Record(context.Background(), input, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, f, request
+ }
+
+ func seedServerEvidenceFlow(t *testing.T, s *Server, id string, body []byte) {
+ t.Helper()
+ _, err := s.m.traffic.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) VALUES(?,1,'evidence.local','POST','/','http://evidence.local/',200,'application/octet-stream',0,?,'')`, id, len(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = s.m.traffic.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head,req_body,resp_body) VALUES(?,'POST / HTTP/1.1','HTTP/1.1 200 OK',?,?)`, id, []byte{}, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ func TestFindingTrafficToolUpgradePreservesCustomization(t *testing.T) {
+ s, _, _ := trafficEvidenceServer(t)
+ pg := s.m.pg
+ worker, err := pg.GetAgentByKey("worker")
+ if err != nil || worker == nil {
+ t.Fatal("missing worker", err)
+ }
+ oldPrompt, _ := pg.CurrentPrompt(worker.ID)
+ t.Cleanup(func() { pg.SavePrompt(worker.ID, oldPrompt, "restore test fixture", "test") })
+ if _, err := pg.SavePrompt(worker.ID, "USER CUSTOM PROMPT", "test", "test"); err != nil {
+ t.Fatal(err)
+ }
+ custom := json.RawMessage(`{"type":"object","properties":{"evidence":{"type":"string","description":"user evidence instructions"}},"required":["evidence"]}`)
+ for _, key := range []string{"report_finding", "update_finding_report", "get_finding_traffic"} {
+ old, err := pg.GetTool(key)
+ if err != nil || old == nil {
+ t.Fatal("missing tool", key, err)
+ }
+ t.Cleanup(func() {
+ bindings, _ := json.Marshal(old.Agents)
+ pg.UpdateTool(old.Key, old.Description, old.Schema, bindings, old.Enabled)
+ })
+ if err := pg.UpdateTool(key, "user description", custom, json.RawMessage(`["worker"]`), false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := pg.SetSetting("finding_traffic_tools_v1", "false"); err != nil {
+ t.Fatal(err)
+ }
+ s.seedFindingTrafficTools()
+ for key, property := range map[string]string{"report_finding": "traffic_refs", "update_finding_report": "evidence_version"} {
+ tool, err := pg.GetTool(key)
+ if err != nil || tool == nil {
+ t.Fatal(err)
+ }
+ var schema struct {
+ Properties map[string]json.RawMessage `json:"properties"`
+ Required []string `json:"required"`
+ }
+ if err := json.Unmarshal(tool.Schema, &schema); err != nil {
+ t.Fatal(err)
+ }
+ if tool.Enabled || tool.Description != "user description" || len(tool.Agents) != 1 || tool.Agents[0] != "worker" || len(schema.Required) != 1 || schema.Required[0] != "evidence" || len(schema.Properties[property]) == 0 || !strings.Contains(string(schema.Properties["evidence"]), "user evidence instructions") {
+ t.Fatalf("custom configuration overwritten: %+v", tool)
+ }
+ }
+ reader, _ := pg.GetTool("get_finding_traffic")
+ if reader.Enabled || !contains(reader.Agents, "reporter") {
+ t.Fatal("reader should be bound without enabling it")
+ }
+ if err := pg.RemoveAgentFromTool("reporter", "get_finding_traffic"); err != nil {
+ t.Fatal(err)
+ }
+ s.seedFindingTrafficTools()
+ reader, _ = pg.GetTool("get_finding_traffic")
+ if contains(reader.Agents, "reporter") {
+ t.Fatal("restart overwrote user's unbinding")
+ }
+ if got, _ := pg.CurrentPrompt(worker.ID); got != "USER CUSTOM PROMPT" {
+ t.Fatal("custom prompt replaced")
+ }
+ }
+
+ func TestFindingTrafficAPIAndExport(t *testing.T) {
+ s, f, req := trafficEvidenceServer(t)
+ body := bytes.Repeat([]byte{0, 255, 65, 66}, 5000)
+ for _, id := range []string{"a", "b", "c"} {
+ seedServerEvidenceFlow(t, s, id, body)
+ }
+ base := fmt.Sprintf("/api/exploration/findings/%d/traffic", f.FindingID)
+ w := req("POST", base, `{"traffic_refs":[{"traffic_id":"a","role":"baseline"},{"traffic_id":"b","role":"proof","note":"proof note"},{"traffic_id":"c"}]}`)
+ if w.Code != 200 {
+ t.Fatalf("bind: %d %s", w.Code, w.Body)
+ }
+ var list db.FindingTraffic
+ if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
+ t.Fatal(err)
+ }
+ if len(list.Bindings) != 3 || list.Bindings[0].Snapshot.ReqHead != "" {
+ t.Fatal("not a bounded summary")
+ }
+ first, second, third := list.Bindings[0].ID, list.Bindings[1].ID, list.Bindings[2].ID
+ if w = req("PATCH", fmt.Sprintf("%s/%d", base, first), `{"version":0,"note":"stale"}`); w.Code != 409 {
+ t.Fatal(w.Code, w.Body)
+ }
+ if w = req("PUT", base+"/order", fmt.Sprintf(`{"version":1,"binding_ids":["%d","%d","%d"]}`, third, first, second)); w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ if w = req("PUT", base+"/order", fmt.Sprintf(`{"version":2,"binding_ids":["%d"]}`, first)); w.Code != 409 {
+ t.Fatal(w.Code, w.Body)
+ }
+ if w = req("GET", fmt.Sprintf("%s/%d", base, first), ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"binary":true`) {
+ t.Fatal(w.Code, w.Body)
+ }
+ if w = req("GET", fmt.Sprintf("%s/%d/body?side=response&offset=20001", base, first), ""); w.Code != 422 {
+ t.Fatal(w.Code, w.Body)
+ }
+ if _, err := s.m.traffic.DeleteHost("evidence.local"); err != nil {
+ t.Fatal(err)
+ }
+ if w = req("GET", fmt.Sprintf("%s/%d/body?side=response&download=1", base, first), ""); w.Code != 200 || !bytes.Equal(w.Body.Bytes(), body) {
+ t.Fatal("download after original removal failed")
+ }
+ // IDs belong to the requested finding; cross-finding detail cannot be read.
+ finding, err := s.m.pg.GetFinding(f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ task, err := s.m.pg.GetTask(*finding.TaskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := s.evidenceStore().Record(t.Context(), db.RecordFindingInput{TaskID: task.ID, ExplorationID: task.ExplorationID, Summary: "other", Severity: "low"}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if w = req("GET", fmt.Sprintf("/api/exploration/findings/%d/traffic/%d", other.FindingID, first), ""); w.Code != 404 {
+ t.Fatal(w.Code, w.Body)
+ }
+ exportURL := fmt.Sprintf("/api/exploration/findings/export?format=md-zip&scope=selected&ids=%d", f.FindingID)
+ w = req("GET", exportURL, "")
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ archive, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ binaries := 0
+ linked := false
+ for _, entry := range archive.File {
+ r, err := entry.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := io.ReadAll(r)
+ r.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.HasSuffix(entry.Name, "/response.bin") {
+ binaries++
+ if !bytes.Equal(raw, body) {
+ t.Fatal("export changed binary")
+ }
+ }
+ if strings.HasSuffix(entry.Name, ".md") && bytes.Contains(raw, []byte(fmt.Sprintf("evidence/%d/%d/", f.FindingID, third))) {
+ linked = true
+ }
+ }
+ if binaries != 3 || !linked {
+ t.Fatalf("missing attachments/links: %d %v", binaries, linked)
+ }
+ // Reports can use snapshots with capture stopped and original rows gone.
+ result, err := s.toolGetFindingTraffic().Call(context.Background(), json.RawMessage(fmt.Sprintf(`{"finding_id":"%d"}`, f.FindingID)), nil)
+ if err != nil || !strings.Contains(result.Flatten(), "proof note") {
+ t.Fatal(result, err)
+ }
+ // Corrupt body must fail before an attachment response is sent.
+ snap := list.Bindings[0].Snapshot
+ path := filepath.Join(s.m.dir, "evidence", "blobs", snap.RespHash[:2], snap.RespHash+".bin")
+ if err = os.WriteFile(path, []byte("corrupt"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if w = req("GET", exportURL, ""); w.Code < 400 || strings.Contains(w.Header().Get("Content-Type"), "zip") {
+ t.Fatal("corrupt export returned an attachment", w.Code)
+ }
+ }
+
+ func TestFindingTrafficArchiveV3RoundTripAndRetry(t *testing.T) {
+ s, f, _ := trafficEvidenceServer(t)
+ ctx := context.Background()
+ s.ctx = ctx
+ body := []byte("evidence without original traffic\x00\xff")
+ seedServerEvidenceFlow(t, s, "original", body)
+ list, err := s.evidenceStore().Bind(ctx, f.FindingID, []db.TrafficRef{{TrafficID: "original", Role: "proof", Note: "keep note"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ finding, err := s.m.pg.GetFinding(f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tid := *finding.TaskID
+ sharedTask, err := s.m.CreateTask("shared evidence", "fixture", nil, 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sid, _ := strconv.ParseInt(sharedTask.ID, 10, 64)
+ defer s.m.pg.DeleteTask(sid)
+ shared, err := s.evidenceStore().Record(ctx, db.RecordFindingInput{TaskID: sid, ExplorationID: sharedTask.ExpID, Summary: "shared", Severity: "low"}, []db.TrafficRef{{TrafficID: "original"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.m.traffic.DeleteHost("evidence.local"); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.m.SetTaskPaused(strconv.FormatInt(tid, 10), true); err != nil {
+ t.Fatal(err)
+ }
+ job, err := s.m.pg.QueueTaskArchive(tid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.m.pg.EditFindingTraffic(ctx, f.FindingID, list.Bindings[0].ID, 1, nil, nil, true, nil); err == nil {
+ t.Fatal("write allowed after archive queued")
+ }
+ if err = s.runOneTaskArchiveJob(); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := s.m.pg.GetFinding(f.FindingID); got != nil {
+ t.Fatal("archive retained hot finding")
+ }
+ if err = s.evidenceStore().Collect(ctx, time.Now().Add(48*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.evidenceStore().WithBinding(ctx, shared.FindingID, shared.Traffic.Bindings[0].ID, func(b db.FindingTrafficBinding) error {
+ r, _, err := s.evidenceStore().OpenBody(b.Snapshot, "response")
+ if r != nil {
+ r.Close()
+ }
+ return err
+ }); err != nil {
+ t.Fatal("shared body deleted", err)
+ }
+ if _, err = s.m.pg.QueueTaskArchiveRestore(job.ID); err != nil {
+ t.Fatal(err)
+ }
+ // Force a database error after validated body installation; then retry normally.
+ if _, err = s.m.pg.Exec(`CREATE FUNCTION fail_evidence_restore_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'restore fixture failure'; END $$`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.m.pg.Exec(`CREATE TRIGGER fail_evidence_restore_test BEFORE INSERT ON finding_traffic_bindings FOR EACH ROW EXECUTE FUNCTION fail_evidence_restore_test()`); err != nil {
+ t.Fatal(err)
+ }
+ defer s.m.pg.Exec(`DROP FUNCTION IF EXISTS fail_evidence_restore_test() CASCADE`)
+ if err = s.runOneTaskArchiveJob(); err == nil {
+ t.Fatal("expected restore failure")
+ }
+ if got, _ := s.m.pg.GetFinding(f.FindingID); got != nil {
+ t.Fatal("partial restore")
+ }
+ if _, err = s.m.pg.Exec(`DROP FUNCTION fail_evidence_restore_test() CASCADE`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.m.pg.QueueTaskArchiveRestore(job.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.runOneTaskArchiveJob(); err != nil {
+ t.Fatal(err)
+ }
+ restored, err := s.m.pg.GetFindingTraffic(ctx, f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := restored.Bindings[0]
+ if restored.Version != list.Version || b.ID != list.Bindings[0].ID || b.Note != "keep note" || b.Role != "proof" || b.Position != 0 {
+ t.Fatalf("restored: %+v", restored)
+ }
+ if err = s.evidenceStore().WithBinding(ctx, f.FindingID, b.ID, func(b db.FindingTrafficBinding) error {
+ r, _, err := s.evidenceStore().OpenBody(b.Snapshot, "response")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ got, err := io.ReadAll(r)
+ if !bytes.Equal(got, body) {
+ t.Fatal("restore changed body")
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ // The read tool enforces task visibility too.
+ result, err := s.toolGetFindingTraffic().Call(agent.WithRunInfo(ctx, agent.RunInfo{TaskID: sid}), json.RawMessage(fmt.Sprintf(`{"finding_id":"%d"}`, f.FindingID)), nil)
+ if err != nil || !strings.Contains(result.Flatten(), "不可读取") {
+ t.Fatal(result, err)
+ }
+ }
+
+ func TestFindingTrafficFailedReportDoesNotTrigger(t *testing.T) {
+ s, f, _ := trafficEvidenceServer(t)
+ finding, err := s.m.pg.GetFinding(f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ task, err := s.m.pg.GetTask(*finding.TaskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var last int64
+ if err = s.m.pg.QueryRow(`SELECT COALESCE(max(id),0) FROM activity`).Scan(&last); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.m.pg.SetSchedState(schedKeyLastToolCall, strconv.FormatInt(last, 10)); err != nil {
+ t.Fatal(err)
+ }
+ id, err := s.m.pg.Exploration(task.ExplorationID).AppendActivity(db.Activity{Kind: "tool_result", Tool: "report_finding", ToolUseID: "failure-fixture", IsError: true, Detail: "body missing"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A nil server makes any attempted trigger fail this test immediately.
+ scheduler := &Scheduler{pg: s.m.pg}
+ scheduler.fireToolCalls([]*db.AgentTrigger{{OnToolCall: true, ToolNames: []string{"report_finding"}, AgentKey: "reporter"}})
+ if got := scheduler.mustState(schedKeyLastToolCall); got != strconv.FormatInt(id, 10) {
+ t.Fatal("failed finding must still advance watermark", got)
+ }
+ }
+
+ func TestFindingTrafficUTF8SegmentsAndInheritedWrites(t *testing.T) {
+ s, f, req := trafficEvidenceServer(t)
+ ctx := context.Background()
+ text := strings.Repeat("中文证据🙂", 2000)
+ seedServerEvidenceFlow(t, s, "unicode", []byte(text))
+ list, err := s.evidenceStore().Bind(ctx, f.FindingID, []db.TrafficRef{{TrafficID: "unicode"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var joined strings.Builder
+ offset := int64(0)
+ for {
+ var preview evidencePreview
+ err = s.evidenceStore().WithBinding(ctx, f.FindingID, list.Bindings[0].ID, func(b db.FindingTrafficBinding) error {
+ var e error
+ preview, e = readEvidencePreview(s.evidenceStore(), b.Snapshot, "response", offset, 8192)
+ return e
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if preview.Binary {
+ t.Fatal("valid UTF-8 classified binary")
+ }
+ joined.WriteString(preview.Content)
+ if !preview.Truncated {
+ break
+ }
+ if preview.NextOffset <= offset {
+ t.Fatal("preview made no progress")
+ }
+ offset = preview.NextOffset
+ }
+ if joined.String() != text {
+ t.Fatal("UTF-8 character split damaged preview")
+ }
+ finding, err := s.m.pg.GetFinding(f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ child, err := s.m.CreateTaskWithOptions("inherited evidence API", "fixture", db.TaskCreateOptions{SourceTaskIDs: []int64{*finding.TaskID}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ cid, _ := strconv.ParseInt(child.ID, 10, 64)
+ defer s.m.pg.DeleteTask(cid)
+ base := fmt.Sprintf("/api/exploration/findings/%d/traffic", f.FindingID)
+ suffix := "?context_task=" + child.ID
+ if w := req("GET", base+suffix, ""); w.Code != 200 {
+ t.Fatal(w.Code, w.Body)
+ }
+ for _, method := range []string{"POST", "PATCH", "PUT", "DELETE"} {
+ path := base
+ if method == "PATCH" || method == "DELETE" {
+ path += fmt.Sprintf("/%d", list.Bindings[0].ID)
+ }
+ if method == "PUT" {
+ path += "/order"
+ }
+ w := req(method, path+suffix, `{"version":1,"traffic_refs":[{"traffic_id":"unicode"}]}`)
+ if w.Code != 403 {
+ t.Fatal(method, w.Code, w.Body)
+ }
+ }
+ if _, err = s.m.traffic.DeleteHost("evidence.local"); err != nil {
+ t.Fatal(err)
+ }
+ result, err := s.toolUpdateFindingReport().Call(ctx, json.RawMessage(fmt.Sprintf(`{"finding_id":%d,"evidence_version":1,"report":"## 证据报告\n\n证据 #%d:已验证完整请求响应"}`, f.NodeID, list.Bindings[0].ID)), nil)
+ if err != nil || result.IsError {
+ t.Fatal(result, err)
+ }
+ updated, err := s.m.pg.GetFinding(f.FindingID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if updated.ReportEvidenceVersion != 1 || updated.EvidenceVersion != 1 {
+ t.Fatal("report did not record the read evidence version")
+ }
+ for _, format := range []string{"md-single", "json", "csv"} {
+ w := req("GET", fmt.Sprintf("/api/exploration/findings/export?scope=selected&ids=%d&format=%s", f.FindingID, format), "")
+ if w.Code != 200 {
+ t.Fatal(format, w.Code, w.Body)
+ }
+ if !strings.Contains(w.Body.String(), fmt.Sprint(list.Bindings[0].ID)) {
+ t.Fatal("export omitted evidence ID", format)
+ }
+ }
+ }
diff --cc server/finding_workflow_test.go
index 0000000,8d2b2ad..df26e29
mode 000000,100644..100644
--- a/server/finding_workflow_test.go
+++ b/server/finding_workflow_test.go
@@@ -1,0 -1,312 +1,325 @@@
+ package server
+
+ import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/Autumn-27/artex/agent"
+ "github.com/Autumn-27/artex/db"
+ actool "github.com/Autumn-27/norma/tool"
+ )
+
+ func workflowCall(t *testing.T, ctx context.Context, tool actool.CoreTool, input any, wantError bool) string {
+ t.Helper()
+ raw, err := json.Marshal(input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r, err := tool.Call(ctx, raw, nil)
+ if err != nil || r.IsError != wantError {
+ t.Fatalf("%s: error=%v result=%s", tool.Name(), err, r.Flatten())
+ }
+ return r.Flatten()
+ }
+
+ func workflowTool(t *testing.T, tools []actool.CoreTool, name string) actool.CoreTool {
+ t.Helper()
+ for _, tool := range tools {
+ if tool.Name() == name {
+ return tool
+ }
+ }
+ t.Fatalf("missing tool: %s", name)
+ return nil
+ }
+
+ func TestFindingWorkflowAutoHintToPlannerAndSetting(t *testing.T) {
+ s, initial, request := trafficEvidenceServer(t)
+ pg := s.m.pg
+ ctx := context.Background()
+ if _, err := pg.Exec(`DELETE FROM settings WHERE key=$1`, settingAgentTrafficBinding); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { pg.SetBool(settingAgentTrafficBinding, false) })
+ if s.settingsPayload()[settingAgentTrafficBinding] != false {
+ t.Fatal("missing setting must default off")
+ }
+ seedServerEvidenceFlow(t, s, "handoff-proof", []byte("verified local proof"))
+ seedServerEvidenceFlow(t, s, "handoff-baseline", []byte("local baseline"))
+ seedServerEvidenceFlow(t, s, "handoff-verification", []byte{0, 1, 255})
+ // Manual binding is independent of the Agent switch.
+ if r := request("POST", fmt.Sprintf("/api/exploration/findings/%d/traffic", initial.FindingID), `{"traffic_refs":[{"traffic_id":"handoff-proof"}]}`); r.Code != 200 {
+ t.Fatal(r.Code, r.Body)
+ }
+ bind := s.toolBindFindingTraffic()
+ input := map[string]any{"finding_id": initial.FindingID, "traffic_refs": []db.TrafficRef{{TrafficID: "handoff-baseline"}}}
+ workflowCall(t, ctx, bind, input, true)
+ if r := request("PUT", "/api/settings", `{"agent_traffic_binding":true}`); r.Code != 200 {
+ t.Fatal(r.Code, r.Body)
+ }
+ if !pg.GetBool(settingAgentTrafficBinding, false) {
+ t.Fatal("switch was not persisted")
+ }
+ f, _ := pg.GetFinding(initial.FindingID)
+ task := s.m.ResolveTask(fmt.Sprint(*f.TaskID))
+ refs := []db.TrafficRef{{TrafficID: "handoff-baseline", Role: "baseline", Note: "normal response"}, {TrafficID: "handoff-proof", Role: "proof", Note: "proves the finding"}, {TrafficID: "handoff-verification", Role: "verification", Note: "binary verification"}}
+ // Real cross-task Auto hint handler -> persisted graph -> Planner tool.
+ hintResult := workflowCall(t, ctx, s.toolAddHint(), map[string]any{"task_id": task.ID, "hints": []any{map[string]any{"text": "Report the confirmed local finding with its verified evidence", "traffic_refs": refs}}}, false)
+ var hints struct {
+ IDs []int64 `json:"ids"`
+ }
+ if err := json.Unmarshal([]byte(hintResult), &hints); err != nil || len(hints.IDs) != 1 || hints.IDs[0] == 0 {
+ t.Fatal(hintResult, err)
+ }
+ graph := workflowCall(t, ctx, s.toolGetTaskGraph(), map[string]any{"task_id": task.ID}, false)
+ for _, ref := range refs {
+ if !strings.Contains(graph, ref.TrafficID) {
+ t.Fatal("handoff lost reference", ref.TrafficID)
+ }
+ }
+ for range 6 {
+ if _, err := task.Store.AddNode(db.KindFact, map[string]any{"summary": "ID separation"}, 0, "confirmed", "test", nil); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ts := agent.NewToolSet(task.Store, "planner")
+ ts.SetTaskID(*f.TaskID)
+ ts.SetFindingRecorder(s.evidenceStore())
+ notices := 0
+ ts.SetNotifyFinding(func(int64, string) { notices++ })
+ tools, def, cleanup := agent.AugmentTools(ctx, "planner", ts.PlannerTools())
+ defer cleanup()
+ if !strings.Contains(def.FindingGuidance, "evidence_hint_id") || !strings.Contains(def.FindingGuidance, "取消 Worker") {
+ t.Fatal("Planner missed runtime guidance")
+ }
+ report := workflowTool(t, tools, "report_finding")
+ result := workflowCall(t, ctx, report, map[string]any{"vulnclass": "TEST", "severity": "low", "summary": "Planner handoff fixture", "evidence_hint_id": hints.IDs[0]}, false)
+ var recorded db.RecordedFinding
+ if err := json.Unmarshal([]byte(strings.SplitN(result, "\n", 2)[1]), &recorded); err != nil {
+ t.Fatal(err)
+ }
+ if recorded.FindingID == recorded.NodeID || len(recorded.Traffic.Bindings) != 3 || notices != 1 {
+ t.Fatal("bad finding/traffic result", result)
+ }
+ for i, b := range recorded.Traffic.Bindings {
+ if b.Snapshot.SourceTrafficID != refs[i].TrafficID || b.Role != refs[i].Role || b.Note != refs[i].Note {
+ t.Fatalf("handoff mismatch: %+v", b)
+ }
+ }
+ list := workflowCall(t, ctx, s.toolListTaskFindings(), map[string]any{"task_id": task.ID}, false)
+ var nodes []struct {
+ ID int64 `json:"id"`
+ FindingID int64 `json:"finding_id"`
+ FindingNodeID int64 `json:"finding_node_id"`
+ Count int `json:"traffic_count"`
+ }
+ if err := json.Unmarshal([]byte(list), &nodes); err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, n := range nodes {
+ if n.ID == recorded.NodeID {
+ found = n.FindingID == recorded.FindingID && n.FindingNodeID == recorded.NodeID && n.Count == 3
+ }
+ }
+ if !found {
+ t.Fatal("canonical IDs/count missing", list)
+ }
+ workflowCall(t, ctx, s.toolGetFindingTraffic(), map[string]any{"finding_id": recorded.FindingID}, false)
+ wrong := workflowCall(t, ctx, s.toolGetFindingTraffic(), map[string]any{"finding_id": int64(900000000000000000)}, true)
+ if !strings.Contains(wrong, "独立漏洞记录 ID") {
+ t.Fatal("ambiguous ID error", wrong)
+ }
+ input["finding_id"] = recorded.FindingID
+ // Duplicate append preserves metadata and version.
+ workflowCall(t, ctx, bind, input, false)
+ after, err := pg.GetFindingTraffic(ctx, recorded.FindingID)
+ if err != nil || len(after.Bindings) != 3 || after.Version != recorded.Traffic.Version || after.Bindings[0].Note != refs[0].Note {
+ t.Fatal("duplicate changed evidence", after, err)
+ }
+ // A malformed handoff must not create a partial finding or notify Planner.
+ badHint := workflowCall(t, ctx, s.toolAddHint(), map[string]any{"task_id": task.ID, "text": "missing packet", "traffic_refs": []db.TrafficRef{{TrafficID: "missing"}}}, false)
+ var badID int64
+ fmt.Sscanf(badHint, "hint added: %d", &badID)
+ workflowCall(t, ctx, report, map[string]any{"vulnclass": "TEST", "severity": "low", "summary": "must fail", "evidence_hint_id": badID}, true)
+ if notices != 1 {
+ t.Fatal("failed handoff notified before commit")
+ }
+ child, err := s.m.CreateTaskWithOptions("inherited handoff", "fixture", db.TaskCreateOptions{SourceTaskIDs: []int64{*f.TaskID}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ childID, _ := strconv.ParseInt(child.ID, 10, 64)
+ childRow, _ := pg.GetTask(childID)
+ t.Cleanup(func() { pg.DeleteTask(childRow.ID) })
+ childCtx := agent.WithRunInfo(ctx, agent.RunInfo{TaskID: childRow.ID})
+ workflowCall(t, childCtx, bind, input, true)
+ workflowCall(t, childCtx, s.toolGetFindingTraffic(), map[string]any{"finding_id": recorded.FindingID}, false)
+ // Existing, already assembled tools must honor a later switch-off.
+ if r := request("PUT", "/api/settings", `{"agent_traffic_binding":false}`); r.Code != 200 {
+ t.Fatal(r.Code, r.Body)
+ }
+ workflowCall(t, ctx, bind, input, true)
- workflowCall(t, ctx, report, map[string]any{"vulnclass": "TEST", "severity": "low", "summary": "off", "evidence_hint_id": hints.IDs[0]}, true)
++ // Turning binding off must still save a confirmed finding from an already
++ // assembled tool, even if the model sends the old optional evidence fields.
++ offResult := workflowCall(t, ctx, report, map[string]any{"vulnclass": "TEST", "severity": "low", "summary": "off", "evidence_hint_id": hints.IDs[0]}, false)
++ var offRecord struct {
++ db.RecordedFinding
++ EvidenceStatus string `json:"evidence_status"`
++ EvidenceNote string `json:"evidence_note"`
++ }
++ if err := json.Unmarshal([]byte(strings.SplitN(offResult, "\n", 2)[1]), &offRecord); err != nil {
++ t.Fatal(err)
++ }
++ if offRecord.FindingID <= 0 || len(offRecord.Traffic.Bindings) != 0 || offRecord.EvidenceStatus != "not_bound" || !strings.Contains(offRecord.EvidenceNote, "已关闭") {
++ t.Fatal("disabled binding discarded finding or bound evidence", offResult)
++ }
+ workflowCall(t, ctx, report, map[string]any{"vulnclass": "TCP", "severity": "low", "summary": "no packet needed"}, false)
- if notices != 2 {
++ if notices != 3 {
+ t.Fatal("optional no-packet report failed")
+ }
+ workflowCall(t, ctx, s.toolGetFindingTraffic(), map[string]any{"finding_id": recorded.FindingID}, false)
+ tools, def, closeTools := agent.AugmentTools(ctx, "planner", ts.PlannerTools())
+ defer closeTools()
+ if def.FindingGuidance != "" {
+ t.Fatal("disabled feature still injects guidance")
+ }
+ for _, tool := range tools {
+ if tool.Name() == "bind_finding_traffic" {
+ t.Fatal("disabled binding tool exposed")
+ }
+ }
+ }
+
+ func TestFindingWorkflowMigrationPreservesUserConfiguration(t *testing.T) {
+ s, _, _ := trafficEvidenceServer(t)
+ pg := s.m.pg
+ for _, key := range []string{"report_finding", "add_hint", "add_task_hint", "traffic_search", "traffic_get", "traffic_blob", "bind_finding_traffic", "get_finding_traffic"} {
+ old, err := pg.GetTool(key)
+ if err != nil || old == nil {
+ t.Fatal("missing tool", key, err)
+ }
+ t.Cleanup(func() {
+ bindings, _ := json.Marshal(old.Agents)
+ pg.UpdateTool(key, old.Description, old.Schema, bindings, old.Enabled)
+ })
+ }
+ custom := json.RawMessage(`{"type":"object","properties":{"text":{"type":"string","description":"USER TEXT"},"hints":{"type":"array","items":{"type":"object","properties":{"text":{"type":"string","description":"USER ITEM"}}}}},"required":["text"]}`)
+ for _, key := range []string{"report_finding", "add_hint", "add_task_hint"} {
+ if err := pg.UpdateTool(key, "USER DESCRIPTION", custom, json.RawMessage(`["custom-agent"]`), false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, key := range []string{"traffic_search", "traffic_get"} {
+ row, _ := pg.GetTool(key)
+ bindings := json.RawMessage(`["custom-agent"]`)
+ if key == "traffic_search" {
+ bindings = json.RawMessage(`["worker"]`)
+ }
+ if err := pg.UpdateTool(key, row.Description, row.Schema, bindings, false); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := pg.SetSetting("finding_workflow_tools_v2_reporter", "false"); err != nil {
+ t.Fatal(err)
+ }
+ s.seedFindingWorkflowTools()
+ for _, key := range []string{"report_finding", "add_hint", "add_task_hint"} {
+ row, _ := pg.GetTool(key)
+ if row.Enabled || row.Description != "USER DESCRIPTION" || len(row.Agents) != 1 || row.Agents[0] != "custom-agent" {
+ t.Fatal("changed user tool configuration", key)
+ }
+ if !strings.Contains(string(row.Schema), "USER TEXT") || !strings.Contains(string(row.Schema), "USER ITEM") {
+ t.Fatal("changed user schema", key)
+ }
+ field := "traffic_refs"
+ if key == "report_finding" {
+ field = "evidence_hint_id"
+ }
+ if !strings.Contains(string(row.Schema), field) {
+ t.Fatal("missing optional field", key)
+ }
+ }
+ search, _ := pg.GetTool("traffic_search")
+ get, _ := pg.GetTool("traffic_get")
+ if search.Enabled || !contains(search.Agents, "reporter") || get.Enabled || len(get.Agents) != 1 || get.Agents[0] != "custom-agent" {
+ t.Fatal("default/custom reader binding migration incorrect")
+ }
+ if err := pg.RemoveAgentFromTool("reporter", "traffic_search"); err != nil {
+ t.Fatal(err)
+ }
+ s.seedFindingWorkflowTools()
+ search, _ = pg.GetTool("traffic_search")
+ if contains(search.Agents, "reporter") {
+ t.Fatal("one-time migration undid later unbinding")
+ }
+ }
+
+ func TestFindingWorkflowReporterBindsBeforeWritingReport(t *testing.T) {
+ s, f, request := trafficEvidenceServer(t)
+ pg := s.m.pg
+ ctx := context.Background()
+ if err := pg.SetBool(settingAgentTrafficBinding, true); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { pg.SetBool(settingAgentTrafficBinding, false); s.m.SetTrafficEnabled(false) })
+ if err := s.m.SetTrafficEnabled(true); err != nil {
+ t.Fatal(err)
+ }
+ seedServerEvidenceFlow(t, s, "reporter-proof", []byte("local proof payload"))
+ seedServerEvidenceFlow(t, s, "reporter-baseline", []byte("local normal response"))
+ tools, def, cleanup := agent.AugmentTools(ctx, "reporter", nil)
+ defer cleanup()
+ if !strings.Contains(def.FindingGuidance, "报告前自动关联流量") || !strings.Contains(def.FindingGuidance, "绑定成功后重新调用") {
+ t.Fatal("reporter did not receive binding workflow")
+ }
+ for _, name := range []string{"traffic_search", "traffic_get", "get_task_worker_trace", "get_task_node_detail", "bind_finding_traffic", "get_finding_traffic", "update_finding_report"} {
+ workflowTool(t, tools, name)
+ }
+ finding, _ := pg.GetFinding(f.FindingID)
+ detail := workflowCall(t, ctx, workflowTool(t, tools, "get_task_node_detail"), map[string]any{"task_id": fmt.Sprint(*finding.TaskID), "id": f.NodeID}, false)
+ if !strings.Contains(detail, `"finding_id"`) || !strings.Contains(detail, `"finding_node_id"`) {
+ t.Fatal("reporter lacks explicit ID mapping")
+ }
+ workflowCall(t, ctx, workflowTool(t, tools, "traffic_search"), map[string]any{"host": "evidence.local"}, false)
+ for _, id := range []string{"reporter-baseline", "reporter-proof"} {
+ packet := workflowCall(t, ctx, workflowTool(t, tools, "traffic_get"), map[string]any{"id": id}, false)
+ if !strings.Contains(packet, "local") {
+ t.Fatal("reporter cannot inspect packet", packet)
+ }
+ }
+ refs := []db.TrafficRef{{TrafficID: "reporter-baseline", Role: "baseline"}, {TrafficID: "reporter-proof", Role: "proof", Note: "confirmed from recorded response"}}
+ workflowCall(t, ctx, workflowTool(t, tools, "bind_finding_traffic"), map[string]any{"finding_id": f.FindingID, "traffic_refs": refs}, false)
+ list := workflowCall(t, ctx, workflowTool(t, tools, "get_finding_traffic"), map[string]any{"finding_id": f.FindingID}, false)
+ var summary struct {
+ Version int64 `json:"version"`
+ }
+ if err := json.Unmarshal([]byte(list), &summary); err != nil || summary.Version != 1 {
+ t.Fatal(list, err)
+ }
+ workflowCall(t, ctx, workflowTool(t, tools, "update_finding_report"), map[string]any{"finding_id": f.NodeID, "evidence_version": summary.Version, "report": "## Local report\n\nVerified baseline and proof using saved evidence."}, false)
+ updated, err := pg.GetFinding(f.FindingID)
+ if err != nil || updated.ReportEvidenceVersion != summary.Version || updated.EvidenceVersion != summary.Version {
+ t.Fatal("report did not cover post-binding version", updated, err)
+ }
+ // Disabling automatic binding still lets Reporter read manually bound snapshots.
+ if r := request("PUT", "/api/settings", `{"agent_traffic_binding":false}`); r.Code != 200 {
+ t.Fatal(r.Code, r.Body)
+ }
+ off, offDef, closeOff := agent.AugmentTools(ctx, "reporter", nil)
+ defer closeOff()
+ if offDef.FindingGuidance != "" {
+ t.Fatal("off reporter still receives auto-binding guidance")
+ }
+ for _, tool := range off {
+ if tool.Name() == "traffic_search" || tool.Name() == "traffic_get" || tool.Name() == "traffic_blob" || tool.Name() == "bind_finding_traffic" {
+ t.Fatal("auto-binding tool exposed while off", tool.Name())
+ }
+ }
+ workflowCall(t, ctx, workflowTool(t, off, "get_finding_traffic"), map[string]any{"finding_id": f.FindingID}, false)
+ workflowTool(t, off, "update_finding_report")
+ }
diff --cc sidequestion/README.md
index 8fcb96d,0000000..4489387
mode 100644,000000..100644
--- a/sidequestion/README.md
+++ b/sidequestion/README.md
@@@ -1,66 -1,0 +1,66 @@@
+# ARTEX `/btw`
+
+普通聊天、任务 MainAgent 和当前任务自己的 Worker 支持独立旁路提问。主输入框输入 `/btw 问题` 即可提交,空 `/btw` 或“旁路提问”按钮打开历史。桌面使用可调整宽度的侧栏,移动端使用 Drawer。
+
+旁路回答根据提交时的 Agent 上下文快照生成,支持流式显示、追问、停止和清空。关闭面板、刷新页面或断开 SSE 都不会取消模型请求。停止只影响当前旁路;清空会取消旁路并删除旁路历史,同时保留主上下文快照。
+
+## 实现边界
+
- 沿用 Go、norma v0.3.6、Next.js、现有 Markdown / ResizablePanel / Drawer / AlertDialog 组件;没有修改 norma 或添加依赖。Planner、继承自其他任务的 Worker、工具型子任务升级不在本次范围内。
++沿用 Go、norma v0.3.7、Next.js、现有 Markdown / ResizablePanel / Drawer / AlertDialog 组件;没有修改 norma 源码或为旁路添加依赖。Planner、继承自其他任务的 Worker、工具型子任务升级不在本次范围内。
+
+```mermaid
+flowchart LR
+ A[主 Agent QueryDeps] --> B[实际 Provider 绑定]
+ B --> C[不可变结构化快照]
+ B --> D[主 Agent 正常工具循环]
+ C --> E[(PostgreSQL 最新快照)]
+ E --> F[快照 + 最近成功旁路问答 + 问题]
+ F --> G[SideQuestionService 单次 Provider 请求]
+ G --> H[(独立旁路历史和用量)]
+ H --> I[累计回答 SSE / 旁路面板]
+```
+
+- `capture.go` 只在 `Options.Deps.CallModel / CallModelSync` 标记主循环请求。Provider 装饰器位于具体模型内部、路由池外层选择之后,因此记录实际选中的模型;压缩和摘要请求不覆盖快照。
+- 请求开始、完整模型回复、运行终态发布快照。正在生成的半段回复不发布;工具调用通过 norma 的 `MessagesForAPI` 保持配对,工具结果在下一次主模型请求或运行终态进入快照。流式中止保留上一个有效边界。
+- 快照通过 JSON 深拷贝保留结构化消息、系统提示、工具定义及生成参数。模型推理不持有快照锁或数据库事务。
+- `SideQuestionService` 调用具体 Provider;必要时先生成旁路摘要,最终回答仅在首次上下文超限且尚未输出文本/工具调用时允许缩减后重试一次。不创建 agent session,不接入工具执行器、主 transcript、活动流或任务图,也不经过任务模型切换链。回答保留工具定义是为兼容既有结构化工具上下文;摘要请求不提供工具。新返回的工具调用没有执行路径。
+- 每个父会话一个运行请求,单个服务进程最多四个,单次超时 120 秒。旁路使用服务生命周期下的独立取消上下文。
+- 旁路请求保留模型配置引用和非敏感身份摘要;请求时从现有配置取得凭据。配置被删除,或模型、协议、地址等身份字段变化,要求先运行主 Agent 更新快照。测试不会改变产品默认模型。
+
+## 持久化和恢复
+
+`db/schema.sql` 自动创建 `side_question_sessions` 和 `side_question_requests`。前者保存父资源、最新快照、运行编号、版本和清理版本;后者保存问题、累计回答、状态、模型、快照时间、用量、事件序号和分页序号。
+
+父会话键使用 conversation ID,或 task ID + exploration ID + intent ID。Worker 不使用可复用的执行槽位命名。
+
+快照按父会话合并写入,每 250 ms 刷新一次,数据库比较 `(run_id, version)` 防止旧版本覆盖。旁路提交前再次保存选定快照。成功保存后释放内存中的大快照;失败时保留待写版本。回答累计内容在流式事件到来时最多每 250 ms 写入一次,终态立即保存并在数据库错误时有限重试。
+
+服务启动将遗留 `running` 请求标记为 `interrupted`,保留已落库的部分回答和用量,不自动重放请求。最近成功保存的上下文可直接用于下一次提问。旧会话没有快照时要求先运行主 Agent,不从 UI 活动记录重建上下文。
+
+清空操作递增清理版本并删除请求;条件更新阻止迟到的回调重新写回。物理父资源删除依靠外键级联,Worker 逻辑删除在同一事务中删除旁路数据,并拒绝后续迟到快照。任务归档先阻止新请求、等待主流程停止、取消并等待旁路落库;归档格式为 v3,同时兼容不含旁路表的 v1/v2。
+
+历史完整保存,按序号游标每页最多返回 20 条。模型请求最多回放最近 20 组成功问答原文,同时按 token 预算限制回放量;较旧问答维护独立滚动摘要。主上下文超预算时仅摘要旁路副本的旧部分,保留近期结构化工具调用与结果。摘要、准备进度与用量一起纳入旁路的并发、取消和 120 秒超时限制。详见 [上下文预算与开源参考](CONTEXT_BUDGET.md)。
+
+## HTTP 契约
+
+以下路径作为 `{parent}`,沿用现有认证及资源校验:
+
+- `/api/conversations/{id}`
+- `/api/tasks/{id}/chat`
+- `/api/tasks/{id}/intents/{iid}`
+
+| 请求 | 返回及行为 |
+| --- | --- |
+| `GET {parent}/side-questions?before={ordinal}` | `items` 按新到旧排列、独立 `current` 运行状态、`snapshot` 元信息、`next_cursor`;游标为 0 表示最新页 / 无下一页 |
+| `POST {parent}/side-questions` | JSON `{ "question": "…", "client_request_id": "UUID" }`;新请求返回 202 及请求对象;相同 ID 和问题返回既有对象 200 |
+| `DELETE {parent}/side-questions` | 取消并清空当前父会话的旁路问答 |
+| `GET /api/side-questions/{requestID}/events` | `snapshot` SSE 事件,`id` 为递增序号,`data` 为完整累计请求对象;清空时发送 `cleared` |
+| `POST /api/side-questions/{requestID}/cancel` | 显式取消;终态可从历史或 SSE 读取 |
+
+问题上限 4000 字符。无快照、模型配置变化、同一父会话忙或幂等 ID 冲突返回 409;全局并发上限返回 429。每次 SSE 连接都先发送累计状态,不依赖客户端之前收到的文本片段。前端按请求 ID + 序号合并,并在切换父会话、清空时废弃旧回调。
+
+## 验证与参考
+
+自动化检查、实际模型使用及已知限制见 [VALIDATION.md](VALIDATION.md)。
+
+独立请求参考 [Grok CLI side-question.ts(固定提交)](https://github.com/superagent-ai/grok-cli/blob/fb97af83f06dca873281d60168430f06c8de6324/src/utils/side-question.ts),运行隔离参考 [OpenCode(固定提交)](https://github.com/anomalyco/opencode/tree/b3f1a96c6dd7adeb28b36dd11add1998fc84d67b)。ARTEX 的上下文使用 norma 的结构化消息,未采用从前端日志拼接文本的方式。
diff --cc web/src/app/(main)/chat/page.tsx
index 909298b,74284d5..b3ec9fe
--- a/web/src/app/(main)/chat/page.tsx
+++ b/web/src/app/(main)/chat/page.tsx
@@@ -47,12 -47,13 +48,15 @@@ import
} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
- import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+ import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
+import { useSideQuestions } from "@/hooks/use-side-questions";
+ import { mergeActivities } from "@/lib/activity-merge";
import { api } from "@/lib/api";
import { shouldSubmitOnKey, useChatSendMode } from "@/lib/chat-send-mode";
+ import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client";
+import { isBtwCommand } from "@/lib/side-questions";
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
import { cn } from "@/lib/utils";