agenthook

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package agenthook decides whether a coding agent's search call should be answered by the graph instead of by reading text.

The decision is a gate in front of a tool call, not a policy: it runs before `grep`, refuses the calls the graph answers better, and names the call that answers them. Shell hooks in Claude Code and Codex, plus generated modules in OpenCode and Oh My Pi, hand the gate this payload on stdin and read its verdict on stdout. The modules speak for clients that cannot spawn a shell hook directly, which is why the dialect is a field rather than separate parsers.

Every failure here is an allow. A gate that cannot read its input, cannot find the graph or cannot reach the daemon has learned nothing about the call, and a hook that blocks on its own bugs would make the agent unusable in a repository that never asked for it.

Index

Constants

View Source
const DisableVariable = "KIVGRAPH_DISABLE_HOOK"

DisableVariable turns the gate off for one call.

It is read in two places and both are needed. The gate itself reads it from its own environment, which is how a user turns the gate off for a session; and stripAssignments reads it off the front of the very command being gated, which is how the refusal's own advice works -- an agent that prefixes the retry has changed nothing about its environment, only about that one line.

Variables

View Source
var Allow = Decision{}

Allow is the gate having no opinion.

Functions

func ExtensionsFor

func ExtensionsFor(languages []string) []string

ExtensionsFor is every extension the named languages are written in.

It is a thin name over config.SourceExtensions rather than a table of its own. This package used to carry the second copy of that mapping and the watcher carried the first, and the two disagreed: the watcher knew Go, TypeScript and Rust, so a Python or Dart repository's sources were invisible to it. One table answers both now, beside the SupportedLanguages that decides what a configuration may declare in the first place.

func IndexedExtensions

func IndexedExtensions(extensions []string) func(string) bool

IndexedExtensions builds an Indexed function from the languages a configuration names.

It answers on the extension because that is all a glob carries: `**/*.go` has no path to resolve and no file to stat. A glob that names no extension -- `**/*` -- is not a question about code and is left alone.

Types

type Briefing added in v0.9.3

type Briefing struct {
	// Directory holds one marker file per session. Empty disables the
	// briefing entirely.
	Directory string
}

Briefing remembers which sessions have already been briefed.

The zero value never briefs, which is the right answer when there is nowhere to write: a gate that cannot remember would otherwise attach the same paragraph to every call of the session, and an unsolicited paragraph on every tool result is worse than no briefing at all.

func (Briefing) First added in v0.9.3

func (briefing Briefing) First(sessionID string) bool

First reports whether this call is the first of its session, and records that it no longer is.

The race is settled by the filesystem rather than by a lock: two concurrent first calls both try to create the marker with O_EXCL and exactly one succeeds, so a session cannot be briefed twice even when its agent fires two tool calls at once.

Every failure answers false. This runs in front of a tool call that is going to proceed either way, so there is no failure here worth telling anyone about -- the cost of a missed briefing is that the session reads the skill the way it did before this existed. The id is tested for blankness on a trimmed copy and then used as it arrived. It is opaque and belongs to the host, so normalising it would merge two sessions a host considers distinct -- and the second of them would lose the briefing that is this function's whole purpose.

type Decision

type Decision struct {
	// Deny is set when the graph answers this question better.
	Deny bool
	// Reason is what the agent is told, and what the user reads. It names
	// the call to make instead, because a refusal without one is an
	// obstacle rather than a redirect.
	Reason string
	// Context is guidance attached to a call that is going ahead anyway.
	// It is only ever read when Deny is false: a refusal already carries
	// its own text, and saying two things about one call is how an agent
	// ends up acting on the wrong half.
	Context string
}

Decision is what the gate tells the agent.

There are three of them, and exactly one grants anything. A gate that has nothing to say writes nothing, and that is not the same as approving: in Claude Code an explicit `allow` **skips the permission prompt**, so a gate that answered `allow` to every call it had no opinion about would silently auto-approve every shell command in the session, including the ones the user configured a prompt for. Saying nothing leaves the agent's own permission flow exactly where it found it, which is the only safe meaning of "no opinion".

The third is an advisory, and it is bound by that same rule rather than an exception to it: it attaches context and answers the permission question with silence. That is why it is a separate field and not a `Reason` on an allow -- the tempting shape, `permissionDecision: "allow"` with the text in `permissionDecisionReason`, would deliver the same words and strip the user's permission prompt from every call it rode along with.

func (Decision) Write

func (decision Decision) Write(stdout io.Writer) error

Write emits a decision in the JSON form consumed by Claude Code and the generated adapters.

An allow writes nothing at all. See Decision for why that is deliberate.

type Dialect

type Dialect string

Dialect is the agent whose tool vocabulary a payload speaks.

It exists because the supported agents spell the same four tools differently -- Claude Code's `Task` is OpenCode's `task`, and Codex names its editor `apply_patch` where the others say `Edit` -- and a classifier that matched on the spelling of one of them would silently pass every call from the other two. The empty dialect means "infer from the spelling", which is what a payload from an agent we have not named yet gets.

const (
	// DialectClaudeCode is Claude Code, which reads `hookSpecificOutput`.
	DialectClaudeCode Dialect = "claude-code"
	// DialectCodex is the Codex CLI. Its input extends Claude Code's with a
	// turn_id, and a refusal uses exit 2 plus stderr instead of a JSON verdict.
	DialectCodex Dialect = "codex"
	// DialectOpenCode is OpenCode, reached through a generated plugin because
	// its `tool.execute.before` returns `Promise<void>` and blocks by
	// throwing. The plugin translates a deny into that throw.
	DialectOpenCode Dialect = "opencode"
)

type Facts

type Facts struct {
	// Declarations is how many things carry this name.
	Declarations int
	// Repositories is how many repositories they live in.
	Repositories int
	// References is how many places use them.
	References int
	// Sample are a few rows, already formatted, for the refusal to quote.
	// A refusal that names real rows is a redirect; one that recites a rule
	// is an obstacle.
	Sample []string
}

Facts are what the graph knows about a name, at the granularity the gate needs to choose between itself and `grep`.

It is deliberately three numbers and a few rows rather than a result set. The gate is not answering the caller's question -- the tool it names will do that -- it is only deciding who answers it better, and that decision turns on how ambiguous and how widespread the name is.

func (Facts) Known

func (facts Facts) Known() bool

Known reports whether the graph has anything at all under this name.

type Gate

type Gate struct {
	// Graph answers the two questions the gate asks. A nil Graph -- no
	// daemon, or one that could not be reached -- allows everything that
	// needs an answer from it.
	Graph Graph
	// Indexed reports whether a path or glob names a file the graph covers.
	// A nil Indexed treats nothing as indexed.
	Indexed func(name string) bool
	// Briefing remembers which sessions have already been briefed. Its zero
	// value never briefs, which is what a gate with nowhere to write should
	// do.
	Briefing Briefing
	// SessionID is the conversation this call belongs to, and is empty for
	// a host that does not send one.
	SessionID string
	// Repository narrows an intent question to the repository holding the
	// caller's working directory. A symbol name remains workspace-wide so
	// homonyms across repositories are still visible.
	Repository string
}

Gate decides whether a search should be refused in favour of the graph.

func (Gate) Decide

func (gate Gate) Decide(ctx context.Context, question Question) Decision

Decide answers a classified call.

Every branch that cannot establish a positive reason to refuse returns Allow. That is not caution for its own sake: the gate's whole claim is that the tool it names answers better, and it has no standing to refuse a call it knows nothing about.

type Graph

type Graph interface {
	// Symbol answers what is declared under a name. A name the graph does
	// not know is the zero Facts and a nil error.
	Symbol(ctx context.Context, name string) (Facts, error)
	// Intent answers what a loose description most likely names.
	Intent(ctx context.Context, intent, repository string) (Facts, error)
	// Declares answers whether a repository holds a declaration of a name.
	Declares(ctx context.Context, name, repository string) (bool, error)
}

Graph is the part of the daemon the gate asks.

It is an interface because the gate's decisions are worth testing against facts a test states outright, and because every implementation of it has to be allowed to fail: a daemon that is not running is the common case, not an error, and the gate's answer to it is to stand aside.

func Dial

func Dial(ctx context.Context, stateDirectory string) (Graph, func(), error)

Dial connects the gate to the daemon a state directory publishes.

It never starts one. A hook runs on the user's keystroke, before a tool they asked for, and a gate that spawned an indexer there would turn a `grep` into a minute of waiting. No endpoint, a stale endpoint or a refused connection are all the same answer -- the gate has no graph and will stand aside -- so they are one error rather than a taxonomy no caller could act on.

type Kind

type Kind uint8

Kind is the shape of the question a call asks, and therefore which tool answers it.

The shapes are separate because the answers are. A bare identifier is a question about a symbol and `find_references` answers it; a sentence is a question about intent and only `find_by_intent` answers it; and routing either one to the other tool would give a worse answer than the `grep` the gate refused. `KindNone` is every call that is not a search, which is most of them, and it never reaches the graph.

const (
	// KindNone is a call the gate has no opinion about.
	KindNone Kind = iota
	// KindSymbol is a bare identifier: something has that name.
	KindSymbol
	// KindIntent is prose, several words, or a pattern too loose to be a
	// name: the caller does not know what the thing is called.
	KindIntent
	// KindFiles is a question about which files exist, not what is in them.
	KindFiles
	// KindResearchAgent is a subagent asked to go read the codebase.
	KindResearchAgent
	// KindGraphTool is a call to one of Kivgraph's own MCP tools. It is the
	// one kind that is not a question the gate might answer better: it is
	// already the answer, and the gate recognises it only to brief the
	// session that is about to start using it.
	KindGraphTool
)

type Payload

type Payload struct {
	HookEventName string          `json:"hook_event_name"`
	CWD           string          `json:"cwd"`
	ToolName      string          `json:"tool_name"`
	ToolInput     json.RawMessage `json:"tool_input"`
	// SessionID is the conversation this call belongs to, and it is the
	// only field the gate reads that says anything about *when* rather than
	// *what*. It exists for the briefing, which happens once per session
	// and cannot be once per anything without it. Claude Code and Codex
	// send it; generated modules have nothing to put here, and an empty
	// one means the briefing does not fire at all -- see Briefing.
	SessionID string `json:"session_id"`
	// TurnID identifies a Codex turn. Claude Code and the generated adapters
	// do not send it, so it also selects Codex's distinct refusal protocol.
	TurnID string `json:"turn_id"`
}

Payload is the call an agent is about to make.

Most field names are shared by Claude Code and Codex; Codex adds turn_id. The generated OpenCode and Oh My Pi modules build the common shape rather than forwarding their own, so one `hook run` still serves every path.

func (Payload) Dialect added in v0.9.6

func (payload Payload) Dialect() Dialect

Dialect reports the host whose wire contract is positively identified. The empty result deliberately keeps unknown hosts on the JSON protocol used by Claude Code and the generated adapters.

type Question

type Question struct {
	Kind Kind
	// Pattern is the text the caller searched for, with any quoting removed.
	Pattern string
	// Paths are the places it searched, as written. Empty means the working
	// directory, which is what every one of these tools defaults to.
	Paths []string
	// Tool is the spelling the agent used, kept for the message: telling a
	// caller its `rg` was refused reads better than telling it its `Bash` was.
	Tool string
	// Native says the call came from a tool of the agent that takes no command
	// line -- Grep, Glob, a subagent dispatch -- as opposed to one typed in a
	// shell. It decides how a refusal says to insist: a variable before the
	// command has no command to go before.
	Native bool
}

Question is what a call was really asking, once the tool and its flags are stripped away.

func Classify

func Classify(payload Payload) Question

Classify answers what a payload asks, without touching the filesystem or the graph.

It is deliberately total and deliberately shy: anything it does not positively recognise as a search is `KindNone`. The asymmetry is the whole design -- a missed `grep` costs the tokens the gate exists to save, and a wrongly refused `git log` costs the user their trust in it.

Jump to

Keyboard shortcuts

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