hooks

package
v0.173.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 14 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 hooks installs and removes the caprock-hook shim in Claude Code's user-level settings.json, non-destructively. See .ai/03-contracts.md § Hook shim.

Index

Constants

View Source
const BypassKey = "skipDangerousModePermissionPrompt"

BypassKey is the user setting Claude Code writes when someone answers "Yes, I accept" to its one-time bypass warning ("WARNING: Claude Code running in Bypass Permissions mode"). Until it is true, the first session started with --dangerously-skip-permissions opens on that warning, with "No, exit" selected — so Enter ends the session (ADR-042).

View Source
const DefaultRetentionDays = 30

DefaultRetentionDays is Claude Code's period when the key is unset.

View Source
const KeepRetentionDays = 36500

KeepRetentionDays is what "Keep them from now on" writes: a hundred years, which is Claude Code never deleting a transcript by age.

View Source
const RetentionKey = "cleanupPeriodDays"

RetentionKey is the user setting that says how many days Claude Code keeps a conversation's transcript under ~/.claude/projects. At startup it deletes every transcript older than that; unset, the period is DefaultRetentionDays. Caprock can only import what is still on disk, so a new user's history starts about that many days back.

View Source
const ShimTimeoutSeconds = 5

ShimTimeoutSeconds is the per-hook timeout written into settings.json. The shim itself exits within ~1s; 5s is headroom for a slow disk, and it bounds the Phase 2 Stop request-response (5s) too.

Variables

View Source
var Events = []string{"SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "SubagentStop", "SessionEnd", "PreCompact", "StopFailure", "PermissionRequest"}

Events the shim registers for (Phase 0). Order is the order written.

Functions

func AcceptBypass added in v0.79.0

func AcceptBypass(settingsPath string) (backup string, err error)

AcceptBypass records the user's acceptance the way Claude Code's own dialog does — the same key, true, in user settings — after Caprock showed the same warning and the user accepted it there. The file is backed up once first, and every other key is kept in place and order.

func BypassAccepted added in v0.79.0

func BypassAccepted(settingsPath string) (bool, error)

BypassAccepted reports whether the user has accepted Claude Code's bypass warning in their user settings. A missing file is "no", not an error.

func DefaultSettingsPath

func DefaultSettingsPath() (string, error)

DefaultSettingsPath is ~/.claude/settings.json.

func EnsureShim added in v0.70.1

func EnsureShim(dataDir string) error

EnsureShim brings `<data dir>/caprock-hook` up to date with this binary, the path every settings.json Caprock wrote runs on each hook event.

  • A caprock-hook beside this executable (Homebrew, the release archives, `make build`) is copied in whenever the bytes differ.
  • With none beside it (the desktop app ships caprock alone), an existing data-dir shim is replaced by this binary itself, which runs as the shim when started under that name (cmd/caprock). Without this, a shim a Homebrew install put there months earlier kept feeding hooks to every later daemon, because nothing ever replaced it (a user's 0.31.2 shim under 0.147.0). With no data-dir shim either, nothing is written and `<self> hook` is the registered command (ShimCommand).

Every write goes to a temporary file in the data dir and is renamed over the shim, so Claude Code, which may run it at any moment, sees the old file or the new one and never a missing or half-written one (rule 3).

func Install

func Install(settingsPath, shimPath string) (backup string, err error)

Install merges our entries into settings.json (creating the file if absent), backing the original up once before the first write. Returns the backup path ("" when nothing was written or no original existed).

func InstallStatusline added in v0.5.0

func InstallStatusline(settingsPath, cmdPath string) (backup string, err error)

InstallStatusline sets settings.json's statusLine to our command, backing the file up once. It refuses to clobber a statusLine the user set to something else — callers should check StatuslineInstalled and only offer to install when nothing (or our own) is present. Returns the backup path (empty if no change).

func KeepTranscripts added in v0.157.0

func KeepTranscripts(settingsPath string, days int) (changed bool, err error)

KeepTranscripts writes cleanupPeriodDays = days into user settings, the one key changed and every other byte of the file left as it was: the value is replaced where it stands, or the key is added first in the object, indented like the key after it. The user asked for it on the Lifetime screen, after it said what the setting does.

The file is backed up once first, as for the hooks entry, and written atomically. An unparsable file is refused, never overwritten: Claude Code would refuse it too, and the user's own edits are in it. Asking again for the period already set changes nothing and writes nothing.

func ListBackups added in v0.18.0

func ListBackups(settingsPath string) []string

ListBackups returns the Caprock backups of settings.json, oldest first.

func MarshalIndent

func MarshalIndent(v any) ([]byte, error)

MarshalIndent renders an ordered value with 2-space indentation, matching how Claude Code writes settings.json.

func ParseOrdered

func ParseOrdered(data []byte) (any, error)

ParseOrdered decodes JSON preserving object key order.

func RepairStatusline added in v0.53.2

func RepairStatusline(settingsPath, cmdPath string) (repaired bool, err error)

RepairStatusline rewrites our own statusLine entry when the stored command would not actually run, and reports whether it changed anything.

The one form this exists for is the quotes-around-everything command an older version wrote (`"…/caprock statusline"`), which the shell resolves as a single filename that does not exist — so the status line printed nothing, silently, for as long as the entry survived. Recognising it is not enough: install treats anything of ours as an idempotent no-op, so without this the entry would be identified and then left exactly as broken as it was found.

It is deliberately narrow. A statusLine that is not ours is never touched, and neither is one of ours that already runs — this repairs a known-broken spelling, it does not normalise everyone's command to today's preferred one.

func Restore added in v0.18.0

func Restore(settingsPath, backupPath string) error

Restore copies a backup back over settings.json. It takes the backup path explicitly rather than picking one, because choosing which snapshot a user wants is a decision only they can make. Before overwriting it snapshots the current file, so a restore is itself undoable.

func SetStatuslineOn added in v0.112.2

func SetStatuslineOn(settingsPath, cmdPath string, on bool) (changed bool, err error)

SetStatuslineOn applies Settings → Status line to one settings.json: on (Full or Short) registers our command when no statusLine is set, off (Off) removes ours. Both go through the same ownership checks as install and uninstall — a statusLine the user set to something else is never replaced and never removed — and both are no-ops when there is nothing to do. Reports whether the file changed.

func ShellCommand added in v0.27.4

func ShellCommand(p string) string

func ShimCommand added in v0.70.1

func ShimCommand(dataDir string) string

ShimCommand returns the command to register in settings.json: the shim binary in the data dir when it exists, else `<self> hook`.

func StatuslineInstalled added in v0.5.0

func StatuslineInstalled(settingsPath, cmdPath string) (ours bool, present bool, err error)

StatuslineInstalled reports whether settings.json already has a statusLine command that points at our binary (`… statusline`). A different statusLine command (the user's own) is left alone and reported as not-ours.

func Uninstall

func Uninstall(settingsPath, shimPath string) (removed bool, err error)

Uninstall removes only entries whose command points at our shim, and drops empty containers it leaves behind. Other hooks are untouched. Returns whether anything was removed.

func UninstallStatusline added in v0.5.0

func UninstallStatusline(settingsPath, cmdPath string) (removed bool, err error)

UninstallStatusline removes the statusLine only if it is ours, leaving a user-set statusLine untouched. Returns whether anything was removed.

Types

type Object

type Object struct {
	Keys   []string
	Values map[string]any // values are: *Object, []any, string, float64, bool, nil
}

Object is a JSON object with stable key order.

func NewObject

func NewObject() *Object

NewObject creates an empty ordered object.

func (*Object) Delete

func (o *Object) Delete(k string)

Delete removes a key.

func (*Object) Get

func (o *Object) Get(k string) (any, bool)

Get returns a value and whether it exists.

func (*Object) Len

func (o *Object) Len() int

Len returns the number of keys.

func (*Object) MarshalJSON

func (o *Object) MarshalJSON() ([]byte, error)

MarshalJSON writes keys in insertion order.

func (*Object) Set

func (o *Object) Set(k string, v any)

Set inserts or replaces a value, appending new keys at the end.

type Repaired added in v0.149.0

type Repaired struct {
	// Hooks counts our hook commands pointed at the current shim (or
	// removed, where the event already had the current one).
	Hooks int
	// Statusline is whether our statusLine was pointed at this binary.
	Statusline bool
}

Repaired says what RepairPaths rewrote in one settings.json.

func RepairPaths added in v0.149.0

func RepairPaths(settingsPath, shimCmd, statuslineCmd string) (Repaired, error)

RepairPaths points Caprock's own entries in settings.json at the binaries this install runs, and reports what it changed. shimCmd is what an install registers (ShimCommand); statuslineCmd is `<ShellCommand(self)> statusline`, or "" to leave the statusLine alone.

An entry is rewritten only when it is ours (the same recognition install and uninstall use) and the program it runs is missing or is a different file from the one this install would register: a Homebrew caprock that was uninstalled, or one months older than the daemon reading its hooks. A command of anyone else's is never touched, and neither is ours when it already runs this install's binary, whatever its spelling or flags. A statusLine's flags (`--width 100`) are kept.

The file is backed up once and written atomically, like every other write here. It is the daemon's self-repair at start: nobody can be expected to notice that a status line or a hook has been running someone else's binary.

func (Repaired) Changed added in v0.149.0

func (r Repaired) Changed() bool

Changed reports whether anything was written.

type Retention added in v0.157.0

type Retention struct {
	// Days is the period Claude Code applies: the setting, or
	// DefaultRetentionDays when it is unset.
	Days int `json:"days"`
	// Set reports whether the settings name a period at all.
	Set bool `json:"set"`
}

Retention is what the user settings say about it.

func ReadRetention added in v0.157.0

func ReadRetention(settingsPath string) (Retention, error)

ReadRetention reads cleanupPeriodDays from user settings. A missing file is the default period, not an error; an unparsable one is an error, the same as for every other read of this file. A value that is not a number is taken as unset, which is how Claude Code's settings check treats it.

type Status

type Status struct {
	SettingsPath string   `json:"settings_path"`
	ShimPath     string   `json:"shim_path"`
	Installed    []string `json:"installed"` // events with our entry present
	Missing      []string `json:"missing"`   // events from Events without our entry
	ShimExists   bool     `json:"shim_exists"`
}

Status describes what is registered.

func Inspect

func Inspect(settingsPath, shimPath string) (Status, error)

Inspect reads settings.json and reports which events carry our shim.

func InstallFor added in v0.70.1

func InstallFor(dataDir, settingsPath string) (Status, string, error)

InstallFor is `caprock hooks install` as one call, for the CLI and the dashboard's Install button alike: put the shim in the data dir, merge our entries into the settings file at settingsPath (backed up first), and report what is registered now. The two used to be separate code in cmd/caprock; one path means the button cannot install something the command would not.

func StatusFor added in v0.70.1

func StatusFor(dataDir, settingsPath string) (Status, error)

StatusFor is what is registered, checked against the command an install would write — the one question /v1/status, `caprock status` and the Install button must all answer the same way.

The daemon used to check against the data-dir shim path alone. When no caprock-hook sat beside the executable, install registered the fallback `"<exe>" hook`, which the check recognised only if the executable was named caprock; under any other name (a renamed or preview build) the button said "installed" and the next status said all nine events were missing.

func (Status) Complete

func (s Status) Complete() bool

Complete reports whether every event is registered and the shim binary exists.

Jump to

Keyboard shortcuts

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