judge

package
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 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 ApplyReAdmittedPath added in v1.3.1

func ApplyReAdmittedPath(ans ApprovalAnswer, lang string) (how string, ok bool)

ApplyReAdmittedPath registers what a re-admission answer granted and returns the phrase a note should carry. Read answers are registered here — the gate owns the read-root registry — while a write answer is registered by the caller through GrantWritable, the one callback that writes both the table row and the sandbox's writable root; a write grant carries read, so either shape leaves the blocked path reachable inside the sandbox. ok=false means the answer granted nothing: a denial, a write whose registration the caller refused, or a read the registry would not take.

It is the one place that turns one of these answers into a table row, so the two triggers that ask the question — a refused escape, and a command the sandbox just denied — cannot drift apart in what a "yes" means.

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 BoundaryGate added in v1.3.0

func BoundaryGate(opts BoundaryOpts) agentcore.BeforeToolCallFunc

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

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

EscalationRequested is a request fact for the fast decision-model reviewer. It does not authorize the escape; only the final Verdict.Direct does.

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 NetworkFollow added in v1.3.5

func NetworkFollow() bool

NetworkFollow reports whether an auto-mode Allow carries the network bit.

func NetworkKey added in v1.3.3

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

NetworkKey names the standing scope a remembered network answer would cover. It is deliberately narrower than "the call": a host for webfetch, the tool for websearch (whose backend host depends on credentials), and one literal program/subcommand for bash. Anything the parser cannot pin down returns ok=false, and the answer can only be for this call.

func NetworkRemembered added in v1.3.3

func NetworkRemembered(tool string, args json.RawMessage) (grants.NetworkVerdict, bool)

NetworkRemembered returns the standing answer for this call, if one exists.

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 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, Contain 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 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 SetNetworkFollow added in v1.3.5

func SetNetworkFollow(on bool)

SetNetworkFollow turns the policy on or off.

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 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. They are meaningful only
	// for ApprovalConsent; the legacy fields below belong to the older gates.
	Scope Scope
	Needs []Need
	Exec  ExecMode
	// Unconfined, with Approve, means "run this one call outside the sandbox" —
	// the answer to a denial question that offered it. It is a one-call
	// decision: nothing is registered and nothing is remembered.
	Unconfined bool
	// Network, with Approve, grants this call outbound access. A combined
	// prompt sets it explicitly; a network-only ApprovalNetwork answer keeps
	// deciding it by Kind so older drivers are unaffected.
	Network bool
	// NetworkSession and NetworkRemember carry the lifetime the person chose
	// for a network answer. Both false with Network true means this call only.
	NetworkSession  bool
	NetworkRemember bool
	// 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
	// Contained, when set with Approve, answers "keep it in the sandbox" — the
	// escalation dialog's default row. The gate re-contains the call: a request
	// to leave the sandbox is not an entitlement to, and the reviewer had
	// already graded the call runnable under containment.
	Contained 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
	// WriteRoot, when set together with Approve, means the user granted this
	// directory for WRITING: the write side's twin of ReadRoot, answered by the
	// boundary gate's question about a patch that reaches outside the workspace.
	// The gate registers it through BoundaryOpts.GrantWritable, the same callback
	// the escalation dialog uses, so the grant lands in the sandbox's writable
	// roots and in the authorization table at once.
	WriteRoot 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.

func AskReAdmit added in v1.3.3

func AskReAdmit(ctx context.Context, in *bufio.Reader, out io.Writer, mu *sync.Mutex, path, summary, lang, networkKey string) ApprovalAnswer

AskReAdmit is the stdin shape of the sandbox re-admission question. It is the same three answers the TUI's re-admit dialog offers, in one block: allow the path for this session (contained), remember it, or skip. It exists so a REPL user can unblock a command the sandbox just refused instead of being told to run golder in another front-end.

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. The old per-capability kinds below remain only
	// for the legacy gates and the trust bootstrap path.
	ApprovalConsent ApprovalKind = "consent"
	// 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
	// Contain. The two sides disagree, and the mode decides who settles it:
	// auto re-contains the call (the reviewer's answer stands, announced either
	// way), ask puts the escape to the person with containment as the default,
	// headless re-contains or fails closed.
	ApprovalEscalation ApprovalKind = "escalation"
	// ApprovalReAdmit asks whether to re-admit a path the sandbox refused, for
	// reading or for reading and writing, and it has two triggers: an escape
	// request the reviewer declined, and a command the sandbox just denied. In
	// both cases dropping the sandbox for the whole call is rarely what the call
	// needs, and one path is usually all it does need. The answer is recorded in
	// the same table the gates and the sandbox read — the read rows through the
	// gate, the write row through the write dialog's own callback — and the call
	// then runs contained with that path reachable. A "no" leaves the caller's
	// default untouched (contain the call when containment is possible, refuse it
	// otherwise) and records no denial, because nothing was denied. Asked at most
	// once per path per run. Only drivers with a dialog ask it; without one the
	// refusal message carries the same fix.
	ApprovalReAdmit ApprovalKind = "re-admit"
	// ApprovalNetwork asks for one call's network capability when the routine
	// grader could not authorize it. An approval keeps the filesystem sandbox;
	// this is NOT permission to run the call outside containment.
	ApprovalNetwork ApprovalKind = "network"
	// ApprovalBoundary: a tool was pointed outside the workspace — a read tool
	// (read, view_image, grep, find, ls) or a bash command's file operands on the
	// read side, apply_patch on the write side. The workspace is the directory
	// the user opened, so this asks for consent rather than a risk verdict; the
	// answers are "just this one" (ReadGrant / WriteGrant) and "this directory
	// for the session" (ReadRoot / WriteRoot, see BoundaryWrite). It is the one
	// question no approval mode waives, including full-access.
	ApprovalBoundary ApprovalKind = "boundary"
)

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
	// CanContain reports that the call can be contained even when it also asks
	// for an escape, so "stay in the sandbox" remains a meaningful answer.
	CanContain bool
	// UnconfineOffer marks a re-admission question that may also be answered
	// with "run this one call outside the sandbox". It is set only by the
	// sandbox-denial asker, where the command already ran (and was already
	// reviewed) and the refusal is about a path rather than about the call; the
	// refused-escape dialog has its own escape row and does not set it.
	UnconfineOffer bool
	// NetworkRequest marks a prompt whose network side is also being decided.
	// It is set only when the same call asks for a path decision and a network
	// grant, so the dialog can show both groups instead of interrupting twice.
	NetworkRequest bool
	// NetworkKey names the host/command a remembered answer would cover. Empty
	// means the decision is for this call only (an unsafe or unparseable key).
	NetworkKey string
	// NetworkRememberable reports that NetworkKey may be written to the managed
	// store; false still offers the one-call and session rows.
	NetworkRememberable bool
	// 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
	// BoundaryDir is the directory a boundary request may be granted for the
	// session, or "" when no directory is offered (the answer is then "this
	// read" or "no"). Set only for ApprovalBoundary.
	BoundaryDir string
	// BoundaryWrite reports that the boundary request is about WRITING rather
	// than reading, so the dialog offers the write rows ("allow this write
	// once", "allow writing <dir>") and the answer records a write grant. Set
	// only for ApprovalBoundary.
	BoundaryWrite bool
	// ReadRoot is the path a re-admission question can bring back inside the
	// sandbox, for reading or for reading and writing (see NeedsWrite). Set only
	// for ApprovalReAdmit; empty means there is no path to offer and the caller
	// keeps its refusal.
	ReadRoot string
	// NeedsWrite reports that the blocked path is needed for writing, so the
	// dialog says so in its title and leads with the row that grants both (a
	// write grant carries read). Set only for ApprovalReAdmit, from
	// PathWriteNeed: false means the question is presented as a read.
	NeedsWrite bool
	// 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
	// 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 BoundaryOpts added in v1.3.0

type BoundaryOpts 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 because the managed file is opened
	// by the cli assembly, which owns its path and its on-disk shape; a driver
	// without one simply cannot offer the remembered answer, and the prompt says
	// so (the session grant still lands in the table the gate writes itself).
	Persist func(dir string) (made bool, why string)
	// GrantWritable, when set, registers a directory as writable — for the
	// session, and across sessions when persist is true — and reports what
	// happened. It is the same callback the escalation dialog's writable answers
	// use, wired once at the assembly point, and sharing it is the point: it
	// registers the sandbox's writable root AND the authorization table's row,
	// so an approval the next patch honours is also one the next command sees —
	// one answer, one meaning. Nil means the remembered and directory rungs are
	// not offered, and the one-write answer is all the prompt can show.
	GrantWritable func(root string, persist bool) (made bool, why string)
	// WritableAt reports whether a path is already writable for this session
	// (the sandbox's writable-root registry, which config.toml and
	// permissions.toml seed). It is injected for the same reason Persist is:
	// that registry lives above this package. Nil means only the authorization
	// table is consulted, which is the stricter reading — a seeded root then
	// asks once and is recorded in the table by the answer.
	WritableAt func(path string) bool
	// 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()
	// AskCoord carries this prompt's network answer to the permission gate when
	// the same call needs both a path decision and a network grant. A nil
	// coordinator keeps the two gates asking separately, which is the old
	// behavior and the safe fallback for drivers that do not wire it.
	AskCoord *AskCoord
}

BoundaryOpts configures BoundaryGate. 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 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
)

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 legacy driver callback while the dialog is migrated. It exists only at the boundary between drivers and the new gate.

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
	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 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 Contain 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
	// RequireSandbox makes an authorized bash call default to OS isolation.
	// Only an explicit one-call Direct decision can override this requirement.
	RequireSandbox bool
	// Enforce is the sandbox's enforce mode: every bash call runs contained, so
	// the bare envelope (and the network fold that rides it) must not apply.
	// RequireSandbox is also true in auto; that only says isolation is the
	// default, not that the envelope cannot choose the host.
	Enforce 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 Contain
	// 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 because the sandbox's writable registry and the remembered
	// row's spelling live in the cli assembly, not here. 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()
	// AskCoord is the boundary gate's half of a combined prompt: it carries the
	// path prompt's network answer so this gate does not ask the same call's
	// network question a second time. Nil means no combined prompt is in use.
	AskCoord *AskCoord
	// SkipReAdmit suppresses the auto-mode path re-admission offer for this
	// call. The sandbox-denial asker sets it when it re-enters the gate for an
	// escape request: the denial dialog already asked about the path, and the
	// second question must be about the escape, not a repeat of the first.
	SkipReAdmit bool
}

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

func ConsentGateOptsToGate added in v1.4.6

func ConsentGateOptsToGate(o ConsentOpts) GateOpts

ConsentGateOptsToGate adapts the classifier inputs the shared helpers expect. The legacy GateOpts is still the home of the classifier; keeping the adapter local avoids duplicating classifyForGate's chain handling.

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
	// Direct is an explicit decision to waive the file sandbox for THIS call,
	// independent of the four risk tiers. A bare Allow is not a direct grant.
	Direct 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