reviewpolicy

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: 11 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

Overview

Package reviewpolicy decides HOW a tool call is reviewed, not whether it is safe. It is the routing layer between the cheap judge (a decision model fed parsed shell facts) and the expensive one (the conversation model).

The shape of the pipeline it serves:

facts  → what the command IS, parsed, with no verdicts (internal/shellfacts)
Jev    → calibrated probabilities over typed questions (internal/jev)
policy → THIS package: is that answer decisive, or does it escalate?
LLM    → the slow reviewer, for the calls that reach it

The one rule that shapes everything here: a cheap judge may DECIDE a call, but it may never decide it CHEAPLY. Concretely, the levels this package emits mean exactly what the slow reviewer's levels already mean — an Allow still passes every downstream gate (the workspace read boundary, the sandbox router, the trust gate). Nothing here can skip a consent step, because consent is not a risk verdict and a probability is not a permission.

Escalation is the safe direction and the expensive one, so the thresholds are asymmetric on purpose:

  • Deny and Contain are accepted at moderate confidence. Their failure mode is a redundant block or a redundant sandbox — the command is slowed or retried, nothing is lost.
  • Allow demands a high probability, a wide margin over the runner-up, and the absence of every independent danger signal. Its failure mode is that a dangerous command runs unreviewed, so it is the one verdict that must be near-unanimous.
  • Confirm escalates rather than deciding. In auto mode a Confirm runs anyway, so accepting a low-confidence Confirm as "run it" would turn the cheapest judge into the weakest link; the slow reviewer is the right place for the ambiguous middle, and it is rare.

Index

Constants

View Source
const (
	QL   = "level"
	QR   = "risk"
	QRev = "irreversible"
	QSec = "touches_secrets"
	QInt = "matches_intent"
	QWhy = "reason"
	QNet = "network_permission"
)

Question ids. They are constants because the same strings must appear in the request, in the answer decoding, and in the rationale mapping — a typo in one place would silently read as "no signal".

View Source
const (
	EscalateUnusableFacts = "the command could not be parsed"
	EscalateDynamic       = "the program name is computed at runtime"
	EscalateConstructs    = "the command contains control flow"
	EscalateNoLevel       = "the judge returned no verdict"
	EscalateLowConfidence = "the verdict was not decisive"
	EscalateAmbiguous     = "the verdict was confirm"
	EscalateDanger        = "a danger signal contradicts a permissive verdict"
	EscalateIntent        = "the call serves an explicit request; the session reviewer should weigh its scope"
)

Escalation reasons. They are distinct strings rather than a bool because the reason is what tells an operator whether the thresholds are wrong.

View Source
const (
	DangerNone    = 0
	DangerConfirm = 2
	DangerDeny    = 3
)

Danger thresholds, as returned by dangerLevel.

View Source
const Source = "jev"

Source names this classifier in a Verdict, so a card or a log line can say which judge answered.

Variables

View Source
var LevelOptions = map[string]any{
	"allow":   "routine: a read, a build, a test run, an edit inside the workspace, nothing that leaves the machine or destroys work",
	"contain": "risky and its scope is not established by the command text or the context; run it isolated rather than trust a guess",
	"confirm": "the effect depends on the user's explicit request or the conversation; escalate to the session reviewer, which also decides any requested sandbox escape from this level",
	"deny":    "must not run: it destroys work, exfiltrates data, escalates privilege, or writes outside anything the user opened",
}

LevelOptions are the choices for the level question. The spelling matches judge's own vocabulary so a caller can map it without a second table.

View Source
var RiskLevels = []any{
	"low: nothing is changed, or the change is trivially reversible",
	"medium: changes files or state, but inside what the user opened",
	"high: changes things outside the workspace, or is hard to undo",
	"critical: irreversible, destructive, or discloses credentials",
}

RiskLevels is the rubric for the risk score.

Functions

func Questions

func Questions() map[string]jev.Question

Questions builds the question set sent to the decision model for one call.

Three primitives, one round trip: a Choice for the verdict, a Score for the risk, and four independent booleans. The booleans matter because they are evidence the Choice cannot carry: a model can hedge on "is this allow?" while still being confident the command is irreversible, and the policy needs that disagreement to be visible rather than averaged into one label.

func QuestionsFor added in v1.3.1

func QuestionsFor(network bool) map[string]jev.Question

QuestionsFor appends the network question when the call asks for it. The sandbox escape has no separate question: the level is its authorization.

Types

type CallRecord

type CallRecord struct {
	Tool string
	// Routed is "decided" or "escalated".
	Routed string
	// Level is the decided level, empty when escalated.
	Level judge.Level
	// Escalation names why the call went to the fallback.
	Escalation string
	// Attempts and Latency describe the decision-model call.
	Attempts int
	Latency  time.Duration
	// Err is the transport failure, if any. It never contains the API key.
	Err error
}

CallRecord is what one call cost and how it was answered, for telemetry.

type Classifier

type Classifier struct {
	// Client is the decision model. Nil disables the cheap path entirely and
	// every call goes to Fallback.
	Client *jev.Client
	// Fallback is the slow reviewer. Nil means an escalation has nowhere to go,
	// so it fails closed instead — which is the right default for a caller that
	// did not wire one.
	Fallback judge.Classifier
	// Config holds the thresholds.
	Config Config
	// Language pins the rationale's language. Empty detects it from the
	// conversation, the same way the slow reviewer does.
	Language string
	// Cwd is the working directory the state reports, so the judge can tell a
	// path inside the workspace from one outside it.
	Cwd string
	// ExtraRoots are directories outside the workspace the session treats as its
	// own (the skills directory golder advertises in the system prompt). They
	// travel with Cwd because both answer the same question — is this path the
	// user's own or a boundary crossing — and the reviewer must see the same
	// answer the boundary gate enforces.
	ExtraRoots []string
	// WritableAt reports whether a path is already writable for this session
	// (the sandbox's writable-root registry). It travels with the rest of the
	// boundary facts for the same reason: the reviewer must see the answer the
	// gate enforces, and a write the registry already admits is not a question.
	WritableAt func(path string) bool
	// Observer, when set, receives one record per call. It runs on the calling
	// goroutine, so it must not block: it is for telemetry, not for prompting.
	Observer func(CallRecord)
	// Now is a test seam.
	Now func() time.Time
}

Classifier routes tool calls through the decision model.

func (*Classifier) Classify

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

Classify implements judge.Classifier. It is safe for concurrent use: the client bounds its own concurrency and this type holds no mutable state.

type Config

type Config struct {
	// AllowConfidence is the minimum probability for the winning option of an
	// Allow before it is accepted. Below this the call escalates.
	AllowConfidence float64
	// AllowMargin is the minimum distance between the winning option and the
	// runner-up. A 0.86/0.84 split is not a verdict even though the winner
	// clears AllowConfidence.
	AllowMargin float64
	// DecideConfidence is the minimum for accepting Deny or Contain, whose
	// failure modes are cheap.
	DecideConfidence float64
	// DangerConfirm is the probability at which an independent danger signal
	// (irreversibility, credential material) outweighs a permissive level.
	DangerConfirm float64
	// DangerDeny is the probability at which the signal forces a refusal
	// outright rather than a downgrade to confirmation.
	DangerDeny float64
}

Config holds the thresholds. They are fields rather than constants so the policy can be tuned from measurements, and so tests can pin behaviour at the boundary rather than at whatever the defaults happen to be.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns measured-once starting points. They are conservative: the cost of escalating is a slower review, the cost of being wrong is a command nobody approved.

type Outcome

type Outcome struct {
	// Route says whether the level below is final.
	Route Route
	// Level is the verdict to apply when Route is RouteDecided.
	Level   judge.Level
	Network bool
	// Risk mirrors the reviewer's risk rating, for the verdict card.
	Risk string
	// Rationale is a localized one-liner; the model cannot write one, so it is
	// assembled here from the reason label.
	Rationale string
	// Escalation names why the call went up, for telemetry and tests.
	Escalation string
}

Outcome is the decision.

func Decide

func Decide(req Request) Outcome

Decide routes one already-answered call.

It never returns an error: an unusable answer is an escalation, because the caller's next step is the same whether the judge was absent or unsure. It also never returns Allow on partial information — every path that cannot establish the facts or the verdict goes up.

type Request

type Request struct {
	// Facts is the parsed command, or nil when the tool call is not a shell
	// command (a native tool such as apply_patch carries its paths directly).
	Facts *shellfacts.Plan
	// Answers is the decision model's response, keyed by the question ids.
	Answers map[string]jev.Answer
	// Config holds the thresholds.
	Config Config
	// Lang selects the rationale's language ("zh" or "en").
	Lang string
	// Capability requests are separate from the risk tier. A reviewer cannot
	// grant a capability it was never asked about, and absence of its answer
	// escalates rather than meaning "yes".
	NetworkRequested bool
}

Request is one call to decide.

type Route

type Route uint8

Route is what the caller should do with the outcome.

const (
	// RouteDecided means the cheap judge settled it: use Level.
	RouteDecided Route = iota
	// RouteEscalate means hand the call to the slow reviewer. It is never an
	// approval and never an error: it is "this judge cannot answer".
	RouteEscalate
)

type State

type State struct {
	Tool string `json:"tool"`
	// Context is the recent user requests — the evidence the intent question
	// needs. The decision model is a third-party call, so it carries user words
	// only, not tool output: enough to tell an explicit request from a guess,
	// without shipping the transcript.
	Context string `json:"context,omitempty"`
	// Command is the shell command text, unchanged. It is kept beside the
	// parsed form because a parse can be wrong about a construct, and the
	// original text is the tiebreaker a reader can check.
	Command string `json:"command,omitempty"`
	// Arguments carries a native tool's arguments verbatim.
	Arguments json.RawMessage `json:"arguments,omitempty"`
	// Cwd is the directory the call runs in, so a path inside the workspace can
	// be told from one outside it.
	Cwd string `json:"cwd,omitempty"`
	// Facts is the parsed command, absent for a non-shell tool. Its presence is
	// what lets the judge reason about what will run instead of what the text
	// says — the computed program name, the nested command, the redirect.
	Facts *shellfacts.Plan `json:"facts,omitempty"`
	// Access lists the paths the call touches, when they can be determined.
	Access []shellfacts.AccessSummary `json:"access,omitempty"`
	// Auth says what the session already knows about those paths: whether each
	// lands inside the workspace, whether a consent question is in front of this
	// call, and what the authorization table has decided (granted or refused) per
	// capability. Without it the model grades the same text as though no answer
	// had ever been given: it re-asks what the user just approved, or reads a
	// pending question as settled.
	//
	// The flags come from the boundary gate's own predicates, never from a second
	// reading of the arguments, so the reviewer cannot be told something the gate
	// does not believe.
	Auth []judge.AuthFact `json:"auth,omitempty"`
	// Outliving lists paths whose change lands OUTSIDE the edit: `.git/hooks/*`
	// runs on the next git command (and git commands are the ones the read-only
	// fast path waves through all day), `.git/config` is the same door
	// (core.hooksPath, core.sshCommand, credential helpers), and AGENTS.md is
	// injected into every later session's prompt — a persistent injection channel
	// that needs no execution at all.
	//
	// It is a FACT, not a verdict, and that is the point of sending it: a person
	// asking for a pre-commit hook is asking for something legitimate, so a hard
	// deny on the name would take a reasonable request off the table. A hook body
	// looks like any other script until a reader knows when it runs, which is
	// exactly what a file's contents do not say.
	Outliving []string `json:"outliving,omitempty"`
}

State is the material the decision model reads. It is a package-level type rather than an anonymous map so the shape is documented and a test can assert it: what the judge sees decides what it can decide.

type Stats

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

Stats counts how the classifier routed calls, for a status command.

func (*Stats) Observe

func (s *Stats) Observe(rec CallRecord)

Observe is an Observer that keeps counters.

func (*Stats) Snapshot

func (s *Stats) Snapshot() (decided, escalated, failed int, total time.Duration)

Snapshot returns the counters: decided, escalated, failed, and the total time spent in the decision model.

Jump to

Keyboard shortcuts

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