Files

171 lines
4.7 KiB
Go

package audit
import (
"encoding/json"
"fmt"
"sort"
)
// Surface names the regions of a bundle that text rules may scan. Rules choose
// their scope explicitly so that scanning user-supplied request text is always a
// deliberate choice rather than a default.
const (
SurfaceContent = "content" // response.content
SurfaceOutput = "output" // response.output, JSON-encoded
SurfaceArguments = "arguments" // response.tool_calls[*].arguments, JSON-encoded
SurfaceRequest = "request" // request.messages[*].content
// SurfaceRequestNew is the request content this call brought into the
// conversation from outside the model: messages from request.new_from on,
// except assistant turns, which were audited as the previous call's response.
// A finding here is reported once, on the turn the content arrived, rather than
// on every later turn that replays it.
SurfaceRequestNew = "request_new"
)
// DefaultScope is the output-only scope: the auditor judges what was produced,
// not what was prompted, unless a rule opts in.
var DefaultScope = []string{SurfaceContent, SurfaceOutput, SurfaceArguments}
// Surface is a locatable span of text within a bundle.
type Surface struct {
Locator string
Text string
}
// surfaces indexes the scannable text of a bundle once per audit.
type surfaces map[string][]Surface
func (b *Bundle) surfaces() surfaces {
s := surfaces{}
add := func(kind, locator, text string) {
if text != "" {
s[kind] = append(s[kind], Surface{Locator: locator, Text: text})
}
}
add(SurfaceContent, "response.content", b.Response.Content)
if b.Response.Output != nil {
if raw, err := json.Marshal(b.Response.Output); err == nil {
add(SurfaceOutput, "response.output", string(raw))
}
}
for i, call := range b.Response.ToolCalls {
if call.Arguments == nil {
continue
}
if raw, err := json.Marshal(call.Arguments); err == nil {
add(SurfaceArguments, locatorf("response.tool_calls[%d].arguments", i), string(raw))
}
}
newFrom := 0
if b.Request.NewFrom != nil {
newFrom = *b.Request.NewFrom
}
for i, m := range b.Request.Messages {
locator := locatorf("request.messages[%d].content", i)
add(SurfaceRequest, locator, m.Content)
if i >= newFrom && m.Role != "assistant" {
add(SurfaceRequestNew, locator, m.Content)
}
}
return s
}
// selectSurfaces returns the surfaces named by scope, or the default scope when
// scope is empty. Unknown names are a corpus error and are caught by validation.
func (s surfaces) selectSurfaces(scope []string) []Surface {
if len(scope) == 0 {
scope = DefaultScope
}
var out []Surface
for _, name := range scope {
out = append(out, s[name]...)
}
return out
}
// decodedSurfaces is selectSurfaces for checks that must read text as the caller
// would receive it. The output and arguments surfaces are JSON-encoded in
// surfaces(), which hides string boundaries and rewrites quotes and backslashes;
// here each decoded string in them becomes its own Surface under the same
// locator.
func (ctx *evalContext) decodedSurfaces(scope []string) []Surface {
b := ctx.bundle
if len(scope) == 0 {
scope = DefaultScope
}
var out []Surface
for _, name := range scope {
switch name {
case SurfaceArguments:
for i, call := range b.Response.ToolCalls {
locator := locatorf("response.tool_calls[%d].arguments", i)
for _, leaf := range stringLeaves(call.Arguments) {
out = append(out, Surface{Locator: locator, Text: leaf})
}
}
case SurfaceOutput:
for _, leaf := range stringLeaves(b.Response.Output) {
out = append(out, Surface{Locator: "response.output", Text: leaf})
}
default:
out = append(out, ctx.surfaces[name]...)
}
}
return out
}
// stringLeaves returns every non-empty decoded string in a JSON value, object
// keys included, in a stable order.
func stringLeaves(v any) []string {
var out []string
var walk func(any)
walk = func(v any) {
switch x := v.(type) {
case string:
if x != "" {
out = append(out, x)
}
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
walk(k)
walk(x[k])
}
case []any:
for _, item := range x {
walk(item)
}
}
}
walk(v)
return out
}
// requestText is the concatenated prompt, used for containment checks.
func (b *Bundle) requestText() string {
var out string
for _, m := range b.Request.Messages {
out += m.Content + "\n"
}
return out
}
// locatorf builds a stable, pointer-like location string for evidence.
func locatorf(format string, args ...any) string {
return fmt.Sprintf(format, args...)
}
func (b *Bundle) toolByName(name string) (Tool, bool) {
for _, t := range b.Request.Tools {
if t.Name == name {
return t, true
}
}
return Tool{}, false
}