judge

package
v1.5.21 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 23 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.

View Source
const LocalSource = "local"

LocalSource names this stage in a Verdict, so a card or a note can say which judge answered — the same courtesy the reviewer's own Source string pays.

Variables

View Source
var SandboxDenialMarkers = []string{
	"operation not permitted",
	"permission denied",
	"read-only file system",
	"sandbox",
	"landlock",
	"seccomp",
}

SandboxDenialMarkers are the failure signatures that indicate the OS sandbox refused an operation, as opposed to the command itself failing. They mirror codex's detection list (sandboxing/src/denial.rs). One list answers both questions about a denial — whether it happened (LooksSandboxDenied) and which path it named (PathsFromDenial) — so the two can never disagree.

Functions

func AskDisposition added in v1.3.1

func AskDisposition(kind ApprovalKind, lang string) string

AskDisposition says, in one phrase, why a question reached the human instead of being settled by review. Under ask every graded call lands here; under auto only a handful do, and naming the reason is the whole point — auto is a promise not to interrupt, so the one moment it does owes the reader an explanation of what made this call an exception.

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 ConsentGate added in v1.4.6

func ConsentGate(opts ConsentOpts) agentcore.BeforeToolCallFunc

ConsentGate builds the single gate production drivers install after trust. It replaces the separate boundary and permission gates.

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 DecisionLine added in v1.3.1

func DecisionLine(tool, mode string, level Level, disposition string) string

DecisionLine renders the one line every approval surface shares: the tool, the approval mode in force, the reviewer's grade, and who settles it —

bash · ask · confirm → your call
bash · auto · contain → contained · runs in the sandbox

The mode and the grade are the canonical tokens the CLI itself uses (/permissions auto, the reviewer's verdict) rather than paraphrases, because the question this line exists to answer — "does a human have to answer this?" — is a question about exactly those two words: confirm under ask is the user's to settle, confirm under auto is the reviewer's. What follows the arrow is plain language, since that is where the difference lands.

func DecisionLineWithSource added in v1.4.7

func DecisionLineWithSource(tool, mode string, level Level, source, disposition string) string

DecisionLineWithSource is DecisionLine plus the layer that reached the verdict. The source is a canonical token (jev/local/llm/static), printed after the grade:

bash · auto · allow · via local → approved

It belongs on the same line as the mode and grade: "which judge decided this" is as much a part of reading the decision as "which mode was active".

func DenialExplanation added in v1.3.3

func DenialExplanation(output, cwd string) string

DenialExplanation explains a sandbox denial that has no grantable path. It is the other half of PathsFromDenial: when every path the OS named is system protected or credential material, saying so is more useful than silently falling back to the command text and offering a path that cannot fix it.

A protected system path is often not a sandbox decision at all: macOS SIP reports /private/var/select/sh as "Operation not permitted" even outside the sandbox. A credential path is one the static floor deliberately refuses to hand over by a keystroke. Both need a one-call unisolated approval, not a path grant.

func EnvelopeBare added in v1.3.4

func EnvelopeBare(command, lang string) (bool, string)

EnvelopeBare reports whether command may run outside the OS sandbox, with a reason the note can carry. It is called only for a call the gate is ready to approve: the envelope narrows an approval, it never grants one.

func FormatNote

func FormatNote(n Note) string

FormatNote renders one Note as a single line of plain text: the decision line (tool · mode · grade → outcome), the reviewer's risk and authorization rating when there is one, and the rationale — the last two in the language of the conversation, since the reviewer wrote the rationale that way.

func GrantablePathFromText added in v1.3.1

func GrantablePathFromText(summary, justification, cwd string) string

GrantablePathFromText extracts the first plausible path from a call's command and its justification, resolved against cwd. The command goes through commandPaths — the boundary gate's own reader: shellfacts (mvdan) for the grammar, plus the program tables for what the grammar cannot say — so a script's words are never mistaken for paths ("sed -E 's#x#y#g'" has no path in it, and its "/g" flag once reached a dialog). The justification is prose written by the model, so it is read with the lexical scan. "" means no grant is offered — a dialog then shows only allow/deny and a denial has nothing to re-admit — which is the fail-closed direction: a missed path hides a row, it never grants one.

func LooksSandboxDenied added in v1.3.1

func LooksSandboxDenied(output string) bool

LooksSandboxDenied reports whether a sandboxed command's output looks like a sandbox denial rather than an ordinary command failure. The caller only consults this for failed sandboxed runs.

func NetworkKey added in v1.3.3

func NetworkKey(tool string, args json.RawMessage) (key string, ok bool)

NetworkKey names the host a network need is about, for the dialog and for a one-call answer. The network is decided per call now: there is no standing host/command rule to match, so a key this layer cannot pin down is simply empty and the dialog says "network access".

func NetworkRequested added in v1.3.1

func NetworkRequested(tool string, args json.RawMessage) bool

NetworkRequested reports whether a call reaches the network. Two shapes count: bash asking for it (`network: "on"`), and the tools whose whole effect IS an outbound request — webfetch and websearch. The second shape matters because those tools run in this process, where no OS sandbox can contain them: the gate is the only boundary they have, so a call that skipped the network question would reach the internet on the strength of a tool description rather than on a decision.

A request is never an authorization: the gate grants it only after the selected reviewer or the person answers, and the executor never reads the argument as a capability.

func OutlivingPaths added in v1.3.0

func OutlivingPaths(tool string, args json.RawMessage) []string

OutlivingPaths returns the paths in this call whose effect outlives the call, or nil when there are none. It is exported for the reviewer's state: the decision model grades every patch now, and this is the one fact about a patch that its file contents do not reveal — a hook body looks like any script until you know when it runs.

func PathWriteNeed added in v1.3.1

func PathWriteNeed(path, summary string) bool

PathWriteNeed reports whether a denied path is needed for WRITING rather than reading, so the question can say which it is and lead with the row that actually unblocks the command. Three signals, cheapest first: a path that does not exist can only have been needed for writing (there is nothing to read out of it); a redirection that writes to the path (or under it); and a command whose verb, or path-taking flag, makes the path a write target. The parse is what keeps a stderr redirect (`2>/dev/null`) from counting as a write. It stays a heuristic — the dialog still offers both sides — and it is biased to "read" when unsure, which is the narrower grant.

func PathWritten added in v1.3.8

func PathWritten(path, summary string) bool

PathWritten reports whether the command's own text writes path: a redirect target, a write verb's operand, or a flag value naming it. Unlike PathWriteNeed it makes no guess from the path's absence, so it is the right question for a gate deciding the SIDE of a question it is about to ask — reading a file that does not exist is still a read.

func PathsFromDenial added in v1.3.1

func PathsFromDenial(output, cwd string) string

PathsFromDenial returns the first path a sandbox denial named, or "". The OS message is the ground truth about what was refused: it prints the path the syscall failed on — read or write — including paths no static reading of the command can derive (variables, loops, generated names) and paths it can get wrong (a shell metacharacter in a sed expression once offered "/\1"). Only lines carrying a denial marker are read, and every candidate must survive NormalizePath and PlausibleWritableRoot, so a denial naming nothing grantable yields "" and the caller falls back to the command text.

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 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.

func SecretPathReason added in v1.3.0

func SecretPathReason(p string) (string, bool)

SecretPathReason is the write side's twin of CredentialPathReason: callers outside this package (the file tools) refuse a write into live secret material with the same wording the static floor uses, so a granted directory cannot quietly become a way to rewrite an SSH key.

func TouchedPaths added in v1.3.0

func TouchedPaths(tool string, args json.RawMessage) []string

TouchedPaths returns the path spellings a call names, for a caller outside this package that needs the same extraction the boundary gate uses. It is how the reviewer's state reports what a call touches, so the model reasons about the same set the gate asks about rather than a second, drifting reading of the arguments — a mismatch between the two is the failure the boundary regression test exists to catch.

func UserIntentSection added in v1.4.15

func UserIntentSection(msgs agentcore.MessageList) string

UserIntentSection renders the recent USER messages only, for the decision model's state. It is deliberately narrower than the LLM reviewer's transcript: the decision model is an additional outbound call, and tool output is not evidence of intent. The selection budget is the same, so the two layers read the same words.

func WriteAllowed added in v1.3.0

func WriteAllowed(path string, writableAt func(string) bool) bool

WriteAllowed reports whether a write to path is already authorized for this session: the session's writable registry covers it, or the authorization table carries a write grant for it.

It is shared, deliberately, by the two callers that must not disagree — the gate, which decides whether to ASK, and the write tool, which decides whether to WRITE. The gate stays silent exactly when this answers true, so a mismatch is a failure the user sees: a patch refused after they approved it, or a question about a directory they just granted. Both sources are consulted because both are answers the user gave: the registry is where config.toml, permissions.toml and the sandbox dialog put theirs, the table is where every dialog answer now lands — including the one-call "allow this write" row, which is recorded as an exact-path grant and would otherwise silence the question while the tool kept refusing.

writableAt may be nil for a caller that has no registry to consult; the table alone then decides, which is the stricter reading.

Types

type ApprovalAnswer added in v1.1.0

type ApprovalAnswer struct {
	// Scope, Needs and Exec are the capability answer for ApprovalConsent.
	Scope Scope
	Needs []Need
	Exec  ExecMode
	// 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
	// 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
}

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 (
	// ApprovalConsent is the unified capability question. Its Needs name every
	// capability the call requires; the mode decides who answers, and one
	// answer settles all of them.
	ApprovalConsent ApprovalKind = "consent"
	// 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"
)

type ApprovalRequest added in v1.1.0

type ApprovalRequest struct {
	Kind ApprovalKind
	// Source names the layer that reached the verdict: jev, local, llm or
	// static. The dialog prints it in the decision line so the reader does not
	// have to infer the judge from the rationale's wording.
	Source string
	// Needs is the complete capability request for an ApprovalConsent. The
	// dialog shows them together; an approval grants exactly this set.
	Needs []Need
	// Mode is the approval mode in force for this call (auto, ask, read-only,
	// full-access). It is the answer to the reader's real question — "does a
	// human have to answer this?" — which is why every surface prints it: the
	// same verdict is the user's to settle under ask and already settled under
	// auto.
	Mode string
	// Level is the grade the gate acted on (allow, confirm, contain, deny),
	// printed as the canonical token rather than a paraphrase so the dialog,
	// the notes and /permissions all use one vocabulary.
	Level   Level
	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
	// 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
	Rationale string
	// Origin names the agent that asked, when it is not the session's own
	// conversation: a sub-agent's dispatch, filled from the call's context. The
	// dialog prints it so the person knows who is asking; a question that reads
	// as coming from the conversation when a delegated child asked it is a
	// question about a call they never saw.
	Origin 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 AskCoord added in v1.3.3

type AskCoord struct {
	// contains filtered or unexported fields
}

AskCoord carries one combined answer from the gate that asked it to the gate that would otherwise ask the same call's second question. The chain runs trust → boundary → permission and cannot pass a context back, so a shared per-chain object is the smallest way to keep "one dialog for path + network" true without making the boundary gate own the permission gate's decision.

It is keyed by call ID; a call without an ID falls back to the call shape, and a miss simply restores today's behavior (the permission gate asks its own question).

func NewAskCoord added in v1.3.3

func NewAskCoord() *AskCoord

NewAskCoord returns an empty coordinator.

func (*AskCoord) Put added in v1.3.3

func (c *AskCoord) Put(callID string, ans ApprovalAnswer)

Put records the answer for callID.

func (*AskCoord) Take added in v1.3.3

func (c *AskCoord) Take(callID string) (ApprovalAnswer, bool)

Take removes and returns the answer for callID.

type AuthFact added in v1.3.0

type AuthFact struct {
	// Path is the resolved absolute path.
	Path string `json:"path"`
	// InWorkspace reports that the path lands inside the directory the user
	// opened, or inside a root golder itself advertised (the skills directory).
	InWorkspace bool `json:"inWorkspace"`
	// NeedsConsent reports that the boundary gate puts a question about this
	// path: outside the workspace, unread-approved, not credential material and
	// not on the system whitelist. It is the gate's own answer, so a model that
	// sees false knows consent is already settled — by the workspace, by a
	// grant, or by a refusal that will block the call.
	NeedsConsent bool `json:"needsConsent,omitempty"`
	// Read, Write and Execute are the authorization table's decision for this
	// path: "granted", "refused", or empty when nothing speaks to it. The three
	// are reported separately because the table keeps them separate — a
	// directory trusted for running commands does not authorize rewriting it.
	Read    string `json:"read,omitempty"`
	Write   string `json:"write,omitempty"`
	Execute string `json:"execute,omitempty"`
}

AuthFact is what is known about one path a call touches.

func AuthFacts added in v1.3.0

func AuthFacts(tool string, args json.RawMessage, workspaceRoot string, extraRoots []string, writableAt func(string) bool) []AuthFact

AuthFacts describes the paths one tool call touches. It returns nil when the call names no path this package can read, which is the honest answer for a tool with no path arguments and for one the tool table has not been taught.

type Capability added in v1.4.6

type Capability uint8

Capability is one thing a call may need beyond the default sandbox policy.

const (
	CapReadOutside Capability = 1 << iota
	CapWriteOutside
	CapNetwork
	CapUnconfined
	CapHostControl
	CapBrowserRuntime
)

type Chain

type Chain struct {
	Inner Classifier
}

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

apply_patch has no exemption here. It used to: an ordinary in-workspace patch skipped the reviewer, measured at 467 calls and 18.5 minutes of review over ten sessions. The decision model made that affordable to remove — a graded call costs a fraction of the old reviewer's round trip — and removing it is what lets a patch be judged as a whole: the edit's content, where it lands, and whether its effect outlives the call (judge.OutlivingPaths, reported through the reviewer's state).

func (Chain) Classify

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

Classify implements Classifier: the static floor, then the reviewer.

There is nothing between them. This chain used to carry two exemptions — a provably read-only shell command, and a set of tools with no side effects — and both are gone: every call is reviewed. The decision model is what made that affordable, and removing the exemptions is what made the rest of the design small, because a rule with no exceptions needs no machinery to justify its exceptions.

The floor stays in front, and it is not an optimization: it is the one layer that denies credential material WITHOUT asking a model, so a verdict it reaches cannot be argued with, retried, or reached by a prompt. Everything else — including what a model would obviously allow, like `ls` — is the reviewer's to decide.

type Classification added in v1.3.0

type Classification string

Classification is what a command does to the world. Only ReadOnly is decided locally; the rest name the tiers a future classifier could use, and are the vocabulary of bash-classify's scheme.

const (
	// ReadOnly touches no state: it reads, lists, or inspects.
	ReadOnly Classification = "READONLY"
	// LocalEffects changes files or local state only.
	LocalEffects Classification = "LOCAL_EFFECTS"
	// ExternalEffects reaches another system: the network, a cluster, a service.
	ExternalEffects Classification = "EXTERNAL_EFFECTS"
	// Dangerous is destructive or hard to reverse.
	Dangerous Classification = "DANGEROUS"
	// Unknown is a program or subcommand this machine has no rule for. It is
	// ranked above ExternalEffects and below Dangerous, and — like Dangerous —
	// it is never decided locally.
	Unknown Classification = "UNKNOWN"
)

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 ConsentAnswer added in v1.4.6

type ConsentAnswer struct {
	Allow    bool
	Answered bool
	Scope    Scope
	Needs    []Need
	Exec     ExecMode
	// Reason is the reviewer's one-line explanation, when it gave one. The
	// dialog uses it for the note; a programmatic recovery uses it in the
	// transcript so a refusal is not silent.
	Reason string
}

ConsentAnswer is one answer to a ConsentRequest. The driver never sets individual grant booleans: Needs and Scope are the decision.

func PromptConsent added in v1.4.6

func PromptConsent(ctx context.Context, in *bufio.Reader, out io.Writer, mu *sync.Mutex, req ConsentRequest, lang string) ConsentAnswer

PromptConsent is the exported stdin shape for drivers that own no Confirm callback (notably the sandbox-denial recovery question).

func ReviewRecovery added in v1.4.6

func ReviewRecovery(ctx context.Context, opts ConsentOpts, req ConsentRequest) ConsentAnswer

ReviewRecovery settles a post-execution capability request with the SAME mode policy as ConsentGate. It exists because a sandbox denial is discovered after the call already ran: there is no tool call left to gate, only one concrete Need ("this path"), and asking the original question again would be both late and confusing.

The distinction that keeps this honest:

  • auto: the reviewer decides alone. An allow grants the Need for this retry; a deny/contain/failure refuses it. Confirm and the stdin dialog are never consulted, so auto remains fully automatic.
  • ask: the reviewer filters an outright denial; otherwise this is the one human dialog, carrying the same Need list the gate would have shown.
  • read-only: refuse.
  • full-access: allow; there is no sandbox to recover from.

The caller applies the answer (path registration, retry). Policy lives here so the after-the-fact path cannot drift from the before-the-call one.

type ConsentConfirm added in v1.4.6

type ConsentConfirm func(ctx context.Context, req ConsentRequest) ConsentAnswer

ConsentConfirm is the driver's one-question channel.

func ConsentFromApproval added in v1.4.6

func ConsentFromApproval(f func(context.Context, ApprovalRequest) ApprovalAnswer) ConsentConfirm

ConsentFromApproval adapts the driver callback to the consent gate: the driver speaks ApprovalRequest/ApprovalAnswer, the gate speaks ConsentRequest/ConsentAnswer.

type ConsentOpts added in v1.4.6

type ConsentOpts struct {
	Mode           *permissions.State
	Classifier     Classifier
	Cwd            string
	ExtraRoots     []string
	Sandboxed      func(tool string) bool
	RequireSandbox bool
	Enforce        bool
	// BrowserRuntimeOutside is host policy for macOS Chromium, whose child
	// sandbox cannot initialize beneath an inherited Seatbelt profile.
	BrowserRuntimeOutside bool
	Notify                func(Note)
	Confirm               ConsentConfirm
	In                    *bufio.Reader
	Out                   io.Writer
	Mu                    *sync.Mutex
	OnPrompt              func(question string) func()
	WritableAt            func(path string) bool
	GrantWritable         func(root string, persist bool) (bool, string)
	PersistReadRoot       func(dir string) (bool, string)
}

ConsentOpts configures the unified gate.

type ConsentRequest added in v1.4.6

type ConsentRequest struct {
	Tool          string
	Summary       string
	Justification string
	// Source names the layer that reached the verdict (jev/local/llm/static).
	// The driver prints it in the decision line.
	Source        string
	Needs         []Need
	Mode          string
	Level         Level
	Risk          string
	Authorization string
	Rationale     string
	Origin        string
	CanContain    bool
	RequestedExec ExecMode
}

ConsentRequest is the complete question for one call. Needs is the exact set the call cannot run without; an Allow answer grants all of them.

type ExecMode added in v1.4.6

type ExecMode uint8

ExecMode is the execution envelope an answer chooses.

const (
	ExecSandboxed ExecMode = iota
	ExecUnconfined
)

type FirstParty added in v1.4.9

type FirstParty struct {
	Next Classifier
}

FirstParty runs before the JEV/local routine grader. Tools it does not know fall through unchanged; tools it knows return a verdict with a source.

func (FirstParty) Classify added in v1.4.9

func (f FirstParty) Classify(ctx context.Context, tool string, args json.RawMessage) Verdict

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
	// Contain must run isolated: the reviewer will not vouch for this call
	// running anywhere else. Without a sandbox runner the gate prompts
	// (interactive) or blocks (headless) with a containment note. The name says
	// what the tier REQUIRES, not where the call ends up — Allow and Confirm
	// execute inside the sandbox too, unless the gate's envelope admits them
	// (see envelope.go).
	Contain
	// Deny never runs.
	Deny
)

func (Level) String

func (l Level) String() string

type Local added in v1.3.0

type Local struct {
	// Next grades everything this stage defers. It is the reviewer that would
	// have graded the call anyway, so deferring is not a fallback — it is the
	// pre-existing path.
	Next Classifier
}

Risk is how much attention a command deserves, independently of what it does: `git status` and `rm -rf` differ in both axes, but so do `ls` and `cat ~/.ssh/id_rsa`, which are both read-only. Local grades a shell command from the rule table, and defers the tiers it cannot weigh to Next.

It stands where the decision model stands — the classifier the approval gate consults on every gated call — so that a run WITHOUT a decision-model credential is not left with a ~2.2s session-model round trip per command. JEV goes in front of it when it is configured (see cli/run.NewReviewer), so the two never compete: whichever is present answers, and what it cannot answer falls to the session model.

func (Local) Classify added in v1.3.0

func (l Local) Classify(ctx context.Context, tool string, args json.RawMessage) Verdict

Classify implements Classifier: grade the command, decide the routine tiers, defer the rest.

type Need added in v1.4.6

type Need struct {
	Cap Capability
	// Path is the resolved target for an outside-workspace need.
	Path string
	// Dir is the narrowest directory a session grant would cover.
	Dir string
	// Key names a network host/command.
	Key string
}

Need is one capability request with the exact scope it would cover.

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
	// Source names the layer that reached the verdict (jev/local/llm/static).
	// FormatNote prints it in the decision line.
	Source string
	// Needs names the capabilities the call required when it was not granted;
	// Granted names what the answer actually gave. They replace the old
	// high/medium/low risk and authorization words: a reader can act on
	// "write /tmp/out, network github.com" but not on "risk: medium".
	Needs         []Need
	Granted       []Need
	Risk          string
	Authorization string
	Rationale     string
	Lang          string
	// Mode is the approval mode that was in force for this call (auto, ask,
	// read-only, full-access), stamped by the permission gate. It is what makes
	// a verdict line answer the reader's real question — the same grade means
	// "a human said yes" under ask and "the reviewer decided" under auto — so a
	// note built outside a gate (trust, boundary bookkeeping) may leave it empty
	// and render without it.
	Mode string
	// Origin names the agent that asked, when it is not the session's own
	// conversation (a sub-agent dispatch). Empty for a direct call. It is a
	// label for the reader, never an input to a decision.
	Origin string
	// Escalation records that the call asked to run outside the sandbox (bash's
	// sandbox_permissions=require_escalated). The gate decides such a call twice
	// — once on the command's own merits, once on the escape — and a note that
	// cannot say which of the two was refused renders as "allow → denied", which
	// reads as a contradiction instead of a decision.
	Escalation bool
}

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: a call the gate allowed to run directly — auto's Confirm
	// grade, or a user's yes under ask.
	NoteApproved NoteKind = iota
	// NoteSandboxed: a Sandbox-tier call runs isolated.
	NoteSandboxed
	// NoteEscaped: a call ran OUTSIDE the sandbox — the reviewer approved an
	// escalation request, or the user did. It is the one outcome a sandboxed
	// session must never reach the user unannounced, so it has its own kind
	// rather than riding on NoteApproved.
	NoteEscaped
	// 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
	// NoteBoundaryGranted: the workspace-boundary gate was answered yes, so the
	// call may reach outside the workspace. It is NOT a reviewer verdict: the
	// rating suffix belongs to risk grading, and an answer to a consent question
	// has no risk grade behind it.
	NoteBoundaryGranted
	// NoteBoundaryDenied: the person said no to a boundary question. The path is
	// recorded as refused for the session, so the same question is not put again.
	NoteBoundaryDenied
	// NoteBoundaryNoPrompt: the boundary question could not be asked at all (no
	// dialog and no stdin), so the call failed closed. It is a failure to ASK,
	// not a verdict — nothing is recorded — and saying so is the point: an
	// earlier version reported it as an auto-review denial, which blamed the
	// reviewer for a question nobody was asked.
	NoteBoundaryNoPrompt
)

func (NoteKind) Failure added in v1.3.0

func (k NoteKind) Failure() bool

Failure reports whether the note records a call that did not run: the two renderers paint those in the error color, and a new blocking kind has to be added here rather than in both of them.

type OnceSet added in v1.3.1

type OnceSet struct {
	// contains filtered or unexported fields
}

OnceSet answers "is this the first time?" for the path-scoped questions the harness puts to a person. One implementation for one rule: a question that was asked and answered must not be asked again in the same run, or a retrying model turns a refusal into a nag. Safe for concurrent use — tool batches run in parallel and the gate's closure is shared across those calls.

func (*OnceSet) First added in v1.3.1

func (s *OnceSet) First(key string) bool

First records key and reports whether this was its first sighting. An empty key is never a question worth asking, so it reports false without recording.

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 judge stays free of provider imports. Implementations must be safe for concurrent use.

type Scope added in v1.4.6

type Scope uint8

Scope is the lifetime of an answered need.

const (
	ScopeOnce Scope = iota
	ScopeSession
	ScopeRemembered
)

type Verdict

type Verdict struct {
	Level      Level
	Reasons    []string
	Confidence float64
	Source     string
	// Network is an explicit one-call capability decision, independent of the
	// level. It is set only when this classifier actually reviewed a call that
	// requests network access: a bash call asking network:on, or the in-process
	// network tools (webfetch, websearch), which cannot run without it. A level
	// of Allow/Confirm/Contain alone never implies it.
	Network bool
	// 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.

func LocalReadOnlyVerdict added in v1.4.7

func LocalReadOnlyVerdict(tool string, _ json.RawMessage, lang string) (Verdict, bool)

LocalReadOnlyVerdict is the deterministic tier for native file readers. It is shared by the local table and the JEV router: whichever routine grader is active, a call that can only read files should not spend a model round trip to discover that. "Read-only" here is a property of the tool table, not a heuristic: the tool must be marked readOnly and must name paths (which excludes the network tools and the in-memory tools), and shell tools are excluded because their text is not a closed set of file operands.

This is not an outermost allow: the gate still runs the static floor before it, the workspace boundary still asks/records where the read lands, and the read itself still enforces credential-path rejection. Source says "local" so a dialog or note never claims JEV/LLM decided it.

Jump to

Keyboard shortcuts

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