# API Reference


## Registration


Declaring and registering hooks.


[hook()](registration.md#captain_hook.hook)  

[on()](registration.md#captain_hook.on)  


## Primitives


One-line hooks for the common cases.


[gate()](primitives.md#captain_hook.gate)  
Register a blocking gate -- `nudge(message, block=True, ...)` with an explicit signature.

[nudge()](primitives.md#captain_hook.nudge)  
Register a nudge that warns (or blocks) when conditions or signals match.

[lint()](primitives.md#captain_hook.lint)  
Register a lint check that runs on source-file edits and writes.

[diff_lint()](primitives.md#captain_hook.diff_lint)  
Register a diff lint: flag only constructs the edit introduces.

[block_command()](primitives.md#captain_hook.block_command)  
Register a declarative hook that blocks a Bash command matching a pattern.

[warn_command()](primitives.md#captain_hook.warn_command)  
Register a declarative hook that warns on a Bash command matching a pattern.

[rewrite_command()](primitives.md#captain_hook.rewrite_command)  
Register a `PreToolUse` hook that rewrites a matching Bash command.

[rewrite_code()](primitives.md#captain_hook.rewrite_code)  
Register a `PreToolUse` hook that structurally rewrites edited code before it is written.

[llm_gate()](primitives.md#captain_hook.llm_gate)  
Register an LLM-powered blocking gate.

[llm_nudge()](primitives.md#captain_hook.llm_nudge)  
Register an LLM-powered advisory nudge.

[prompt_check()](primitives.md#captain_hook.prompt_check)  
Run an LLM check with a formatted prompt and return block/warn/None.

[approve()](primitives.md#captain_hook.approve)  
Register a hook that answers matching tool permissions with *allow*.

[deny()](primitives.md#captain_hook.deny)  
Register a hook that answers matching tool permissions with *deny*.

[llm_approve()](primitives.md#captain_hook.llm_approve)  
Register an LLM safety judge that auto-approves permission dialogs it deems safe.

[style.styleguide()](primitives.md#captain_hook.style.styleguide)  
Register one change-scoped hook applying the given style rules to Python edits and writes.

[style.matchers](primitives.md#captain_hook.style.matchers)  
Composable AST matchers for style rules -- import this module as `M`.

[style.StyleRule](primitives.md#captain_hook.style.StyleRule)  
Base class for a single-tree AST style rule applied to Python edits and writes.

[style.StyleDiffRule](primitives.md#captain_hook.style.StyleDiffRule)  
Base class for a diff rule: flags constructs newly introduced by the change.

[style.ast_grep_rule()](primitives.md#captain_hook.style.ast_grep_rule)  
Build a \[`StyleRule`\]\[captain_hook.style.StyleRule\] from an inline ast-grep pattern.

[style.ast_grep_diff_rule()](primitives.md#captain_hook.style.ast_grep_diff_rule)  
Like \[`ast_grep_rule`\]\[captain_hook.style.ast_grep_rule\], but flags only matches the edit newly introduces.

[style.AstGrepStyleRule](primitives.md#captain_hook.style.AstGrepStyleRule)  
A \[`StyleRule`\]\[captain_hook.style.StyleRule\] matched by an ast-grep pattern over source text.

[style.AstGrepStyleDiffRule](primitives.md#captain_hook.style.AstGrepStyleDiffRule)  
An \[`AstGrepStyleRule`\]\[captain_hook.style.AstGrepStyleRule\] that flags only constructs the edit introduces.

[style.Violation](primitives.md#captain_hook.style.Violation)  
A single style violation, located by line so the runner can scope it to the edit.

[style.Change](primitives.md#captain_hook.style.Change)  
The pre- and post-edit state of a file, passed to every style rule's `check`.

[GateVerdict](primitives.md#captain_hook.GateVerdict)  
LLM response model for `llm_gate`. The LLM sets `block=True` to deny.

[NudgeVerdict](primitives.md#captain_hook.NudgeVerdict)  
LLM response model for `llm_nudge`. The LLM sets `fire=True` to trigger the nudge.

[PromptCheckVerdict](primitives.md#captain_hook.PromptCheckVerdict)  
LLM response model for `prompt_check`. Action is `"ok"`, `"warning"`, or `"block"`.

[SafetyVerdict](primitives.md#captain_hook.SafetyVerdict)  
LLM response model for `llm_approve`. The LLM sets `safe=True` to auto-approve.


## Conditions


Typed filters that decide when hooks fire.


[Tool](conditions.md#captain_hook.Tool)  
Condition matching the current event's tool name against one or more names.

[FilePath](conditions.md#captain_hook.FilePath)  
Condition matching the current event's file path against glob patterns.

[types.Command](conditions.md#captain_hook.types.Command)  
Condition matching the current event's bash command against a regex.

[Content](conditions.md#captain_hook.Content)  
Condition matching the current event's file content against a regex.

[Pattern](conditions.md#captain_hook.Pattern)  
Condition matching the edit's new content against an ast-grep **structural** pattern.

[TouchedFile](conditions.md#captain_hook.TouchedFile)  
Transcript-history condition: true when an Edit/Write targeted a file matching the glob.

[TestFile](conditions.md#captain_hook.TestFile)  
Condition that matches when the current event targets a test file.

[ReadFile](conditions.md#captain_hook.ReadFile)  
Transcript-history condition: true when a Read tool use targeted a matching file.

[RanCommand](conditions.md#captain_hook.RanCommand)  
Transcript-history condition: true when a Bash tool use running `argv` exists.

[Runs](conditions.md#captain_hook.Runs)  
Structural Bash condition: true when a parsed command's argv starts with `argv`.

[UsedSkill](conditions.md#captain_hook.UsedSkill)  
Transcript-history condition: true when a Skill tool use named one of `names`.

[UsedTool](conditions.md#captain_hook.UsedTool)  
Transcript-history condition: true when a tool use named one of `names` exists.

[UserSaid](conditions.md#captain_hook.UserSaid)  
Matches when a user prompt matches one of `patterns`.

[InPlanMode](conditions.md#captain_hook.InPlanMode)  
Matches when the agent is in plan mode.

[Waiting](conditions.md#captain_hook.Waiting)  
Condition matching while the session is parked on out-of-band work.

[FromSubagent](conditions.md#captain_hook.FromSubagent)  
Condition matching when the current event originates from a subagent or teammate.

[SkipPermissions](conditions.md#captain_hook.SkipPermissions)  
Condition matching when the session was launched with permission bypass available.

[FromTeammate](conditions.md#captain_hook.FromTeammate)  
Matches when the current turn's in-flight subagent spawn is a named teammate.

[FreshSession](conditions.md#captain_hook.FreshSession)  
Matches a `SessionStart` from a fresh `startup` or `clear`, not a `resume` or `compact`.

[Headless](conditions.md#captain_hook.Headless)  
Matches a headless `claude -p` / SDK run (`CLAUDE_CODE_ENTRYPOINT` in the `sdk-*` family).

[RewritingExistingPlan](conditions.md#captain_hook.RewritingExistingPlan)  
Matches a `Write` to a plan file (`.md` under `plans/` or `specs/`) already written this

[ScratchPath](conditions.md#captain_hook.ScratchPath)  
Matches a file-tool target resolving into a system temp root or a scratch-named directory.

[EditedSource](conditions.md#captain_hook.EditedSource)  
Matches when the session edited a non-test, in-repo source file (docs and config excluded).

[Commits](conditions.md#captain_hook.Commits)  
Matches a command line whose primary command explicitly names a path ending in `suffix`.

[Redirects](conditions.md#captain_hook.Redirects)  
Matches when any command in the line carries a shell redirect (input or output).

[Or](conditions.md#captain_hook.Or)  
Match if any of the inner conditions matches.

[And](conditions.md#captain_hook.And)  
Match only if every inner condition matches (useful nested inside `Or`/`Not`).

[Not](conditions.md#captain_hook.Not)  
Match only if the inner condition does not match.

[Signal](conditions.md#captain_hook.Signal)  
A regex-based signal pattern used in the scoring pipeline.

[Signals](conditions.md#captain_hook.Signals)  
Bundle of signal patterns with a scoring threshold.

[CustomCondition](conditions.md#captain_hook.CustomCondition)  
Protocol for user-defined hook conditions.

[CustomCommandLineCondition](conditions.md#captain_hook.CustomCommandLineCondition)  
CustomCondition that fires only when a parsed Bash command line is present.

[CustomInputTypeCondition](conditions.md#captain_hook.CustomInputTypeCondition)  
CustomCondition that fires only for a specific typed tool call.

[workflow_script_source()](conditions.md#captain_hook.workflow_script_source)  
The pending `Workflow` call's script source, or `None`.

[workflow_opt_values()](conditions.md#captain_hook.workflow_opt_values)  
Best-effort raw-source scan for values pinned to `key` in agent() opts. Never raises.


## Events & Results


Typed lifecycle events and hook outcomes.


[Event](events-results.md#captain_hook.Event)  
Hook lifecycle events that can trigger registered hooks.

[BaseHookEvent](events-results.md#captain_hook.BaseHookEvent)  
Base class for all hook events, providing access to raw payload, context, and convenience methods.

[ToolHookEvent](events-results.md#captain_hook.ToolHookEvent)  
Event for tool-related hooks, adding tool name, input, command, and file access.

[ToolRewriteEvent](events-results.md#captain_hook.ToolRewriteEvent)  
Tool event whose input can be rewritten before it runs.

[PreToolUseEvent](events-results.md#captain_hook.PreToolUseEvent)  
Fires before a tool is executed. Return a block result to prevent execution.

[PermissionRequestEvent](events-results.md#captain_hook.PermissionRequestEvent)  
Fires when a permission dialog would be shown.

[PostToolUseEvent](events-results.md#captain_hook.PostToolUseEvent)  
Fires after a tool completes successfully, with access to the tool response.

[PostToolUseFailureEvent](events-results.md#captain_hook.PostToolUseFailureEvent)  
Fires after a tool fails, providing the error message and interrupt status.

[UserPromptSubmitEvent](events-results.md#captain_hook.UserPromptSubmitEvent)  
Fires when the user submits a prompt, before the agent processes it.

[StopEvent](events-results.md#captain_hook.StopEvent)  
Fires when the agent is about to stop. Return a block result to prevent stopping.

[SubagentStartEvent](events-results.md#captain_hook.SubagentStartEvent)  
Fires when a subagent is launched. Provides `agent_type` for filtering.

[SubagentStopEvent](events-results.md#captain_hook.SubagentStopEvent)  
Fires when a subagent finishes. Provides `agent_type` for filtering.

[BackgroundTask](events-results.md#captain_hook.BackgroundTask)  
A background task keeping the session alive, from a `Stop`/`SubagentStop` payload.

[SessionCron](events-results.md#captain_hook.SessionCron)  
A scheduled prompt registered on the session, from a `Stop`/`SubagentStop` payload.

[PreCompactEvent](events-results.md#captain_hook.PreCompactEvent)  
Fires before context compaction, providing the trigger and custom instructions.

[NotificationEvent](events-results.md#captain_hook.NotificationEvent)  
Fires on system notifications, providing message, title, and notification type.

[SessionStartEvent](events-results.md#captain_hook.SessionStartEvent)  
Fires when a session starts, providing what triggered it. Warns inject context; it cannot block.

[SessionEndEvent](events-results.md#captain_hook.SessionEndEvent)  
Fires when the session ends, providing the termination reason. Output is ignored, so it cannot block.

[HookContext](events-results.md#captain_hook.HookContext)  
Runtime context injected into every hook event.

[Turn](events-results.md#captain_hook.Turn)  
The current turn as a one-turn `~cc_transcript.query.Session` view.

[HookResult](events-results.md#captain_hook.HookResult)  
The return value from a hook handler, specifying the action and optional message.

[Action](events-results.md#captain_hook.Action)  
Hook result action determining how the hook output is handled.

[Agent](events-results.md#captain_hook.Agent)  
Condition matching the current event's subagent type against one or more names.


## Files & Commands


Path matching and AST-level command inspection.


[File](files-commands.md#captain_hook.File)  
A file path wrapper with glob matching, prefix checks, and test-file detection.

[file.PathMatcher](files-commands.md#captain_hook.file.PathMatcher)  
A reusable set of glob patterns for matching file paths. Supports `in` operator.

[file.categorize_files()](files-commands.md#captain_hook.file.categorize_files)  
Split paths into source, test, and skipped buckets for a language.

[util.fs.read_json()](files-commands.md#captain_hook.util.fs.read_json)  
Read and parse a JSON file, returning *default* on missing file or parse error.

[util.fs.resolve_binary()](files-commands.md#captain_hook.util.fs.resolve_binary)  
Resolve an absolute, executable path for *name*, or None.

[util.fs.binary_supports()](files-commands.md#captain_hook.util.fs.binary_supports)  
Whether the binary *name* advertises *flag* in its `--help` output.

[Cmd](files-commands.md#captain_hook.Cmd)  
The parsed command line behind `evt.cmd` -- a walk over every command invocation it contains.

[Call](files-commands.md#captain_hook.Call)  
One command invocation reached by walking a command line -- a top-level occurrence, a

[Target](files-commands.md#captain_hook.Target)  
One operand of a command -- a literal path or a glob -- with resolution and blast-radius predicates.

[Targets](files-commands.md#captain_hook.Targets)  
The operand targets of a command, in order -- iterable, sized, and expandable as a whole.

[Expansion](files-commands.md#captain_hook.Expansion)  
The paths a target's glob resolves to, plus whether the walk budget was exhausted.

[Command](files-commands.md#captain_hook.Command)  
A single parsed shell command with executable, arguments, env vars, and redirects.

[CommandLine](files-commands.md#captain_hook.CommandLine)  
A full parsed bash command line, potentially containing multiple commands joined by operators.

[Redirect](files-commands.md#captain_hook.Redirect)  
A shell redirect parsed from a bash command (e.g. `> file.txt`, `2>&1`).

[Word](files-commands.md#captain_hook.Word)  
One structural word of a parsed command (`Command.words`).


## Tool Calls


Typed tool-call inputs reached via evt.input and evt.as_input().


[ToolCall](tool-calls.md#captain_hook.ToolCall)  

[ToolCallBase](tool-calls.md#captain_hook.ToolCallBase)  
Common shape of every typed tool call.

[ReadCall](tool-calls.md#captain_hook.ReadCall)  
A Read of a file, optionally windowed.

[BashCall](tool-calls.md#captain_hook.BashCall)  
A Bash/Execute shell invocation.

[EditCall](tool-calls.md#captain_hook.EditCall)  
An Edit replacement of `old` with `new` in one file.

[MultiEditCall](tool-calls.md#captain_hook.MultiEditCall)  
A MultiEdit applying `edits` to one file, in order.

[WriteCall](tool-calls.md#captain_hook.WriteCall)  
A Write/Create of a whole file.

[NotebookEditCall](tool-calls.md#captain_hook.NotebookEditCall)  
A NotebookEdit replacing a cell's source.

[GlobCall](tool-calls.md#captain_hook.GlobCall)  
A Glob file-pattern search.

[GrepCall](tool-calls.md#captain_hook.GrepCall)  
A Grep content search.

[SkillCall](tool-calls.md#captain_hook.SkillCall)  
A Skill invocation.

[TaskCall](tool-calls.md#captain_hook.TaskCall)  
An Agent/Task subagent dispatch.

[TaskCreateCall](tool-calls.md#captain_hook.TaskCreateCall)  
A TaskCreate tracker entry.

[TaskUpdateCall](tool-calls.md#captain_hook.TaskUpdateCall)  
A TaskUpdate tracker change.

[ExitPlanModeCall](tool-calls.md#captain_hook.ExitPlanModeCall)  
An ExitPlanMode/ExitSpecMode plan submission.

[OtherCall](tool-calls.md#captain_hook.OtherCall)  
A tool the platform does not type: unknown names, MCP tools, and -- under


## Tasks


The native task list, read via evt.tasks.


[Task](tasks.md#captain_hook.Task)  
A task read from Claude Code's native task store (`~/.claude/tasks/<list-id>/<id>.json`).

[Tasks](tasks.md#captain_hook.Tasks)  
The live task list for one session, read from the native store rather than the transcript.


## Signals


NLP signal scoring over transcript text.


[Clause](signals.md#captain_hook.Clause)  
One dependency-aware pattern matched against each sentence of a text.

[NlpSignal](signals.md#captain_hook.NlpSignal)  
A transcript signal that scores `weight` when any clause matches a sentence.

[Phrase](signals.md#captain_hook.Phrase)  
A set of lowercased lemmas naming one concept, matched against tokens by lemma.

[is_past_predicate()](signals.md#captain_hook.is_past_predicate)  
Whether `tok` reports a completed action.

[has_nominal_subject()](signals.md#captain_hook.has_nominal_subject)  
Whether `tok` has a substantive active subject.

[subject_kind()](signals.md#captain_hook.subject_kind)  
The shape of `tok`'s subject, as `Clause`'s `subject` constraint sees it.


## State & Sessions


Session state, workflow state, and multi-step workflows.


[HookState](state-sessions.md#captain_hook.HookState)  
Per-hook persistent state tracked across events in a session (`fire_count` for `max_fires`).

[PrimitiveState](state-sessions.md#captain_hook.PrimitiveState)  
Per-primitive nudge/gate state shared across all hooks in a session.

[SourceEdits](state-sessions.md#captain_hook.SourceEdits)  
Condition matching an `Edit`/`Write` of a non-test source file in one language.

[WorkflowState](state-sessions.md#captain_hook.WorkflowState)  
Base for a pydantic model that bundles one session workflow across several hooks.

[workflow_state()](state-sessions.md#captain_hook.workflow_state)  

[SessionSlot](state-sessions.md#captain_hook.SessionSlot)  
A typed slot for reading/writing a single Pydantic model in a session directory.

[SessionStore](state-sessions.md#captain_hook.SessionStore)  
Class-keyed store providing typed `SessionSlot` access via `store[ModelClass]`.

[session_state()](state-sessions.md#captain_hook.session_state)  
Decorator that registers a Pydantic model for collective `SessionStore` introspection.

[DurableState](state-sessions.md#captain_hook.DurableState)  
Base for a model persisted across sessions, scoped by the `scope` class keyword.

[DurableSlot](state-sessions.md#captain_hook.DurableSlot)  
A `SessionSlot` rooted in a durable directory; inherits the locked `mutate()`.

[DurableStore](state-sessions.md#captain_hook.DurableStore)  
Class-keyed durable store providing typed `DurableSlot` access via `store[Model]`.

[Deque](state-sessions.md#captain_hook.Deque)  
A bounded `deque` field type whose `maxlen` survives JSON round-trips.

[Workflow](state-sessions.md#captain_hook.Workflow)  

[Step](state-sessions.md#captain_hook.Step)  
One step of a `workflow()` guard: `check` gates progress, `message` is shown when it fails.

[Artifact](state-sessions.md#captain_hook.Artifact)  

[text_matches()](state-sessions.md#captain_hook.text_matches)  

[workflow()](state-sessions.md#captain_hook.workflow)  


## Transcripts


Registering external transcripts into a session's deep view.


[register_transcript()](transcripts.md#captain_hook.register_transcript)  
Register an external transcript against `session_id` so it folds into the deep view.

[RegisteredTranscript](transcripts.md#captain_hook.RegisteredTranscript)  
An external transcript folded into a session's deep view -- a codex thread id or a file path.

[RegisteredTranscripts](transcripts.md#captain_hook.RegisteredTranscripts)  
The external transcripts registered against one session, in registration order.


## Testing


Inline tests for hooks.


[Input](testing.md#captain_hook.Input)  
Inline test input descriptor modeling an event payload.

[T](testing.md#captain_hook.T)  
Namespaced transcript-fixture builders for `Input(transcript=[...])` in inline tests.

[Allow](testing.md#captain_hook.Allow)  
Inline test expectation: the hook should allow (return None or action `"allow"`).

[Block](testing.md#captain_hook.Block)  
Inline test expectation: the hook should block. Optional regex `pattern` matches the block message.

[Warn](testing.md#captain_hook.Warn)  
Inline test expectation: the hook should warn. Optional regex `pattern` matches the warning message.

[Rewrite](testing.md#captain_hook.Rewrite)  
Inline test expectation: the hook should rewrite the tool input.

[Ask](testing.md#captain_hook.Ask)  
Inline test expectation: the hook returned no result (`None`).

[FileFixture](testing.md#captain_hook.FileFixture)  
Inline-test file descriptor: materialized to a real temp file so size/stat-based guards run for real.

[TranscriptFixture](testing.md#captain_hook.TranscriptFixture)  
A lightweight transcript stub for use in inline tests.


## Configuration & Prompts


Settings, scaffolding, and LLM prompt helpers.


[HooksSettings](configuration-prompts.md#captain_hook.HooksSettings)  
Base settings class for hook configuration, backed by environment variables with `HOOKS_` prefix.

[build_settings()](configuration-prompts.md#captain_hook.build_settings)  
Build settings from a conf module via an explicit `HooksSettings` subclass or auto-inferred fields.

[Prompt](configuration-prompts.md#captain_hook.Prompt)  
Fluent builder for structured LLM prompts with system text, XML context sections, and a question.


## Prompt Contexts


Declarative evidence blocks attached to LLM primitive prompts.


[PromptContext](prompt-contexts.md#captain_hook.PromptContext)  
One declarative XML block attached to an LLM primitive's prompt.

[apply_contexts()](prompt-contexts.md#captain_hook.apply_contexts)  
Append each context's block to `prompt` in order, each clipped to `max_len` characters.

[BeforeEdit](prompt-contexts.md#captain_hook.BeforeEdit)  
The pending edit's pre-image, as a `<before_edit>` block.

[AfterEdit](prompt-contexts.md#captain_hook.AfterEdit)  
The pending edit's new text, as an `<after_edit>` block.

[Introduced](prompt-contexts.md#captain_hook.Introduced)  
Constructs the pending edit newly introduces, as an auto-tagged block.

[WorkflowScriptSource](prompt-contexts.md#captain_hook.WorkflowScriptSource)  
Gating context: the pending `Workflow` call's script source, headed by its model pins.

[UserMessages](prompt-contexts.md#captain_hook.UserMessages)  
The session's user prompts as a `<user_messages>` request/authorization record.

[Excerpts](prompt-contexts.md#captain_hook.Excerpts)  
Verbatim excerpts pulled from a text under a character budget.

[excerpt_around()](prompt-contexts.md#captain_hook.excerpt_around)  
Verbatim excerpts of `text` around each `(start, end)` character span.

[COMMENT_TYPES](prompt-contexts.md#captain_hook.COMMENT_TYPES)  
Tree-sitter node kinds that denote a comment, across every supported grammar.

[Edit](prompt-contexts.md#captain_hook.Edit)  
The pending edit's before/after source, parsed for structural queries.

[SyntaxNode](prompt-contexts.md#captain_hook.SyntaxNode)  
One node of a parsed syntax tree -- the framework's face over the ast-grep binding node.

[Match](prompt-contexts.md#captain_hook.Match)  
A structural match, located by 1-based line to align with `Violation` and changed-line scoping.
