judge

package
v1.2.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DenyGuidance = "" /* 128-byte string literal not displayed */

DenyGuidance is the actionable tail on hard blocks: what to change to get the call executable again. It ships in tail (not in the suffix) so every Deny path carries the same way back.

Variables

This section is empty.

Functions

func ChainGates

func ChainGates(first, second agentcore.BeforeToolCallFunc) agentcore.BeforeToolCallFunc

ChainGates composes two BeforeToolCall gates so the run gets trust first, then the risk grade, then the user hooks: a block from first short-circuits (second never runs), so an earlier gate stays authoritative over a later one. A nil operand is identity. A sandbox request from either gate survives composition: the second gate's decision wins field-by-field as before, but the sandbox bit is OR-ed in so a sandbox-tier grade cannot be dropped by a later no-op gate.

func ConversationLanguage

func ConversationLanguage(msgs agentcore.MessageList) string

ConversationLanguage reports the language the user is currently writing in, as "zh" (Simplified Chinese) or "en". It scans the newest user messages for a CJK ideograph — the practical signal for "answer me in Chinese" — and falls back to English, the default for golder's prompts. UI surfaces use it to localize fixed template text; the reviewer uses it to instruct the model to write its rationale in the user's language.

func CredentialPathReason added in v1.1.0

func CredentialPathReason(p string) (string, bool)

CredentialPathReason is the exported form of credentialPathRead for callers outside the judge package (the file tools) that have already resolved a path and want to refuse it with the same wording the static floor uses.

func EscalationPathFromText added in v1.2.17

func EscalationPathFromText(summary, justification, cwd string) string

EscalationPathFromText extracts the first plausible path token from an escalation's summary and the model's justification, resolved against cwd. "" means no grant is offered — the dialog then offers only allow/deny, which is the fail-closed direction: a missed path hides a row, it never grants one.

func FormatNote

func FormatNote(n Note) string

FormatNote renders one Note as a single line of plain text. The template follows the note's language (zh/en); the rationale is already in that language because the reviewer was instructed to write it that way.

func PermissionGate

func PermissionGate(state *permissions.State, opts GateOpts) agentcore.BeforeToolCallFunc

PermissionGate builds the mode-aware BeforeToolCall gate. The mode is read per call, so a /permissions switch applies to the next tool call even mid-run:

  • read-only: mutating tools are blocked with a NoteReadOnly note.
  • ask: verdicts above Allow prompt the human when In is set, and are blocked (with a note) otherwise.
  • auto: verdicts above Allow are decided by the reviewer — Confirm runs, Sandbox runs isolated, Deny blocks — each announced with a note.
  • full-access: no review; only the static floor can deny.

A nil state is treated as full-access (no gate).

func PlausibleWritableRoot added in v1.2.17

func PlausibleWritableRoot(p, cwd string) bool

PlausibleWritableRoot filters the candidates whose grant would be meaningless or dangerous: paths the command can already write (the workspace, the temp roots), the system runtime (read-only by design), and golder's own state. Exported because the TUI checks the same predicate when it decides whether to offer the grant.

func ReadOnlyShellCommand added in v1.2.21

func ReadOnlyShellCommand(command string) bool

ReadOnlyShellCommand reports whether this shell command is one the fast path recognizes — the same predicate the permission gate uses to skip the reviewer, exposed so the execution layer can contain what it allows. It carries the kill switch and the static floor with it, so a caller cannot forget either.

func ReadScopeGate added in v1.2.15

func ReadScopeGate(opts ReadScopeOpts) agentcore.BeforeToolCallFunc

ReadScopeGate builds the beforeToolCall gate that asks before a read-only tool reaches outside the workspace. It returns nil when there is no gate to build (no resolvable workspace root); callers chain it in front of the permission gate so consent is settled before the call is graded.

func ReviewTimeoutFromEnv

func ReviewTimeoutFromEnv(getenv func(string) string) time.Duration

ReviewTimeoutFromEnv resolves GOLDER_REVIEW_TIMEOUT_MS, clamped to a sane range. Unset or unparseable yields the default.

Types

type ApprovalAnswer added in v1.1.0

type ApprovalAnswer struct {
	// Approve runs the call. False blocks it (the model is told it was
	// denied and can propose something else).
	Approve bool
	// Always remembers the decision for this session, keyed by the request's
	// tool and summary prefix, so the same shape of call is not asked again.
	Always bool
	// Answered is false when the dialog could not run (ctx cancelled, no UI);
	// the gate then falls back to its fail-closed behavior.
	Answered bool
	// WritableRoot, when set together with Approve, means the user granted
	// this path read+write access INSIDE the sandbox for the session instead
	// of running the call unisolated. The driver has already registered the
	// grant with the sandbox (internal/seatbelt); the gate then re-contains
	// the call, so it runs under the widened sandbox rather than bare.
	WritableRoot string
	// ReadRoot, when set together with Approve, means the user granted this
	// directory for READING for the session (a read-scope answer). The grant
	// is registered by the gate itself as the read-root registry's single
	// owner, so every file tool and the sandbox see it on the next call.
	ReadRoot string
	// SessionReads, when set together with Approve, means the user allowed
	// local reads in the trust gate's directory for the session (the trust
	// dialog's "reads here" answer). The gate registers it with the trust
	// manager; being a trust decision rather than a workspace-boundary one,
	// reads outside the workspace still take the read-scope gate's consent.
	SessionReads bool
	// Persisted, when set together with Approve, means the driver has already
	// made this grant permanent (it wrote the managed store). The gate itself
	// never persists anything — it stays a decision layer — but its verdict
	// note must not say "for this session" when the grant outlives it.
	Persisted bool
}

ApprovalAnswer is the user's decision.

type ApprovalKind added in v1.1.0

type ApprovalKind string

ApprovalKind says why a call needs the user's answer.

const (
	// ApprovalConfirm: the reviewer graded the call Confirm and the mode is
	// not auto.
	ApprovalConfirm ApprovalKind = "confirm"
	// ApprovalNoSandbox: the reviewer asked for isolation but the execution
	// layer has no runner for this call, so approving runs it bare.
	ApprovalNoSandbox ApprovalKind = "no-sandbox"
	// ApprovalReviewFailed: the reviewer could not decide and the call cannot
	// be contained.
	ApprovalReviewFailed ApprovalKind = "review-failed"
	// ApprovalTrust: a side-effect tool in a directory the user has not
	// trusted. The gate is the trust manager, not the reviewer; the dialog
	// asks the same question the REPL's first-run prompt does.
	ApprovalTrust ApprovalKind = "trust"
	// ApprovalEscalation: the model asked to run a call outside the sandbox
	// (bash sandbox_permissions=require_escalated) while the reviewer graded
	// it Sandbox. The two sides disagree, so the gate asks the user instead
	// of silently recontaining the call — approving runs it unisolated.
	ApprovalEscalation ApprovalKind = "escalation"
	// ApprovalReadScope: a read-only tool (read, view_image, grep, find, ls)
	// was pointed outside the workspace. The workspace is the directory the
	// user opened, so this asks for consent rather than a risk verdict; the
	// answer is "just this read" (ReadGrant) or "this directory for the
	// session" (ReadRoot). It is the one question no approval mode waives,
	// including full-access.
	ApprovalReadScope ApprovalKind = "read-scope"
)

type ApprovalRequest added in v1.1.0

type ApprovalRequest struct {
	Kind    ApprovalKind
	Tool    string
	Summary string
	// Justification carries the model's reason when the call is an escalation
	// request (bash sandbox_permissions=require_escalated); empty otherwise.
	Justification string
	// ReadScope is the directory a read-scope request may be granted for the
	// session, or "" when no directory is offered (the answer is then "this
	// read" or "no"). Set only for ApprovalReadScope.
	ReadScope string
	// TrustDir names the directory a trust question is about, or "" for every
	// other kind. The trust gate's session answers - allow local reads, allow
	// all tools - are grants for this directory, so the dialog names it rather
	// than leaving "this folder" to be guessed. Set only for ApprovalTrust.
	TrustDir      string
	Risk          string
	Authorization string
	Rationale     string
}

ApprovalRequest is what the gate shows the user: the call itself plus the reviewer's verdict, so the decision is informed rather than a bare yes/no.

type Chain

type Chain struct {
	Inner Classifier
	// WorkspaceRoot is the project boundary the routine-edit fast path weighs a
	// patch against (editscope.go). Empty keeps that exemption off, which is the
	// safe default: without the boundary there is no way to tell an in-workspace
	// patch from one reaching the skills directory, so the reviewer keeps every
	// patch. The read-only fast path needs no root — a command's text is the whole
	// question there — which is why only this one reads it.
	WorkspaceRoot string
}

Chain runs StaticFloor first (deny wins), then inner, and degrades any inner error to Confirm. A nil inner grades static-only.

func (Chain) Classify

func (c Chain) Classify(ctx context.Context, tool string, args json.RawMessage) Verdict

Classify implements Classifier.

type Classifier

type Classifier interface {
	Classify(ctx context.Context, tool string, args json.RawMessage) Verdict
}

Classifier grades one tool call. Implementations must be safe for concurrent use: parallel tool batches grade concurrently.

type GateOpts

type GateOpts struct {
	In  *bufio.Reader
	Out io.Writer
	Mu  *sync.Mutex
	// Classifier grades one call. Production injects a Chain over the LLM
	// reviewer; nil keeps the static floor but fails closed on every gated
	// (non-read-only) tool instead of allowing it.
	Classifier Classifier
	// Sandboxed reports whether a tool call at the Sandbox tier will actually
	// run isolated by the execution layer (the bash tool's seatbelt runner).
	// When it returns true the gate lets the call through — isolation is the
	// enforcement, not a prompt or a block. Nil, or false for this tool,
	// prompts (interactive) or fails closed.
	Sandboxed func(toolName string) bool
	// Notify, when set, receives one Note per non-trivial verdict (approval,
	// sandbox routing, denial, read-only block, reviewer failure) so the
	// driver can show the decision and its rationale. Callbacks run on the
	// run goroutine; implementations must not block on the UI thread.
	Notify func(Note)
	// Confirm, when set, is the driver's approval dialog for a call the gate
	// cannot settle on its own: a Confirm tier outside auto mode, a Sandbox
	// tier the execution layer cannot isolate, or a failed review with no
	// containment. The interactive terminal drivers use In/Out instead; the
	// TUI has no stdin and supplies a callback that renders a dialog and
	// blocks on the user's answer. It runs on the run goroutine and must
	// itself be safe to block (the TUI implementation hands the request to
	// the UI goroutine and waits on a channel). nil keeps the fail-closed
	// behavior.
	Confirm func(ctx context.Context, req ApprovalRequest) ApprovalAnswer
	// Cwd is the directory the run is gated against. It is used to judge
	// whether an escalation's path is worth offering a grant for (a path the
	// command can already write needs none). Empty means no path grant is
	// offered.
	Cwd string
	// GrantWritable, when set, registers a path as writable for the session and
	// — when persist is true — makes that survive the process. It backs the
	// stdin prompt's `w`/`s` answers, the twin of the TUI dialog's rows, and is
	// a callback for the same reason the read grant's is: this package is a
	// leaf and cannot reach the sandbox registry or the managed store. why
	// carries the failure, or the note for a grant that was already in place.
	GrantWritable func(root string, persist bool) (made bool, why string)
	// OnPrompt, when set, is called with the question just before a prompt is
	// put to the person — whichever way that prompt travels (the driver's
	// Confirm dialog, or the stdin prompt) — and returns the function to call
	// once it has been answered. It exists so a driver can tell the terminal
	// around it that this pane is waiting for a human: see
	// internal/hostcompat. The returned function is called exactly once, even
	// when the prompt ran and the answer was "no", and even when no answer
	// arrived at all.
	//
	// A nil hook, or a hook returning nil, changes nothing. It is called on the
	// run goroutine, outside the prompt mutex, and must not block: it is the
	// driver's own transport, not part of the decision.
	OnPrompt func(question string) func()
}

GateOpts tunes PermissionGate. Interactive drivers pass the shared stdin reader/writer so Confirm/Sandbox prompts behave exactly like the trust gate; headless drivers leave In nil and get the fail-closed path.

type LLMJudge

type LLMJudge struct {
	// Review is the injected model call. Nil means no reviewer is available:
	// every call fails closed at Confirm.
	Review ReviewFunc
	// Timeout bounds one review; zero uses reviewDefaultTimeout.
	Timeout time.Duration
	// Cwd and DirTrust describe the launch directory ("trusted"/"untrusted")
	// so the reviewer sees the same trust context the trust gate enforces.
	Cwd      string
	DirTrust string
	// Language overrides the auto-detected rationale language ("zh"/"en").
	// Tests use it; production leaves it empty.
	Language string
}

LLMJudge grades one tool call with the active conversation model.

func NewLLMJudge

func NewLLMJudge(review ReviewFunc, cwd string, trusted bool) *LLMJudge

NewLLMJudge builds a reviewer over the injected model call. cwd/trusted describe the working directory the run is gated against.

func (*LLMJudge) Classify

func (j *LLMJudge) Classify(ctx context.Context, tool string, args json.RawMessage) Verdict

Classify implements Classifier.

type Level

type Level int

Level is the risk tier for one tool call.

const (
	// Allow runs without friction.
	Allow Level = iota
	// Confirm needs an explicit human yes.
	Confirm
	// Sandbox must run isolated; without a sandbox runner it prompts
	// (interactive) or blocks (headless) with a sandbox note.
	Sandbox
	// Deny never runs.
	Deny
)

func (Level) String

func (l Level) String() string

type Note

type Note struct {
	Tool string
	// ToolCallID is the originating call id, so a transcript can file the
	// note directly above that call's card.
	ToolCallID string
	Kind       NoteKind
	Level      Level
	// Summary is a short preview of the call (command/path), when available.
	Summary       string
	Risk          string
	Authorization string
	Rationale     string
	Lang          string
}

Note is one verdict announcement for the user: the decision, the tool, and the reviewer's rationale (already written in the user's language).

type NoteKind

type NoteKind int

NoteKind classifies one user-facing verdict note.

const (
	// NoteApproved: auto mode approved a Confirm-tier call (runs directly).
	NoteApproved NoteKind = iota
	// NoteSandboxed: a Sandbox-tier call runs isolated.
	NoteSandboxed
	// NoteDenied: the reviewer (or the static floor) denied the call.
	NoteDenied
	// NoteUnavailable: the reviewer failed and the call was handled
	// conservatively (sandboxed when possible, otherwise blocked).
	NoteUnavailable
	// NoteBlockedNoPrompt: the call needed confirmation but no interactive
	// prompt exists, so it was blocked.
	NoteBlockedNoPrompt
	// NoteReadOnly: read-only mode blocked a mutating tool.
	NoteReadOnly
)

type ReadScopeOpts added in v1.2.15

type ReadScopeOpts struct {
	// WorkspaceRoot is the directory the file tools treat as the boundary.
	// Empty means the process working directory, the same default the tools
	// use.
	WorkspaceRoot string
	// Roots are additional trusted read roots that are never asked about,
	// because golder itself advertised them (the skills directory is the one
	// case: the system prompt hands the model absolute SKILL.md paths).
	Roots []string
	In    *bufio.Reader
	Out   io.Writer
	Mu    *sync.Mutex
	// Confirm is the driver's approval dialog for a call that needs an answer.
	// It runs on the run goroutine and may block until the user answers.
	Confirm func(ctx context.Context, req ApprovalRequest) ApprovalAnswer
	// Notify receives the decision so the driver can show it, exactly as the
	// permission gate announces its verdicts.
	Notify func(Note)
	// Persist, when set, makes a read grant survive the process: the gate
	// calls it after the user chooses the remembered option and reports the
	// outcome in the note. It is a callback rather than a direct write because
	// this package is a leaf (it cannot import the config layer that owns the
	// managed store); a driver without one simply cannot offer the remembered
	// answer, and the prompt says so.
	Persist func(dir string) (made bool, why string)
	// OnPrompt, when set, is told the question just before a prompt is put to
	// the person and returns the function to call once it is answered. See
	// GateOpts.OnPrompt: it is how a driver tells the terminal around it that
	// this pane waits for a human (internal/hostcompat).
	OnPrompt func(question string) func()
}

ReadScopeOpts configures ReadScopeGate. Prompting follows the permission gate's two shapes: interactive drivers pass In/Out (the REPL's shared stdin), the TUI passes Confirm (it has no stdin), and a driver with neither gets the fail-closed path.

type ReviewFunc

type ReviewFunc func(ctx context.Context, systemPrompt, userPrompt string) (string, error)

ReviewFunc performs one model call for the reviewer: given a system prompt and a user message, it returns the model's final text. The wiring layer (cli/run) builds it from the active provider, so this leaf package stays free of provider imports. Implementations must be safe for concurrent use.

type Verdict

type Verdict struct {
	Level      Level
	Reasons    []string
	Confidence float64
	Source     string
	// Failed marks a reviewer that could not decide (timeout, transport
	// error, malformed answer). The gate must never treat it as an approval:
	// it prompts, sandboxes, or blocks instead.
	Failed bool
	// Risk ("low"/"medium"/"high"/"critical") and Authorization
	// ("unknown"/"low"/"medium"/"high") are the reviewer's own rating, used
	// in the verdict card. Empty for static verdicts.
	Risk          string
	Authorization string
	// Lang is the rationale's language ("zh"/"en"), so UI templates can
	// match it.
	Lang string
}

Verdict is one classification result.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL