session

package
v0.3.13 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SessionStateDirName is the directory name for session state files within git common dir.
	SessionStateDirName = "entire-sessions"
)

Variables

This section is empty.

Functions

func MermaidDiagram added in v0.3.13

func MermaidDiagram() string

MermaidDiagram generates a Mermaid state diagram from the transition table. The diagram is derived by calling Transition() for representative context variants per phase/event, so it stays in sync with the implementation.

Types

type Action added in v0.3.13

type Action int

Action represents a side effect that should be performed after a transition. The caller is responsible for executing these -- the state machine only declares them.

const (
	ActionCondense               Action = iota // Condense session data to permanent storage
	ActionCondenseIfFilesTouched               // Condense only if FilesTouched is non-empty
	ActionDiscardIfNoFiles                     // Discard session if FilesTouched is empty
	ActionMigrateShadowBranch                  // Migrate shadow branch to new HEAD
	ActionWarnStaleSession                     // Warn user about stale session(s)
	ActionClearEndedAt                         // Clear EndedAt timestamp (session re-entering)
	ActionUpdateLastInteraction                // Update LastInteractionTime
)

func ApplyCommonActions added in v0.3.13

func ApplyCommonActions(state *State, result TransitionResult) []Action

ApplyCommonActions applies the common (non-strategy-specific) actions from a TransitionResult to the given State. It updates Phase, LastInteractionTime, and EndedAt as indicated by the transition.

Returns the subset of actions that require strategy-specific handling (e.g., ActionCondense, ActionMigrateShadowBranch, ActionWarnStaleSession). The caller is responsible for dispatching those.

func (Action) String added in v0.3.13

func (a Action) String() string

String returns a human-readable name for the action.

type Event added in v0.3.13

type Event int

Event represents something that happened to a session.

const (
	EventTurnStart    Event = iota // Agent begins working on a prompt
	EventTurnEnd                   // Agent finishes its turn
	EventGitCommit                 // A git commit was made (PostCommit hook)
	EventSessionStart              // Session process started (SessionStart hook)
	EventSessionStop               // Session process ended (SessionStop hook)
)

func (Event) String added in v0.3.13

func (e Event) String() string

String returns a human-readable name for the event.

type Phase added in v0.3.13

type Phase string

Phase represents the lifecycle stage of a session.

const (
	PhaseActive          Phase = "active"
	PhaseActiveCommitted Phase = "active_committed"
	PhaseIdle            Phase = "idle"
	PhaseEnded           Phase = "ended"
)

func PhaseFromString added in v0.3.13

func PhaseFromString(s string) Phase

PhaseFromString normalizes a phase string, treating empty or unknown values as PhaseIdle for backward compatibility with pre-state-machine session files.

func (Phase) IsActive added in v0.3.13

func (p Phase) IsActive() bool

IsActive reports whether the phase represents an active agent turn.

type PromptAttribution

type PromptAttribution struct {
	// CheckpointNumber is which checkpoint this was recorded before (1-indexed)
	CheckpointNumber int `json:"checkpoint_number"`

	// UserLinesAdded is lines added by user since the last checkpoint
	UserLinesAdded int `json:"user_lines_added"`

	// UserLinesRemoved is lines removed by user since the last checkpoint
	UserLinesRemoved int `json:"user_lines_removed"`

	// AgentLinesAdded is total agent lines added so far (base → last checkpoint).
	// Always 0 for checkpoint 1 since there's no previous checkpoint to measure against.
	AgentLinesAdded int `json:"agent_lines_added"`

	// AgentLinesRemoved is total agent lines removed so far (base → last checkpoint).
	// Always 0 for checkpoint 1 since there's no previous checkpoint to measure against.
	AgentLinesRemoved int `json:"agent_lines_removed"`

	// UserAddedPerFile tracks per-file user additions for accurate modification tracking.
	// This enables distinguishing user self-modifications from agent modifications.
	// See docs/architecture/attribution.md for details.
	UserAddedPerFile map[string]int `json:"user_added_per_file,omitempty"`
}

PromptAttribution captures line-level attribution data at the start of each prompt. By recording what changed since the last checkpoint BEFORE the agent works, we can accurately separate user edits from agent contributions.

type State

type State struct {
	// SessionID is the unique session identifier
	SessionID string `json:"session_id"`

	// CLIVersion is the version of the CLI that created this session
	CLIVersion string `json:"cli_version,omitempty"`

	// BaseCommit tracks the current shadow branch base. Initially set to HEAD when the
	// session starts, but updated on migration (pull/rebase) and after condensation.
	// Used for shadow branch naming and checkpoint storage — NOT for attribution.
	BaseCommit string `json:"base_commit"`

	// AttributionBaseCommit is the commit used as the reference point for attribution calculations.
	// Unlike BaseCommit (which tracks the shadow branch and moves with migration), this field
	// preserves the original base commit so deferred condensation can correctly calculate
	// agent vs human line attribution. Updated only after successful condensation.
	AttributionBaseCommit string `json:"attribution_base_commit,omitempty"`

	// WorktreePath is the absolute path to the worktree root
	WorktreePath string `json:"worktree_path,omitempty"`

	// WorktreeID is the internal git worktree identifier (empty for main worktree)
	// Derived from .git/worktrees/<name>/, stable across git worktree move
	WorktreeID string `json:"worktree_id,omitempty"`

	// StartedAt is when the session was started
	StartedAt time.Time `json:"started_at"`

	// EndedAt is when the session was explicitly closed by the user.
	// nil means the session is still active or was not cleanly closed.
	EndedAt *time.Time `json:"ended_at,omitempty"`

	// Phase is the lifecycle stage of this session (see phase.go).
	// Empty means idle (backward compat with pre-state-machine files).
	Phase Phase `json:"phase,omitempty"`

	// PendingCheckpointID is the checkpoint ID for the current commit cycle.
	// Generated once when first needed, reused across all commits in the session.
	PendingCheckpointID string `json:"pending_checkpoint_id,omitempty"`

	// LastInteractionTime is updated on every hook invocation.
	// Used for stale session detection in "entire doctor".
	LastInteractionTime *time.Time `json:"last_interaction_time,omitempty"`

	// StepCount is the number of checkpoints/steps created in this session.
	// JSON tag kept as "checkpoint_count" for backward compatibility with existing state files.
	StepCount int `json:"checkpoint_count"`

	// CheckpointTranscriptStart is the transcript line offset where the current
	// checkpoint cycle began. Set to 0 at session start, updated to current
	// transcript length after each condensation. Used to scope the transcript
	// for checkpoint condensation: "everything since last checkpoint".
	CheckpointTranscriptStart int `json:"checkpoint_transcript_start,omitempty"`

	// Deprecated: CondensedTranscriptLines is replaced by CheckpointTranscriptStart.
	// Kept for backward compatibility with existing state files.
	// Use NormalizeAfterLoad() to migrate.
	CondensedTranscriptLines int `json:"condensed_transcript_lines,omitempty"`

	// UntrackedFilesAtStart tracks files that existed at session start (to preserve during rewind)
	UntrackedFilesAtStart []string `json:"untracked_files_at_start,omitempty"`

	// FilesTouched tracks files modified/created/deleted during this session
	FilesTouched []string `json:"files_touched,omitempty"`

	// LastCheckpointID is the checkpoint ID from last condensation, reused for subsequent commits without new content
	LastCheckpointID id.CheckpointID `json:"last_checkpoint_id,omitempty"`

	// AgentType identifies the agent that created this session (e.g., "Claude Code", "Gemini CLI", "Cursor")
	AgentType agent.AgentType `json:"agent_type,omitempty"`

	// Token usage tracking (accumulated across all checkpoints in this session)
	TokenUsage *agent.TokenUsage `json:"token_usage,omitempty"`

	// Deprecated: TranscriptLinesAtStart is replaced by CheckpointTranscriptStart.
	// Kept for backward compatibility with existing state files.
	TranscriptLinesAtStart int `json:"transcript_lines_at_start,omitempty"`

	// TranscriptIdentifierAtStart is the last transcript identifier when the session started.
	// Used for identifier-based transcript scoping (UUID for Claude, message ID for Gemini).
	TranscriptIdentifierAtStart string `json:"transcript_identifier_at_start,omitempty"`

	// TranscriptPath is the path to the live transcript file (for mid-session commit detection)
	TranscriptPath string `json:"transcript_path,omitempty"`

	// FirstPrompt is the first user prompt that started this session (truncated for display)
	FirstPrompt string `json:"first_prompt,omitempty"`

	// PromptAttributions tracks user and agent line changes at each prompt start.
	// This enables accurate attribution by capturing user edits between checkpoints.
	PromptAttributions []PromptAttribution `json:"prompt_attributions,omitempty"`

	// PendingPromptAttribution holds attribution calculated at prompt start (before agent runs).
	// This is moved to PromptAttributions when SaveChanges is called.
	PendingPromptAttribution *PromptAttribution `json:"pending_prompt_attribution,omitempty"`
}

State represents the state of an active session. This is stored in .git/entire-sessions/<session-id>.json

func (*State) NormalizeAfterLoad added in v0.3.13

func (s *State) NormalizeAfterLoad()

NormalizeAfterLoad applies backward-compatible migrations to state loaded from disk. Call this after deserializing a State from JSON.

type StateStore

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

StateStore provides low-level operations for managing session state files.

StateStore is a primitive for session state persistence. It is NOT the same as the Sessions interface - it only handles state files in .git/entire-sessions/, not the full session data which includes checkpoint content.

Use StateStore directly in strategies for performance-critical state operations. Use the Sessions interface (when implemented) for high-level session management.

func NewStateStore

func NewStateStore() (*StateStore, error)

NewStateStore creates a new state store. Uses the git common dir to store session state (shared across worktrees).

func NewStateStoreWithDir

func NewStateStoreWithDir(stateDir string) *StateStore

NewStateStoreWithDir creates a new state store with a custom directory. This is useful for testing.

func (*StateStore) Clear

func (s *StateStore) Clear(ctx context.Context, sessionID string) error

Clear removes the session state file for the given session ID.

func (*StateStore) List

func (s *StateStore) List(ctx context.Context) ([]*State, error)

List returns all session states.

func (*StateStore) Load

func (s *StateStore) Load(ctx context.Context, sessionID string) (*State, error)

Load loads the session state for the given session ID. Returns (nil, nil) when session file doesn't exist (not an error condition).

func (*StateStore) RemoveAll

func (s *StateStore) RemoveAll() error

RemoveAll removes the entire session state directory. This is used during uninstall to completely remove all session state.

func (*StateStore) Save

func (s *StateStore) Save(ctx context.Context, state *State) error

Save saves the session state atomically.

type TransitionContext added in v0.3.13

type TransitionContext struct {
	HasFilesTouched    bool // len(FilesTouched) > 0
	IsRebaseInProgress bool // .git/rebase-merge/ or .git/rebase-apply/ exists
}

TransitionContext provides read-only context for transitions that need to inspect session state without mutating it.

type TransitionResult added in v0.3.13

type TransitionResult struct {
	NewPhase Phase
	Actions  []Action
}

TransitionResult holds the outcome of a state machine transition.

func Transition added in v0.3.13

func Transition(current Phase, event Event, ctx TransitionContext) TransitionResult

Transition computes the next phase and required actions given the current phase and an event. This is a pure function with no side effects.

Empty or unknown phase values are normalized to PhaseIdle for backward compatibility with session state files created before phase tracking.

Jump to

Keyboard shortcuts

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