diff --git a/agent/assembly.go b/agent/assembly.go index c57f558f9..ddbb0620f 100644 --- a/agent/assembly.go +++ b/agent/assembly.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "log" + "log/slog" "runtime/debug" "sync" @@ -113,7 +113,7 @@ func (g *guardedTool) AcceptsRawInput() bool { func (g *guardedTool) Call(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (res actool.Result, err error) { defer func() { if r := recover(); r != nil { - log.Printf("[tools] %s panic: %v\n%s", g.Name(), r, debug.Stack()) + slog.Error("[tools] tool handler panicked", "tool", g.Name(), "panic", r, "stack", string(debug.Stack())) res, err = actool.Errorf(fmt.Sprintf("internal error in tool %s: %v (this call has failed; try different arguments or another tool)", g.Name(), r)), nil } }() diff --git a/agent/compaction.go b/agent/compaction.go index 36e38314c..e3c6fcb0e 100644 --- a/agent/compaction.go +++ b/agent/compaction.go @@ -20,7 +20,7 @@ import ( "context" "encoding/json" "fmt" - "log" + "log/slog" "sort" "strings" "sync" @@ -71,7 +71,7 @@ func (c *Compactor) OnPlannerRound(ctx context.Context, ts *db.ExplorationStore) } round, uncompressed, activeDigests, err := c.maintain(ts) if err != nil { - log.Printf("[compaction] maintain exp=%d: %v", ts.ID(), err) + slog.Warn("[compaction] maintain failed", "exp", ts.ID(), "err", err) return } needMinor := uncompressed >= c.n @@ -244,7 +244,7 @@ func (c *Compactor) major(ctx context.Context, ts *db.ExplorationStore) { } } if err := ts.SupersedeDigests(stale); err != nil { - log.Printf("[compaction] supersede exp=%d: %v", ts.ID(), err) + slog.Warn("[compaction] supersede failed", "exp", ts.ID(), "err", err) } for _, b := range toCreate { c.foldBlock(ctx, ts, g, b, nodeByID, cvers, c.generationFor(b, active)) @@ -258,7 +258,7 @@ func (c *Compactor) major(ctx context.Context, ts *db.ExplorationStore) { func (c *Compactor) foldBlock(ctx context.Context, ts *db.ExplorationStore, g *coldGraph, b block, nodeByID map[int64]*db.Node, cvers map[int64]int, generation int) { body, err := c.compress(ctx, g, b, nodeByID) if err != nil { - log.Printf("[compaction] compress exp=%d block=%v: %v", ts.ID(), b.Members, err) + slog.Warn("[compaction] compress failed", "exp", ts.ID(), "block", b.Members, "err", err) return } // Re-read fresh state and drop any member that revived while we compressed. @@ -279,7 +279,7 @@ func (c *Compactor) foldBlock(ctx context.Context, ts *db.ExplorationStore, g *c final := block{Members: members, Anchors: b.Anchors} payload := digestPayload(body, final, nodeByID, generation, blockSignature(final, cvers)) if _, err := ts.AddDigest(payload, members); err != nil { - log.Printf("[compaction] add digest exp=%d: %v", ts.ID(), err) + slog.Warn("[compaction] add digest failed", "exp", ts.ID(), "err", err) } } diff --git a/agent/coverage.go b/agent/coverage.go index 6ad9b40fd..913d5e332 100644 --- a/agent/coverage.go +++ b/agent/coverage.go @@ -1,7 +1,7 @@ package agent import ( - "log" + "log/slog" "github.com/Autumn-27/artex/db" ) @@ -15,7 +15,7 @@ func coverageOn(as *db.AssetStore, taskID int64) bool { } enabled, err := as.CoverageEnabled(taskID) if err != nil { - log.Printf("[coverage] task %d: reading the coverage flag failed; leaving coverage on: %v", taskID, err) + slog.Warn("[coverage] reading the coverage flag failed; leaving coverage on", "task_id", taskID, "err", err) return true } return enabled diff --git a/agent/noa.go b/agent/noa.go index 49d0662a1..83621b9ed 100644 --- a/agent/noa.go +++ b/agent/noa.go @@ -1,7 +1,7 @@ package agent import ( - "log" + "log/slog" "path/filepath" "github.com/Autumn-27/norma/agentcore" @@ -11,7 +11,7 @@ import ( // noaWarn returns a diagnostics sink tagging non-fatal noa messages with the // session, routed through the package logger (agents have no per-instance one). func noaWarn(session string) func(string) { - return func(msg string) { log.Printf("[noa] %s: %s", session, msg) } + return func(msg string) { slog.Warn("[noa] diagnostics", "session", session, "msg", msg) } } // noa is the "model-driven context compression" mechanism introduced in norma v0.4.0, diff --git a/agent/provider.go b/agent/provider.go index cf8251775..5cd49ef02 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -14,7 +14,7 @@ import ( "context" "fmt" "io" - "log" + "log/slog" "net/http" "net/url" "os" @@ -616,22 +616,23 @@ func logTestConnection(c Config, capt *llmrec.Capture) { attempts := capt.Attempts() if c.Format == FormatBedrockGateway { if len(attempts) == 0 { - log.Print("[llm-test] bedrock-gateway — no HTTP request was sent") + slog.Warn("[llm-test] bedrock-gateway: no HTTP request was sent") return } for i, a := range attempts { - log.Printf("[llm-test] bedrock-gateway — attempt %d/%d HTTP %d", i+1, len(attempts), a.Status) + slog.Info("[llm-test] bedrock-gateway attempt", "attempt", i+1, "attempts", len(attempts), "status", a.Status) } return } if len(attempts) == 0 { - log.Printf("[llm-test] %s / %s @ %s — no HTTP request was ever sent (config resolution or connection setup failed)", - c.Provider(), c.Model, c.BaseURL) + slog.Warn("[llm-test] no HTTP request was ever sent (config resolution or connection setup failed)", + "provider", c.Provider(), "model", c.Model, "base_url", c.BaseURL) return } for i, a := range attempts { - log.Printf("[llm-test] %s / %s @ %s — attempt %d/%d HTTP %d\nresponse body: %s", - c.Provider(), c.Model, c.BaseURL, i+1, len(attempts), a.Status, clipBody(a.Body)) + slog.Info("[llm-test] connection attempt", + "provider", c.Provider(), "model", c.Model, "base_url", c.BaseURL, + "attempt", i+1, "attempts", len(attempts), "status", a.Status, "response_body", clipBody(a.Body)) } } diff --git a/agent/slog_test.go b/agent/slog_test.go new file mode 100644 index 000000000..fdaa98abc --- /dev/null +++ b/agent/slog_test.go @@ -0,0 +1,33 @@ +package agent + +import ( + "bytes" + "context" + "log" + "strings" + "testing" + + "github.com/Autumn-27/artex/llmrec" +) + +func TestSlogPreservesTagsAndLevels(t *testing.T) { + var buf bytes.Buffer + prev := log.Default().Writer() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev) }) + + noaWarn("sess-1")("fallback triggered") + _, capt := llmrec.NewCapture(context.Background()) + logTestConnection(Config{Format: FormatBedrockGateway}, capt) + + lines := strings.Split(strings.TrimSpace(buf.String()), "\n") + if len(lines) != 2 { + t.Fatalf("got %d log lines, want 2:\n%s", len(lines), buf.String()) + } + if !strings.Contains(lines[0], "WARN [noa]") || !strings.Contains(lines[0], "session=sess-1") { + t.Fatalf("unexpected noa log line: %q", lines[0]) + } + if !strings.Contains(lines[1], "WARN [llm-test]") { + t.Fatalf("unexpected llm-test log line: %q", lines[1]) + } +} diff --git a/agent/spill.go b/agent/spill.go index 7d43d65a4..2336c0148 100644 --- a/agent/spill.go +++ b/agent/spill.go @@ -3,7 +3,7 @@ package agent import ( "bytes" "context" - "log" + "log/slog" "path/filepath" "strconv" @@ -54,7 +54,7 @@ func toolOutputDir(base, runDir, spillDir string) string { return filepath.Join(runDir, "cmd-output") } if err := spillDirMaker(base, spillDir); err != nil { - log.Printf("[agent] spill directory %s: %v", spillDir, err) + slog.Warn("[agent] spill directory creation failed", "dir", spillDir, "err", err) return "" } return spillDir @@ -100,7 +100,7 @@ func (h spillHooks) PreToolUse(ctx context.Context, name string, input []byte) ( func (h spillHooks) PostToolUse(ctx context.Context, name string, input, result []byte, isErr bool) { if bytes.Contains(result, spillMarker) { if err := h.share(h.dir); err != nil { - log.Printf("[agent] share the spill files in %s: %v", h.dir, err) + slog.Warn("[agent] failed to share spill files", "dir", h.dir, "err", err) } } if h.inner != nil { diff --git a/agent/toolrag.go b/agent/toolrag.go index f4e6c83d6..ac3d0336b 100644 --- a/agent/toolrag.go +++ b/agent/toolrag.go @@ -3,7 +3,7 @@ package agent import ( "context" "fmt" - "log" + "log/slog" "math" "os" "sort" @@ -183,15 +183,15 @@ func applyToolRAG(ctx context.Context, agentKey string, tools []actool.CoreTool, query, _ := ctx.Value(toolQueryKey{}).(string) out, projected, err := projectTools(query, tools, toolRAGKeep(deferred), k, score) if err != nil { - log.Printf("[tool-rag] %s: scoring failed, using full catalog (%d tools): %v", agentKey, len(tools), err) + slog.Warn("[tool-rag] scoring failed, using full catalog", "agent", agentKey, "tools", len(tools), "err", err) } else if !projected { - log.Printf("[tool-rag] %s: full catalog (%d tools; empty query or under %d)", agentKey, len(tools), toolRAGMinCatalog) + slog.Info("[tool-rag] using full catalog (empty query or under threshold)", "agent", agentKey, "tools", len(tools), "min_catalog", toolRAGMinCatalog) } else { names := make([]string, len(out)) for i, t := range out { names[i] = t.Name() } - log.Printf("[tool-rag] %s: selected %d/%d tools: %s", agentKey, len(out), len(tools), strings.Join(names, ", ")) + slog.Info("[tool-rag] selected tools", "agent", agentKey, "selected", len(out), "total", len(tools), "names", strings.Join(names, ", ")) } return out } diff --git a/agent/tools.go b/agent/tools.go index 0aedcd706..edf6efafa 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "log" + "log/slog" "strconv" "strings" "time" @@ -1584,7 +1584,7 @@ func (t *ToolSet) addFinding() actool.CoreTool { // advice "register it again if it is distinct" is unactionable, because the // retry hits the same check and is suppressed again. if a.ForceRegister { - log.Printf("[triage] override: force_register set, registering %q without the duplicate check", a.Name) + slog.Info("[triage] override: force_register set, registering without duplicate check", "candidate", a.Name) } else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) { res := map[string]any{ "duplicate_of_finding_id": ans.DuplicateOf, diff --git a/agent/tools_insert.go b/agent/tools_insert.go index b65d9c8d1..8f86a0cdc 100644 --- a/agent/tools_insert.go +++ b/agent/tools_insert.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "log" + "log/slog" "net" "net/url" "strconv" @@ -129,7 +129,7 @@ func insertAssetsRuleLoadFailure(err error) (actool.Result, bool) { if err == nil { return actool.Result{}, false } - log.Printf("[insert_assets] intercept rules unavailable: %v", err) + slog.Warn("[insert_assets] intercept rules unavailable", "err", err) return actool.Errorf("asset intercept rules are unavailable; insertion refused"), true } diff --git a/agent/triage.go b/agent/triage.go index 75ed0f437..435b1c2c4 100644 --- a/agent/triage.go +++ b/agent/triage.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "io" - "log" + "log/slog" "math" "net/http" "regexp" @@ -323,12 +323,16 @@ func (p *Planner) SetTriageClient(c TriageClient) { p.triage = c } // bounded: newest findings first (a duplicate of a fresh finding is the common case). func (t *ToolSet) triageDuplicate(ctx context.Context, in db.RecordFindingInput) (DuplicateAnswer, bool) { if t.triage == nil || t.ts == nil { - log.Printf("[triage] skip: client=%v store=%v", t.triage != nil, t.ts != nil) + slog.Info("[triage] skip", "client", t.triage != nil, "store", t.ts != nil) return DuplicateAnswer{}, false } nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500) - if err != nil || len(nodes) == 0 { - log.Printf("[triage] skip: nodes=%d err=%v", len(nodes), err) + if err != nil { + slog.Warn("[triage] skip: failed to list findings", "nodes", len(nodes), "err", err) + return DuplicateAnswer{}, false + } + if len(nodes) == 0 { + slog.Info("[triage] skip: no existing findings", "nodes", 0) return DuplicateAnswer{}, false } // Findings from independently created tasks on the same assets are NOT in the @@ -351,26 +355,26 @@ func (t *ToolSet) triageDuplicate(ctx context.Context, in db.RecordFindingInput) // candidate list is built from nodes whose FindingID is still 0 and every // entry is dropped (observed live: "nodes=6, no usable existing findings"). if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil { - log.Printf("[triage] populate finding ids failed: %v", err) + slog.Warn("[triage] populate finding ids failed", "err", err) } existing := triageCandidates(nodes, in) if len(existing) == 0 { - log.Printf("[triage] skip: no usable existing findings (nodes=%d)", len(nodes)) + slog.Info("[triage] skip: no usable existing findings", "nodes", len(nodes)) return DuplicateAnswer{}, false } - log.Printf("[triage] asking: existing=%d candidate=%q", len(existing), in.Name) + slog.Info("[triage] asking", "existing", len(existing), "candidate", in.Name) ans, err := t.triage.Duplicate(ctx, TriageCandidate{ Name: in.Name, VulnClass: in.VulnClass, Severity: in.Severity, Summary: in.Summary, }, existing) if err != nil { - log.Printf("[triage] client error (fail open): %v", err) + slog.Warn("[triage] client error (fail open)", "err", err) return DuplicateAnswer{}, false } // Carry the node id of the matched finding alongside its findings-table id: // the agent extends a finding through update_finding_report, which takes the // node id, so an answer that names only the table id sends it to the wrong call. ans = withNodeID(ans, existing) - log.Printf("[triage] answer: dup=%d node=%d conf=%.2f", ans.DuplicateOf, ans.DuplicateOfNode, ans.Confidence) + slog.Info("[triage] answer", "dup", ans.DuplicateOf, "node", ans.DuplicateOfNode, "conf", fmt.Sprintf("%.2f", ans.Confidence)) return ans, true } diff --git a/agent/worker.go b/agent/worker.go index 49284543e..e973e3c77 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "log" + "log/slog" "os" "path/filepath" "strconv" @@ -343,7 +343,7 @@ func makeRunDir(base, leaf string) { return } if err := runDirMaker(base, leaf); err != nil { - log.Printf("[agent] run directory %s: %v", leaf, err) + slog.Warn("[agent] run directory creation failed", "dir", leaf, "err", err) } } diff --git a/cmd/artex-archive-check/main.go b/cmd/artex-archive-check/main.go index af0efd9a2..929483f08 100644 --- a/cmd/artex-archive-check/main.go +++ b/cmd/artex-archive-check/main.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "fmt" "log" + "log/slog" "os" "path/filepath" "time" @@ -47,7 +48,7 @@ func check() error { cleanup, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := s.Delete(cleanup, uri); err != nil { - log.Printf("test object cleanup failed for %s: %v", uri, err) + slog.Warn("test object cleanup failed", "uri", uri, "err", err) } }() if err := s.Upload(ctx, uri, file, checksum); err != nil { diff --git a/cmd/artex/main.go b/cmd/artex/main.go index 19f9de6cd..2ea700d81 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -9,6 +9,7 @@ import ( "flag" "fmt" "log" + "log/slog" "net/http" "os" "os/signal" @@ -48,10 +49,10 @@ type configSnapshot struct { func logConfigSnapshot(s configSnapshot) { b, err := json.Marshal(s) if err != nil { - log.Printf("[config] snapshot unavailable: %v", err) + slog.Warn("[config] snapshot unavailable", "err", err) return } - log.Printf("[config] snapshot %s", b) + slog.Info("[config] snapshot", "config", string(b)) } // version is the build version, injected at release time via @@ -132,7 +133,7 @@ func run() int { skillDir, err := config.SkillDir() if err != nil { - log.Printf("[config] %v", err) + slog.Error("[config] skill directory unavailable", "err", err) return 1 } if abs, e := filepath.Abs(skillDir); e == nil { @@ -143,7 +144,7 @@ func run() int { // Proxies whose X-Forwarded-For the login rate limit reads; empty trusts none. trusted, err := server.ParseTrustedProxies(os.Getenv("ARTEX_TRUSTED_PROXIES")) if err != nil { - log.Printf("[config] ARTEX_TRUSTED_PROXIES: %v", err) + slog.Error("[config] invalid ARTEX_TRUSTED_PROXIES", "err", err) return 1 } trustedAddrs := make([]string, 0, len(trusted)) @@ -178,15 +179,15 @@ func run() int { // server/execpriv.go). An explicit option that cannot be applied stops the start. priv, err := server.ResolveExecPrivilege(*execUID, *execGID, flagWasSet("exec-uid") || flagWasSet("exec-gid")) if err != nil { - log.Printf("[config] %v", err) + slog.Error("[config] resolve exec privilege failed", "err", err) return 1 } if err := server.PrepareExecPrivilege(&priv, *dataDir, config.KeyDir(), config.Path()); err != nil { - log.Printf("[config] %v", err) + slog.Error("[config] prepare exec privilege failed", "err", err) return 1 } if err := server.InstallBashShim(priv); err != nil { - log.Printf("[config] %v", err) + slog.Error("[config] install bash shim failed", "err", err) return 1 } // Before the stores open and any agent runs: check that the isolation above holds @@ -197,7 +198,7 @@ func run() int { }) isolation, err := server.EnforceIsolation(runtime.GOOS, priv, selfTest, *devNoIsolation) if err != nil { - log.Printf("[config] %v", err) + slog.Error("[config] enforce isolation failed", "err", err) return 1 } @@ -225,7 +226,7 @@ func run() int { } go func() { - log.Printf("ARTEX %s backend listening on %s (data=%s, workers=%d)", version, *addr, *dataDir, mgr.Workers()) + slog.Info("ARTEX backend listening", "version", version, "addr", *addr, "data", *dataDir, "workers", mgr.Workers()) if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("serve: %v", err) } @@ -234,7 +235,7 @@ func run() int { // Wait for a stop signal. <-ctx.Done() - log.Println("shutting down...") + slog.Info("shutting down") // Close the listener before draining. Otherwise a request accepted during // the drain can start a detached run, and mgr.Close runs while that run // is still writing. @@ -242,13 +243,13 @@ func run() int { httpErr := httpSrv.Shutdown(shutdownCtx) cancel() if httpErr != nil { - log.Printf("http shutdown: %v", httpErr) + slog.Error("http shutdown failed", "err", httpErr) } drainCtx, drainCancel := context.WithTimeout(context.Background(), 15*time.Second) drainErr := srv.Wait(drainCtx) drainCancel() if drainErr != nil { - log.Printf("task drain: %v", drainErr) + slog.Error("task drain failed", "err", drainErr) } // The health writer flushes on ctx.Done(). Wait for it before the deferred // store close, so the last cooling window is not written at a closed database.