cli

package
v0.3.10 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

hooks_claudecode_handlers.go contains Claude Code specific hook handler implementations. These are called by the hook registry in hook_registry.go.

hooks_geminicli_handlers.go contains Gemini CLI specific hook handler implementations. These are called by the hook registry in hook_registry.go.

Index

Constants

View Source
const (
	// EntireSettingsFile is the path to the Entire settings file
	EntireSettingsFile = ".entire/settings.json"
	// EntireSettingsLocalFile is the path to the local settings override file (not committed)
	EntireSettingsLocalFile = ".entire/settings.local.json"
)
View Source
const (
	EntireDir         = paths.EntireDir
	EntireTmpDir      = paths.EntireTmpDir
	EntireMetadataDir = paths.EntireMetadataDir
)

Directory paths - re-exported from paths package for convenience

View Source
const DisabledMessage = "Entire is disabled. Run `entire enable` to re-enable."

DisabledMessage is the message shown when Entire is disabled

Variables

View Source
var (
	Version = "dev"
	Commit  = "unknown"
)

Version information (can be set at build time)

View Source
var ErrSessionSkipped = errors.New("session skipped")

ErrSessionSkipped is returned when a session should be skipped (e.g., due to concurrent warning).

Functions

func AgentTranscriptPath

func AgentTranscriptPath(transcriptDir, agentID string) string

AgentTranscriptPath returns the path to a subagent's transcript file. Subagent transcripts are stored as agent-{agentId}.jsonl in the same directory as the main transcript.

func BranchExistsLocally

func BranchExistsLocally(branchName string) (bool, error)

BranchExistsLocally checks if a local branch exists.

func BranchExistsOnRemote

func BranchExistsOnRemote(branchName string) (bool, error)

BranchExistsOnRemote checks if a branch exists on the origin remote. Returns true if the branch is tracked on origin, false otherwise.

func CaptureGeminiPrePromptState

func CaptureGeminiPrePromptState(sessionID, transcriptPath string) error

CaptureGeminiPrePromptState captures current untracked files and transcript position before a prompt for Gemini sessions. This is called by the BeforeAgent hook. The transcriptPath is the path to the Gemini session transcript (JSON format).

func CapturePrePromptState

func CapturePrePromptState(sessionID, transcriptPath string) error

CapturePrePromptState captures current untracked files and transcript position before a prompt and saves them to a state file. Works correctly from any subdirectory within the repository. The transcriptPath parameter is optional - if empty, transcript position won't be captured.

func CapturePreTaskState

func CapturePreTaskState(toolUseID string) error

CapturePreTaskState captures current untracked files before a Task execution and saves them to a state file. Works correctly from any subdirectory within the repository.

func CheckoutBranch

func CheckoutBranch(ref string) error

CheckoutBranch switches to the specified local branch or commit. Uses git CLI instead of go-git to work around go-git v5 bug where Checkout deletes untracked files (see https://github.com/go-git/go-git/issues/970). Should be switched back to go-git once we upgrade to go-git v6 Returns an error if the ref doesn't exist or checkout fails.

func CleanupPrePromptState

func CleanupPrePromptState(sessionID string) error

CleanupPrePromptState removes the state file after use

func CleanupPreTaskState

func CleanupPreTaskState(toolUseID string) error

CleanupPreTaskState removes the task state file after use

func ComputeDeletedFiles deprecated

func ComputeDeletedFiles() ([]string, error)

ComputeDeletedFiles returns files that were deleted during the session (tracked files that no longer exist).

Deprecated: Use ComputeFileChanges instead for better performance.

func ComputeFileChanges

func ComputeFileChanges(preState *PrePromptState) (newFiles, deletedFiles []string, err error)

ComputeFileChanges returns new files (created during session) and deleted files (tracked files that were deleted) using a single git status call. This is more efficient than calling ComputeNewFiles and ComputeDeletedFiles separately.

If preState is nil, newFiles will be nil but deletedFiles will still be computed (deleted files don't depend on pre-prompt state).

func ComputeNewFiles deprecated

func ComputeNewFiles(preState *PrePromptState) ([]string, error)

ComputeNewFiles compares current untracked files with pre-prompt state to find files that were created during the session.

Deprecated: Use ComputeFileChanges instead for better performance.

func ComputeNewFilesFromTask

func ComputeNewFilesFromTask(preState *PreTaskState) ([]string, error)

ComputeNewFilesFromTask compares current untracked files with pre-task state to find files that were created during the task.

func CopyAgentTranscript

func CopyAgentTranscript(srcTranscript, taskMetadataDir, agentID string) error

CopyAgentTranscript copies a subagent's transcript to the task metadata directory. If the source transcript doesn't exist, this is a no-op (not an error).

func CountTodosFromToolInput

func CountTodosFromToolInput(toolInput json.RawMessage) int

CountTodosFromToolInput returns the number of todo items in the TodoWrite tool_input. Returns 0 if the JSON is invalid or empty.

This function unwraps the outer tool_input object to extract the todos array, then delegates to strategy.CountTodos for the actual count.

func DetectChangedFiles

func DetectChangedFiles() (modified, newFiles, deleted []string, err error)

DetectChangedFiles detects files that have been modified, added, or deleted since the last commit (or compared to the index for incremental checkpoints). Returns three slices: modified files, new (untracked) files, and deleted files. Excludes .entire/ directory from all results.

func ExtractLastCompletedTodoFromToolInput

func ExtractLastCompletedTodoFromToolInput(toolInput json.RawMessage) string

ExtractLastCompletedTodoFromToolInput extracts the content of the last completed todo item. In PostToolUse[TodoWrite], the tool_input contains the NEW todo list where the just-finished work is marked as "completed". The last completed item represents the work that was just done.

Returns empty string if no completed items exist or JSON is invalid.

func ExtractTodoContentFromToolInput

func ExtractTodoContentFromToolInput(toolInput json.RawMessage) string

ExtractTodoContentFromToolInput extracts the content of the in-progress todo item from TodoWrite tool_input. Falls back to the first pending item if no in-progress item is found. Returns empty string if no suitable item is found or JSON is invalid.

This function unwraps the outer tool_input object to extract the todos array, then delegates to strategy.ExtractInProgressTodo for the actual parsing logic.

func FetchAndCheckoutRemoteBranch

func FetchAndCheckoutRemoteBranch(branchName string) error

FetchAndCheckoutRemoteBranch fetches a branch from origin and creates a local tracking branch. Uses git CLI instead of go-git for fetch because go-git doesn't use credential helpers, which breaks HTTPS URLs that require authentication.

func FetchMetadataBranch

func FetchMetadataBranch() error

FetchMetadataBranch fetches the entire/sessions branch from origin and creates/updates the local branch. This is used when the metadata branch exists on remote but not locally. Uses git CLI instead of go-git for fetch because go-git doesn't use credential helpers, which breaks HTTPS URLs that require authentication.

func FilterAndNormalizePaths

func FilterAndNormalizePaths(files []string, cwd string) []string

FilterAndNormalizePaths converts absolute paths to relative and filters out infrastructure paths and paths outside the repo.

func FindActivePreTaskFile

func FindActivePreTaskFile() (taskToolUseID string, found bool)

FindActivePreTaskFile finds an active pre-task file in .entire/tmp/ and returns the parent Task's tool_use_id. Returns ("", false) if no pre-task file exists. When multiple pre-task files exist (nested subagents), returns the most recently modified one. Works correctly from any subdirectory within the repository.

func FindCheckpointUUID

func FindCheckpointUUID(transcript []transcriptLine, toolUseID string) (string, bool)

FindCheckpointUUID finds the UUID of the message containing the tool_result for the given tool_use_id. This is used to find the checkpoint point for transcript truncation when rewinding to a task. Returns the UUID and true if found, empty string and false otherwise.

func GetAgentsWithHooksInstalled

func GetAgentsWithHooksInstalled() []agent.AgentName

GetAgentsWithHooksInstalled returns names of agents that have hooks installed.

func GetCurrentBranch

func GetCurrentBranch() (string, error)

GetCurrentBranch returns the name of the current branch. Returns an error if in detached HEAD state or if not in a git repository.

func GetCurrentHookAgent

func GetCurrentHookAgent() (agent.Agent, error)

func GetLogLevel

func GetLogLevel() string

GetLogLevel returns the configured log level from settings. Returns empty string if not configured (caller should use default). Note: ENTIRE_LOG_LEVEL env var takes precedence; check it first.

func GetMergeBase

func GetMergeBase(branch1, branch2 string) (*plumbing.Hash, error)

GetMergeBase finds the common ancestor (merge-base) between two branches. Returns the hash of the merge-base commit.

func GetNextCheckpointSequence

func GetNextCheckpointSequence(sessionID, taskToolUseID string) int

GetNextCheckpointSequence returns the next sequence number for incremental checkpoints. It counts existing checkpoint files in the task metadata checkpoints directory. Returns 1 if no checkpoints exist yet.

func GetStrategy

func GetStrategy() strategy.Strategy

GetStrategy returns the configured strategy instance. Falls back to default if the configured strategy is not found.

func HasUncommittedChanges

func HasUncommittedChanges() (bool, error)

HasUncommittedChanges checks if there are any uncommitted changes in the repository. This includes staged changes, unstaged changes, and untracked files. Uses git CLI instead of go-git because go-git doesn't respect global gitignore (core.excludesfile) which can cause false positives for globally ignored files.

func IsAccessibleMode

func IsAccessibleMode() bool

IsAccessibleMode returns true if accessibility mode should be enabled. This checks the ACCESSIBLE environment variable. Set ACCESSIBLE=1 (or any non-empty value) to enable accessible mode, which uses simpler prompts that work better with screen readers.

func IsEnabled

func IsEnabled() (bool, error)

IsEnabled returns whether Entire is currently enabled. Returns true by default if settings cannot be loaded.

func IsMultiSessionWarningDisabled

func IsMultiSessionWarningDisabled() bool

IsMultiSessionWarningDisabled checks if multi-session warnings are disabled. Returns false (show warnings) by default if settings cannot be loaded or the key is missing.

func IsOnDefaultBranch

func IsOnDefaultBranch() (bool, string, error)

IsOnDefaultBranch checks if the repository is currently on the default branch. It determines the default branch by: 1. Checking the remote origin's HEAD reference 2. Falling back to common names (main, master) if remote HEAD is unavailable Returns (isDefault, branchName, error)

func JoinAgentNames

func JoinAgentNames(names []agent.AgentName) string

JoinAgentNames joins agent names into a comma-separated string.

func NewAccessibleForm

func NewAccessibleForm(groups ...*huh.Group) *huh.Form

NewAccessibleForm creates a new huh form with accessibility mode enabled if the ACCESSIBLE environment variable is set. Note: WithAccessible() is only available on forms, not individual fields. Always wrap confirmations and other prompts in a form to enable accessibility.

func NewHelpCmd

func NewHelpCmd(rootCmd *cobra.Command) *cobra.Command

NewHelpCmd creates a custom help command that supports a hidden -t flag to display the entire command tree.

func NewRootCmd

func NewRootCmd() *cobra.Command

func ParseSubagentTypeAndDescription

func ParseSubagentTypeAndDescription(toolInput json.RawMessage) (agentType, description string)

ParseSubagentTypeAndDescription extracts subagent_type and description from Task tool_input. Returns empty strings if parsing fails or fields are not present.

func RegisterHookHandler

func RegisterHookHandler(agentName agent.AgentName, hookName string, handler HookHandlerFunc)

RegisterHookHandler registers a handler for an agent's hook.

func SaveEntireSettings

func SaveEntireSettings(settings *EntireSettings) error

SaveEntireSettings saves the Entire settings to .entire/settings.json.

func SaveEntireSettingsLocal

func SaveEntireSettingsLocal(settings *EntireSettings) error

SaveEntireSettingsLocal saves the Entire settings to .entire/settings.local.json.

func ShouldSkipOnDefaultBranch

func ShouldSkipOnDefaultBranch() (bool, string)

ShouldSkipOnDefaultBranch checks if we're on the default branch. Returns (shouldSkip, branchName). If shouldSkip is true, the caller should skip the operation to avoid polluting main/master history. If the branch cannot be determined, returns (false, "") to allow the operation.

func ShouldSkipOnDefaultBranchForStrategy

func ShouldSkipOnDefaultBranchForStrategy() (bool, string)

ShouldSkipOnDefaultBranchForStrategy checks if we're on the default branch and whether the current strategy allows operating on it. Returns (shouldSkip, branchName). If shouldSkip is true, the caller should skip the operation. Shadow strategies return false (allowing main branch).

func TaskMetadataDir

func TaskMetadataDir(sessionMetadataDir, toolUseID string) string

TaskMetadataDir returns the path to a task's metadata directory within the session metadata directory.

func TruncateTranscriptAtUUID

func TruncateTranscriptAtUUID(transcript []transcriptLine, uuid string) []transcriptLine

TruncateTranscriptAtUUID returns transcript lines up to and including the line with the given UUID. If the UUID is not found or is empty, returns the entire transcript.

func ValidateBranchName

func ValidateBranchName(branchName string) error

ValidateBranchName checks if a branch name is valid using git check-ref-format. Returns an error if the name is invalid or contains unsafe characters.

func WriteTaskCheckpoint

func WriteTaskCheckpoint(taskMetadataDir string, checkpoint *TaskCheckpoint) error

WriteTaskCheckpoint writes the checkpoint.json file to the task metadata directory. Creates the directory if it doesn't exist.

func WriteTaskPrompt

func WriteTaskPrompt(taskMetadataDir, prompt string) error

WriteTaskPrompt writes the task prompt to the task metadata directory.

Types

type EntireSettings

type EntireSettings struct {
	// Strategy is the name of the git strategy to use
	Strategy string `json:"strategy"`

	// Enabled indicates whether Entire is active. When false, CLI commands
	// show a disabled message and hooks exit silently. Defaults to true.
	Enabled bool `json:"enabled"`

	// LocalDev indicates whether to use "go run" instead of the "entire" binary
	// This is used for development when the binary is not installed
	LocalDev bool `json:"local_dev,omitempty"`

	// LogLevel sets the logging verbosity (debug, info, warn, error).
	// Can be overridden by ENTIRE_LOG_LEVEL environment variable.
	// Defaults to "info".
	LogLevel string `json:"log_level,omitempty"`

	// StrategyOptions contains strategy-specific configuration
	StrategyOptions map[string]interface{} `json:"strategy_options,omitempty"`

	// Telemetry controls anonymous usage analytics.
	// nil = not asked yet (show prompt), true = opted in, false = opted out
	Telemetry *bool `json:"telemetry,omitempty"`
}

EntireSettings represents the .entire/settings.json configuration

func LoadEntireSettings

func LoadEntireSettings() (*EntireSettings, error)

LoadEntireSettings loads the Entire settings from .entire/settings.json, then applies any overrides from .entire/settings.local.json if it exists. Returns default settings if neither file exists. Works correctly from any subdirectory within the repository.

type GitAuthor

type GitAuthor struct {
	Name  string
	Email string
}

GitAuthor represents the git user configuration

func GetGitAuthor

func GetGitAuthor() (*GitAuthor, error)

GetGitAuthor retrieves the git user.name and user.email from the repository config. It checks local config first, then falls back to global config. If go-git can't find the config, it falls back to using the git command. Returns fallback defaults if no user is configured anywhere.

type HookHandlerFunc

type HookHandlerFunc func() error

HookHandlerFunc is a function that handles a specific hook event.

func GetHookHandler

func GetHookHandler(agentName agent.AgentName, hookName string) HookHandlerFunc

GetHookHandler returns the handler for an agent's hook, or nil if not found.

type PostTaskHookInput

type PostTaskHookInput struct {
	TaskHookInput

	AgentID   string          // Extracted from tool_response.agentId
	ToolInput json.RawMessage // Raw tool input for reference
}

PostTaskHookInput represents the parsed input from PostToolUse[Task] hook

type PrePromptState

type PrePromptState struct {
	SessionID      string   `json:"session_id"`
	Timestamp      string   `json:"timestamp"`
	UntrackedFiles []string `json:"untracked_files"`

	// StartMessageIndex is the message count in the transcript when this state
	// was captured. Used for calculating token usage since the prompt started.
	// Only set for Gemini sessions. Zero means not set or session just started.
	StartMessageIndex int `json:"start_message_index,omitempty"`

	// Transcript position at prompt start - tracks what was added during this checkpoint
	// Used for Claude Code sessions.
	LastTranscriptIdentifier string `json:"last_transcript_identifier,omitempty"` // Last identifier when prompt started (UUID for Claude, message ID for Gemini)
	LastTranscriptLineCount  int    `json:"last_transcript_line_count,omitempty"` // Line count when prompt started
}

PrePromptState stores the state captured before a user prompt

func LoadPrePromptState

func LoadPrePromptState(sessionID string) (*PrePromptState, error)

LoadPrePromptState loads previously captured state. Returns nil if no state file exists.

type PreTaskState

type PreTaskState struct {
	ToolUseID      string   `json:"tool_use_id"`
	Timestamp      string   `json:"timestamp"`
	UntrackedFiles []string `json:"untracked_files"`
}

PreTaskState stores the state captured before a task execution

func LoadPreTaskState

func LoadPreTaskState(toolUseID string) (*PreTaskState, error)

LoadPreTaskState loads previously captured task state. Returns nil if no state file exists.

type PromptResponsePair

type PromptResponsePair struct {
	Prompt    string
	Responses []string // Multiple responses can occur between tool calls
	Files     []string
}

PromptResponsePair represents a user prompt and the assistant's responses. Used for extracting all interactions from a transcript.

func ExtractAllPromptResponses

func ExtractAllPromptResponses(transcript []transcriptLine) []PromptResponsePair

ExtractAllPromptResponses extracts all user prompt and assistant response pairs from a transcript. Returns pairs in chronological order (oldest first). Each pair contains the user's prompt, assistant's text response, and files modified.

type SilentError

type SilentError struct {
	Err error
}

SilentError wraps an error to signal that the error message has already been printed to the user. main.go checks for this type to avoid duplicate output.

func NewSilentError

func NewSilentError(err error) *SilentError

NewSilentError creates a SilentError wrapping the given error. Use this when you've already printed a user-friendly error message and don't want main.go to print the error again.

func (*SilentError) Error

func (e *SilentError) Error() string

func (*SilentError) Unwrap

func (e *SilentError) Unwrap() error

type SubagentCheckpointHookInput

type SubagentCheckpointHookInput struct {
	SessionID      string          `json:"session_id"`
	TranscriptPath string          `json:"transcript_path"`
	ToolName       string          `json:"tool_name"`
	ToolUseID      string          `json:"tool_use_id"`
	ToolInput      json.RawMessage `json:"tool_input"`
	ToolResponse   json.RawMessage `json:"tool_response"`
}

SubagentCheckpointHookInput represents the JSON input from PostToolUse hooks for subagent checkpoint creation (TodoWrite, Edit, Write)

type TaskCheckpoint

type TaskCheckpoint struct {
	SessionID      string `json:"session_id"`
	ToolUseID      string `json:"tool_use_id"`
	CheckpointUUID string `json:"checkpoint_uuid"`
	AgentID        string `json:"agent_id,omitempty"`
}

TaskCheckpoint contains the checkpoint information for a task

func ReadTaskCheckpoint

func ReadTaskCheckpoint(taskMetadataDir string) (*TaskCheckpoint, error)

ReadTaskCheckpoint reads the checkpoint file from the task metadata directory.

type TaskHookInput

type TaskHookInput struct {
	SessionID      string          `json:"session_id"`
	TranscriptPath string          `json:"transcript_path"`
	ToolUseID      string          `json:"tool_use_id"`
	ToolInput      json.RawMessage `json:"tool_input"`
}

TaskHookInput represents the JSON input from PreToolUse[Task] hook

type TranscriptPosition

type TranscriptPosition struct {
	LastUUID  string // Last non-empty UUID (from user/assistant messages)
	LineCount int    // Total number of lines
}

TranscriptPosition contains the position information for a transcript file.

func GetTranscriptPosition

func GetTranscriptPosition(path string) (TranscriptPosition, error)

GetTranscriptPosition reads a transcript file and returns the last UUID and line count. Returns empty position if file doesn't exist or is empty. Only considers UUIDs from actual messages (user/assistant), not summary rows which use leafUuid.

Directories

Path Synopsis
Package agent provides interfaces and types for integrating with coding agents.
Package agent provides interfaces and types for integrating with coding agents.
claudecode
Package claudecode implements the Agent interface for Claude Code.
Package claudecode implements the Agent interface for Claude Code.
geminicli
Package geminicli implements the Agent interface for Gemini CLI.
Package geminicli implements the Agent interface for Gemini CLI.
Package checkpoint provides types and interfaces for checkpoint storage.
Package checkpoint provides types and interfaces for checkpoint storage.
id
Package id provides the CheckpointID type for identifying checkpoints.
Package id provides the CheckpointID type for identifying checkpoints.
Package jsonutil provides JSON utilities with consistent formatting.
Package jsonutil provides JSON utilities with consistent formatting.
Package logging provides structured logging for the Entire CLI using slog.
Package logging provides structured logging for the Entire CLI using slog.
Package sessionid provides session ID formatting and transformation functions.
Package sessionid provides session ID formatting and transformation functions.
Package settings provides configuration loading for Entire.
Package settings provides configuration loading for Entire.
Package strategy provides an interface for different git strategies that can be used to save and manage Claude Code session changes.
Package strategy provides an interface for different git strategies that can be used to save and manage Claude Code session changes.
Package stringutil provides UTF-8 safe string manipulation utilities.
Package stringutil provides UTF-8 safe string manipulation utilities.
Package summarize provides AI-powered summarization of development sessions.
Package summarize provides AI-powered summarization of development sessions.
Package trailers provides parsing and formatting for Entire commit message trailers.
Package trailers provides parsing and formatting for Entire commit message trailers.
Package transcript provides shared types for parsing Claude Code transcripts.
Package transcript provides shared types for parsing Claude Code transcripts.
Package validation provides input validation functions for the Entire CLI.
Package validation provides input validation functions for the Entire CLI.

Jump to

Keyboard shortcuts

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