session

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTag

func AddTag(sess *Session, tag string)

AddTag adds a tag to a session.

func BuildBM25Score

func BuildBM25Score(queryTerms []string, doc string, docLen int, avgDocLen float64, df map[string]int, totalDocs int) float64

BuildBM25Score computes the BM25 score for a document against query terms. Uses standard parameters k1=1.2, b=0.75.

func CheckForRecovery

func CheckForRecovery() []string

CheckForRecovery looks for any WAL files and offers recovery. Returns session IDs that have WAL files.

func CleanOldSessions

func CleanOldSessions(maxAge time.Duration) (int, error)

CleanOldSessions removes sessions older than the given duration.

func CompressOldSessions

func CompressOldSessions(maxAge time.Duration) (int, error)

CompressOldSessions gzips session files older than maxAge. Returns the number of sessions compressed.

func ComputeChecksum

func ComputeChecksum(sess *Session) string

ComputeChecksum returns a SHA-256 hash of the session content.

func Diff

func Diff(a, b *Session) string

Diff compares two sessions and returns the differences as a human-readable string.

func Export

func Export(s *Session, format string, redact bool) ([]byte, error)

Export renders a session in the specified format, optionally redacting secrets.

func ExportHTML

func ExportHTML(session *ExportedSession) string

ExportHTML renders a session as a styled HTML page with dark/light theme support.

func ExportJSON

func ExportJSON(session *ExportedSession) string

ExportJSON renders a session as full structured JSON suitable for re-import.

func ExportMarkdown

func ExportMarkdown(session *ExportedSession) string

ExportMarkdown renders a session as a readable Markdown conversation log.

func ExportReplay

func ExportReplay(session *ExportedSession) string

ExportReplay renders a session as JSONL suitable for step-by-step replay.

func ExportToMarkdown

func ExportToMarkdown(sess *Session) string

ExportToMarkdown exports a session as readable markdown.

func ExtractDecisions

func ExtractDecisions(messages []Message) []string

ExtractDecisions scans assistant messages for decision-like patterns.

func ExtractGoal

func ExtractGoal(messages []Message) string

ExtractGoal returns the primary goal from the first user message.

func ExtractPendingTasks

func ExtractPendingTasks(messages []Message) []string

ExtractPendingTasks identifies tasks that are mentioned but not yet completed.

func ExtractUserPrompts

func ExtractUserPrompts(steps []ReplayStep) []string

ExtractUserPrompts returns only the user messages from a slice of replay steps.

func FormatCheckpointList

func FormatCheckpointList(checkpoints []Checkpoint) string

FormatCheckpointList produces a human-readable list of checkpoints for selection.

func FormatDivergences

func FormatDivergences(divs []Divergence) string

FormatDivergences renders a human-readable summary of divergences found during replay.

func FormatHandover

func FormatHandover(handover *Handover) string

FormatHandover produces a human-readable string representation of a handover.

func FormatRecoveryCandidates

func FormatRecoveryCandidates(candidates []RecoveryCandidate) string

FormatRecoveryCandidates formats recovery candidates for display.

func FormatResults

func FormatResults(results []FTSResult, showContext int) string

FormatResults formats search results for terminal display.

func GenerateHandoverPrompt

func GenerateHandoverPrompt(handover *Handover) string

GenerateHandoverPrompt produces a structured markdown prompt that can be fed to a receiving model so it understands the work context.

func GenerateShareLink(session *ExportedSession) string

GenerateShareLink creates a deterministic share ID from the session content hash.

func MigrateToJSONL

func MigrateToJSONL(id string) error

MigrateToJSONL converts a legacy JSON session to JSONL format.

func RedactSecrets

func RedactSecrets(text string) string

RedactSecrets replaces detected secrets in text with [REDACTED].

func RemoveTag

func RemoveTag(sess *Session, tag string)

RemoveTag removes a tag from a session.

func RewindLastExchange

func RewindLastExchange(sess *Session) error

RewindLastExchange removes the most recent user+assistant exchange.

func RewindTo

func RewindTo(sess *Session, checkpointIndex int) error

RewindTo truncates the session to the given checkpoint index. All messages after the checkpoint are removed.

func Save

func Save(s *Session) error

Save persists a session to disk atomically. Writes to a temp file first, then renames — a crash at any point leaves either the old valid file or the new valid file, never a partial write.

func SaveHandover

func SaveHandover(handover *Handover, path string) error

SaveHandover persists a handover to disk as JSON.

func SaveMessages

func SaveMessages(path string, messages []Message) error

SaveMessages serializes a slice of conversation messages to a JSON file atomically. This is a lightweight alternative to full Session persistence for callers that only need message-level save/restore.

func SessionPath

func SessionPath(projectDir, sessionID string) string

SessionPath returns the file path for a session within a project directory. Sessions are stored under .hawk/sessions/{id}.json.

func Stats

func Stats(sess *Session) map[string]interface{}

SessionStats computes lightweight stats without full validation.

Types

type AutoSaver

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

AutoSaver periodically saves sessions and tracks session metadata.

func NewAutoSaver

func NewAutoSaver(interval time.Duration, saveFn func()) *AutoSaver

NewAutoSaver creates an auto-saver that triggers saveFn at the given interval.

func (*AutoSaver) Reset

func (as *AutoSaver) Reset()

Reset restarts the auto-save timer.

func (*AutoSaver) Stop

func (as *AutoSaver) Stop()

Stop stops the auto-saver.

func (*AutoSaver) Touch

func (as *AutoSaver) Touch()

Touch resets the timer (called on activity to delay the save).

type BatchedWAL

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

BatchedWAL wraps a WAL and batches Append calls, flushing to disk on a timer (100ms) or when the buffer reaches 10 entries. This reduces the number of f.Sync() calls from one-per-append to one-per-flush.

LOCK ORDERING: b.mu must always be acquired before b.wal.mu. The timer callback acquires b.mu then calls flushLocked() which acquires b.wal.mu. Never acquire b.mu while holding b.wal.mu.

func NewBatchedWAL

func NewBatchedWAL(wal *WAL) *BatchedWAL

NewBatchedWAL wraps an existing WAL with batching.

func (*BatchedWAL) Append

func (b *BatchedWAL) Append(msg Message) error

Append buffers a message and flushes if the buffer is full.

func (*BatchedWAL) Close

func (b *BatchedWAL) Close() error

Close flushes remaining entries and closes the underlying WAL.

func (*BatchedWAL) Flush

func (b *BatchedWAL) Flush() error

Flush writes all buffered messages to the underlying WAL.

type Checkpoint

type Checkpoint struct {
	Index      int       `json:"index"`
	MessageID  string    `json:"message_id,omitempty"`
	Role       string    `json:"role"`
	Preview    string    `json:"preview"`
	ToolName   string    `json:"tool_name,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
	TokenCount int       `json:"token_count,omitempty"`
}

Checkpoint represents a restorable point in the conversation.

func ListCheckpoints

func ListCheckpoints(sess *Session) []Checkpoint

ListCheckpoints extracts interactive restore points from a session. Returns user/assistant message boundaries where rewind is safe.

type CheckpointManager

type CheckpointManager struct {
	Checkpoints    []*SessionCheckpoint `json:"checkpoints"`
	MaxCheckpoints int                  `json:"max_checkpoints"`
	Dir            string               `json:"dir"`
	// contains filtered or unexported fields
}

CheckpointManager manages session checkpoints with persistence.

func NewCheckpointManager

func NewCheckpointManager(dir string) *CheckpointManager

NewCheckpointManager creates a CheckpointManager that persists to dir.

func (*CheckpointManager) AutoCheckpoint

func (cm *CheckpointManager) AutoCheckpoint(messages []Message, files []string) (*SessionCheckpoint, error)

AutoCheckpoint creates an automatic checkpoint named by timestamp.

func (*CheckpointManager) Create

func (cm *CheckpointManager) Create(name, description string, messages []Message, files []string) (*SessionCheckpoint, error)

Create saves a named checkpoint capturing current conversation and file state.

func (*CheckpointManager) Delete

func (cm *CheckpointManager) Delete(id string) error

Delete removes a checkpoint by ID.

func (*CheckpointManager) DiffFromCheckpoint

func (cm *CheckpointManager) DiffFromCheckpoint(checkpointID string, currentFiles []string) []string

DiffFromCheckpoint returns a list of files that changed since the given checkpoint.

func (*CheckpointManager) FormatCheckpoints

func (cm *CheckpointManager) FormatCheckpoints() string

FormatCheckpoints returns a human-readable display of all checkpoints.

func (*CheckpointManager) Get

Get returns a checkpoint by ID, or nil if not found.

func (*CheckpointManager) List

func (cm *CheckpointManager) List() []*SessionCheckpoint

List returns all checkpoints in chronological order.

func (*CheckpointManager) Load

func (cm *CheckpointManager) Load() error

Load reads the checkpoint index from disk.

func (*CheckpointManager) Prune

func (cm *CheckpointManager) Prune()

Prune removes old auto-checkpoints, keeping all named checkpoints and the most recent auto-checkpoints within MaxCheckpoints total.

func (*CheckpointManager) Restore

func (cm *CheckpointManager) Restore(checkpointID string) ([]Message, error)

Restore loads a checkpoint and restores file states, returning the messages at that point.

func (*CheckpointManager) Save

func (cm *CheckpointManager) Save() error

Save persists the checkpoint index to disk.

func (*CheckpointManager) ShouldAutoCheckpoint

func (cm *CheckpointManager) ShouldAutoCheckpoint(messageCount, toolCalls int) bool

ShouldAutoCheckpoint returns true if an auto-checkpoint should be taken based on message count or tool call count thresholds.

type CheckpointTrigger

type CheckpointTrigger int

CheckpointTrigger classifies events that may trigger a checkpoint.

const (
	TriggerFileWrite    CheckpointTrigger = iota // file was modified
	TriggerToolError                             // tool execution failed
	TriggerUserFeedback                          // user gave correction
	TriggerPlanChange                            // plan/subtask status changed
	TriggerContextShift                          // topic changed significantly
)

func (CheckpointTrigger) String

func (ct CheckpointTrigger) String() string

String returns a human-readable name for the trigger.

type CoherenceState

type CoherenceState struct {
	Threads         []*SessionThread  `json:"threads"`
	Pivots          []Pivot           `json:"pivots"`
	LastUpdatedTurn int               `json:"last_updated_turn"`
	CurrentAct      ConversationalAct `json:"current_act"`
	IntentSummary   string            `json:"intent_summary"`
}

type CoherenceTracker

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

func NewCoherenceTracker

func NewCoherenceTracker(updateInterval, maxThreads int) *CoherenceTracker

func (*CoherenceTracker) ClassifyAct

func (ct *CoherenceTracker) ClassifyAct(message string) ConversationalAct

func (*CoherenceTracker) FormatForPrompt

func (ct *CoherenceTracker) FormatForPrompt() string

func (*CoherenceTracker) GetState

func (ct *CoherenceTracker) GetState() CoherenceState

func (*CoherenceTracker) RecordPivot

func (ct *CoherenceTracker) RecordPivot(turn int, from, to string)

func (*CoherenceTracker) UpdateIntent

func (ct *CoherenceTracker) UpdateIntent(message string, turn int)

type ConversationalAct

type ConversationalAct string
const (
	ActQuestion  ConversationalAct = "question"
	ActInstruct  ConversationalAct = "instruct"
	ActCorrect   ConversationalAct = "correct"
	ActElaborate ConversationalAct = "elaborate"
	ActConfirm   ConversationalAct = "confirm"
	ActPivot     ConversationalAct = "pivot"
	ActExplore   ConversationalAct = "explore"
	ActUnknown   ConversationalAct = "unknown"
)

type Divergence

type Divergence struct {
	StepIndex int    `json:"step_index"`
	Expected  string `json:"expected"`
	Got       string `json:"got"`
	Type      string `json:"type"` // "content_mismatch", "tool_mismatch", "error"
}

Divergence records a mismatch between expected and actual output at a step.

func DetectDivergence

func DetectDivergence(expected, actual string) *Divergence

DetectDivergence compares expected and actual output and returns a Divergence if they differ. Returns nil if they match.

type Entry

type Entry struct {
	ID        string
	Preview   string
	CWD       string
	UpdatedAt time.Time
}

Entry is a summary of a saved session for listing.

func List

func List() ([]Entry, error)

List returns all saved sessions, newest first. Uses file modification time for sorting to avoid loading all sessions.

type ExportFormat

type ExportFormat string

ExportFormat defines the output format for session exports.

const (
	// FormatMarkdown exports as a readable conversation log.
	FormatMarkdown ExportFormat = "markdown"
	// FormatJSON exports as full structured JSON.
	FormatJSON ExportFormat = "json"
	// FormatHTML exports as a styled HTML page.
	FormatHTML ExportFormat = "html"
	// FormatReplay exports as JSONL for reproducible replay.
	FormatReplay ExportFormat = "replay"
)

type ExportedMessage

type ExportedMessage struct {
	Role       string    `json:"role"`
	Content    string    `json:"content"`
	Timestamp  time.Time `json:"timestamp"`
	ToolName   string    `json:"tool_name,omitempty"`
	ToolResult string    `json:"tool_result,omitempty"`
	TokenCount int       `json:"token_count,omitempty"`
}

ExportedMessage is a single message within an exported session.

type ExportedSession

type ExportedSession struct {
	ID        string             `json:"id"`
	Model     string             `json:"model"`
	Provider  string             `json:"provider"`
	CreatedAt time.Time          `json:"created_at"`
	Messages  []ExportedMessage  `json:"messages"`
	Metadata  map[string]string  `json:"metadata,omitempty"`
	Stats     SessionExportStats `json:"stats"`
}

ExportedSession is a portable representation of a session.

func Import

func Import(data string, format ExportFormat) (*ExportedSession, error)

Import parses an exported session from the given data and format.

func ImportFromAider

func ImportFromAider(historyData string) (*ExportedSession, error)

ImportFromAider imports a session from Aider's chat history format. Aider uses a Markdown-like format with role markers like "#### user" and "#### assistant".

func ImportFromClaude

func ImportFromClaude(jsonlData string) (*ExportedSession, error)

ImportFromClaude imports a session from Claude Code's JSONL format.

func RedactSensitive

func RedactSensitive(session *ExportedSession) *ExportedSession

RedactSensitive returns a copy of the session with sensitive values replaced by [REDACTED].

type FTSResult

type FTSResult struct {
	SessionID    string
	MessageIndex int
	Role         string
	Content      string
	Preview      string
	Score        float64
	Highlights   []Highlight
	Timestamp    time.Time
}

FTSResult represents a single match from a full-text search query.

type ForkCheckpoint

type ForkCheckpoint struct {
	StepID    string    `json:"step_id"`
	ThreadID  string    `json:"thread_id"`
	Data      []byte    `json:"data"`
	Kind      string    `json:"kind"`
	CreatedAt time.Time `json:"created_at"`
}

type ForkOptions

type ForkOptions struct {
	SourceThreadID string
	FromStepID     string
	NewThreadName  string
}

type ForkableStore

type ForkableStore interface {
	GetForkCheckpoints(threadID string) ([]ForkCheckpoint, error)
	CreateThread(name string) (string, error)
	CopyCheckpoints(from string, to string, upToStep string) error
}

type Handover

type Handover struct {
	SessionID string          `json:"session_id"`
	FromModel string          `json:"from_model"`
	ToModel   string          `json:"to_model"`
	Context   HandoverContext `json:"context"`
	CreatedAt time.Time       `json:"created_at"`
	Status    string          `json:"status"`
}

Handover represents a session transfer between models, machines, or team members.

func LoadHandover

func LoadHandover(path string) (*Handover, error)

LoadHandover reads a handover from disk.

type HandoverContext

type HandoverContext struct {
	Goal                  string   `json:"goal"`
	Progress              string   `json:"progress"`
	FilesModified         []string `json:"files_modified"`
	PendingTasks          []string `json:"pending_tasks"`
	Warnings              []string `json:"warnings"`
	KeyDecisions          []string `json:"key_decisions"`
	CurrentState          string   `json:"current_state"`
	TokensBudgetRemaining int      `json:"tokens_budget_remaining"`
}

HandoverContext captures the full state needed to continue work.

type HandoverManager

type HandoverManager struct {
	Handovers []*Handover
	// contains filtered or unexported fields
}

HandoverManager coordinates handover creation and tracking.

func NewHandoverManager

func NewHandoverManager() *HandoverManager

NewHandoverManager creates a new HandoverManager.

func (*HandoverManager) AcceptHandover

func (m *HandoverManager) AcceptHandover(handover *Handover, toModel string) error

AcceptHandover marks a handover as accepted by the receiving model.

func (*HandoverManager) PrepareHandover

func (m *HandoverManager) PrepareHandover(sessionID, fromModel string, messages []Message, files []string) *Handover

PrepareHandover creates a Handover from a session's messages and file list. It extracts the goal, summarizes progress, lists modified files, identifies pending work, and records key decisions.

type Highlight

type Highlight struct {
	Start int
	End   int
}

Highlight marks a matched region within content.

func HighlightMatches

func HighlightMatches(content string, query string) []Highlight

HighlightMatches finds positions of query terms in content for highlighting.

type IndexedMessage

type IndexedMessage struct {
	Index     int
	Role      string
	Preview   string // first 100 chars
	Timestamp time.Time
}

IndexedMessage stores metadata about a message for search results.

type InputProvenance

type InputProvenance string
const (
	ProvenanceExternalUser   InputProvenance = "external_user"
	ProvenanceInterSession   InputProvenance = "inter_session"
	ProvenanceInternalSystem InputProvenance = "internal_system"
	ProvenanceCron           InputProvenance = "cron"
	ProvenanceWebhook        InputProvenance = "webhook"
)

type IntegrityCheck

type IntegrityCheck struct {
	Valid    bool           `json:"valid"`
	Warnings []string       `json:"warnings,omitempty"`
	Errors   []string       `json:"errors,omitempty"`
	Stats    IntegrityStats `json:"stats"`
}

IntegrityCheck validates a session's structural integrity.

func ValidateIntegrity

func ValidateIntegrity(sess *Session) *IntegrityCheck

ValidateIntegrity checks a session for structural problems.

type IntegrityStats

type IntegrityStats struct {
	MessageCount      int `json:"message_count"`
	UserMessages      int `json:"user_messages"`
	AssistantMessages int `json:"assistant_messages"`
	ToolUses          int `json:"tool_uses"`
	ToolResults       int `json:"tool_results"`
	OrphanedResults   int `json:"orphaned_results"`
	EmptyMessages     int `json:"empty_messages"`
}

IntegrityStats holds session statistics found during validation.

type InterruptionType

type InterruptionType string

InterruptionType classifies what was happening when the session stopped.

const (
	InterruptionNone          InterruptionType = "none"
	InterruptionMidTool       InterruptionType = "mid_tool"       // tool was executing
	InterruptionMidResponse   InterruptionType = "mid_response"   // assistant was writing a response
	InterruptionAwaitingInput InterruptionType = "awaiting_input" // waiting for user input
	InterruptionToolError     InterruptionType = "tool_error"     // tool execution failed
	InterruptionPermissionAsk InterruptionType = "permission_ask" // waiting for permission approval
)

type LockFile

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

LockFile prevents double-opening a session.

func AcquireLock

func AcquireLock(sessionID string) (*LockFile, error)

AcquireLock creates a lock file for the session. Returns error if already locked.

func (*LockFile) Refresh

func (l *LockFile) Refresh()

Refresh updates the lock file timestamp to prevent it from going stale.

func (*LockFile) Release

func (l *LockFile) Release()

Release removes the lock file.

type Message

type Message struct {
	Role       string            `json:"role"`
	Content    string            `json:"content,omitempty"`
	ToolUse    []types.ToolCall  `json:"tool_use,omitempty"`
	ToolResult *types.ToolResult `json:"tool_result,omitempty"`
}

Message is a persisted conversation message.

func LoadMessages

func LoadMessages(path string) ([]Message, error)

LoadMessages deserializes conversation messages from a JSON file.

type MessageRecord

type MessageRecord struct {
	ID        int64
	SessionID string
	Role      string
	Content   string
	ToolUseID string
	ToolName  string
	IsError   bool
	Tokens    int
	CreatedAt time.Time
}

MessageRecord represents a single message within a session.

type Pivot

type Pivot struct {
	Turn int    `json:"turn"`
	From string `json:"from"`
	To   string `json:"to"`
}

type ProvenanceTag

type ProvenanceTag struct {
	Source    InputProvenance `json:"source"`
	SessionID string          `json:"session_id,omitempty"`
	Channel   string          `json:"channel,omitempty"`
	Trusted   bool            `json:"trusted"`
}

func NewCronProvenance

func NewCronProvenance() ProvenanceTag

func NewInterSessionProvenance

func NewInterSessionProvenance(fromSession string) ProvenanceTag

func NewSystemProvenance

func NewSystemProvenance() ProvenanceTag

func NewUserProvenance

func NewUserProvenance() ProvenanceTag

func NewWebhookProvenance

func NewWebhookProvenance(channel string) ProvenanceTag

func (ProvenanceTag) RequiresSecurityWrap

func (p ProvenanceTag) RequiresSecurityWrap() bool

type RecoveryCandidate

type RecoveryCandidate struct {
	SessionID       string
	CWD             string
	Model           string
	Provider        string
	Interruption    InterruptionType
	LastToolName    string
	LastToolID      string
	MessageCount    int
	LastActivity    time.Time
	UnresolvedTools []string // tool_use IDs without matching tool_result
	Age             time.Duration
}

RecoveryCandidate represents an interrupted session that can be resumed.

func ScanForRecovery

func ScanForRecovery() []RecoveryCandidate

ScanForRecovery scans the sessions directory for sessions that may have been interrupted (have WAL files or unresolved tool calls).

type Replay

type Replay struct {
	SessionID   string       `json:"session_id"`
	Steps       []ReplayStep `json:"steps"`
	Speed       float64      `json:"speed"` // 1.0=realtime, 0=instant
	Breakpoints []int        `json:"breakpoints,omitempty"`
	Status      string       `json:"status"` // "idle", "playing", "paused", "stopped", "done"
	CurrentStep int          `json:"current_step"`
	// contains filtered or unexported fields
}

Replay manages the re-execution of a previous session's prompts.

func LoadFromExport

func LoadFromExport(data string) (*Replay, error)

LoadFromExport parses a JSONL replay format string into a Replay instance. Each line must be a JSON object with fields matching the replayEntry structure used by ExportReplay (seq, role, content, tool_name, delta_ms, timestamp).

func NewReplay

func NewReplay(sessionID string) *Replay

NewReplay creates a new Replay instance for the given session ID.

func (*Replay) FormatReplayStatus

func (r *Replay) FormatReplayStatus() string

FormatReplayStatus returns a human-readable progress display for the replay.

func (*Replay) Pause

func (r *Replay) Pause()

Pause pauses the replay execution.

func (*Replay) Play

func (r *Replay) Play(ctx context.Context, executeFn func(string) (string, error)) (*ReplayResult, error)

Play re-executes all user prompts in the replay using the provided execute function. It compares assistant responses against the original to detect divergences. The executeFn takes a user prompt and returns the model's response.

func (*Replay) PlayStep

func (r *Replay) PlayStep(ctx context.Context, step int, executeFn func(string) (string, error)) (*ReplayStep, error)

PlayStep re-executes a single step at the given index.

func (*Replay) RemoveBreakpoint

func (r *Replay) RemoveBreakpoint(stepIndex int)

RemoveBreakpoint removes a breakpoint at the given step index.

func (*Replay) Resume

func (r *Replay) Resume()

Resume resumes a paused replay.

func (*Replay) SetBreakpoint

func (r *Replay) SetBreakpoint(stepIndex int)

SetBreakpoint adds a breakpoint at the given step index.

func (*Replay) Stop

func (r *Replay) Stop()

Stop terminates the replay execution.

type ReplayResult

type ReplayResult struct {
	OriginalSteps int           `json:"original_steps"`
	ReplayedSteps int           `json:"replayed_steps"`
	Divergences   []Divergence  `json:"divergences,omitempty"`
	Duration      time.Duration `json:"duration"`
}

ReplayResult summarizes the outcome of a full replay execution.

type ReplayStep

type ReplayStep struct {
	Index            int           `json:"index"`
	Role             string        `json:"role"`
	Content          string        `json:"content"`
	ToolName         string        `json:"tool_name,omitempty"`
	ToolArgs         string        `json:"tool_args,omitempty"`
	OriginalDuration time.Duration `json:"original_duration"`
	Timestamp        time.Time     `json:"timestamp"`
}

ReplayStep represents a single step in a session replay.

type SQLiteStore

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

SQLiteStore provides SQLite-backed session persistence.

func NewSQLiteStore

func NewSQLiteStore(dbPath string) (*SQLiteStore, error)

NewSQLiteStore opens (or creates) the SQLite database at dbPath and runs any pending migrations. The driver must already be registered with database/sql (e.g., via import _ "modernc.org/sqlite").

func (*SQLiteStore) AppendMessage

func (s *SQLiteStore) AppendMessage(sessionID string, msg *MessageRecord) error

AppendMessage adds a message to a session and updates the session's updated_at timestamp and token totals.

func (*SQLiteStore) Close

func (s *SQLiteStore) Close() error

Close closes the underlying database connection.

func (*SQLiteStore) Compact

func (s *SQLiteStore) Compact(sessionID string, keepLast int) error

Compact removes old messages from a session, keeping only the last keepLast messages. This is useful for long-running sessions where older context is no longer needed.

func (*SQLiteStore) CreateSession

func (s *SQLiteStore) CreateSession(sess *SessionRecord) error

CreateSession inserts a new session record.

func (*SQLiteStore) DeleteSession

func (s *SQLiteStore) DeleteSession(id string) error

DeleteSession removes a session and all its messages.

func (*SQLiteStore) ForkSession

func (s *SQLiteStore) ForkSession(originalID, newID string) error

ForkSession creates a copy of a session with a new ID, duplicating all messages. The new session's parent_id points to the original.

func (*SQLiteStore) GetMessages

func (s *SQLiteStore) GetMessages(sessionID string) ([]*MessageRecord, error)

GetMessages retrieves all messages for a session, ordered by creation time.

func (*SQLiteStore) GetSession

func (s *SQLiteStore) GetSession(id string) (*SessionRecord, error)

GetSession retrieves a session by ID.

func (*SQLiteStore) GetSessionStats

func (s *SQLiteStore) GetSessionStats(id string) (*SessionStats, error)

GetSessionStats returns aggregate statistics for a session.

func (*SQLiteStore) ListSessions

func (s *SQLiteStore) ListSessions(projectDir string, limit int) ([]*SessionRecord, error)

ListSessions returns sessions for a project directory, ordered by most recently updated. If projectDir is empty, all sessions are returned. limit <= 0 means no limit.

func (*SQLiteStore) SearchSessions

func (s *SQLiteStore) SearchSessions(query string) ([]*SessionRecord, error)

SearchSessions performs a full-text search across message content and returns sessions that contain matching messages. Requires the FTS migration to have been applied (migration 2).

func (*SQLiteStore) UpdateSession

func (s *SQLiteStore) UpdateSession(id string, updates map[string]interface{}) error

UpdateSession updates specific fields of a session. Supported keys: status, title, model, provider, total_tokens, total_cost_usd.

type SearchEngine

type SearchEngine struct {
	SessionDir string
	Index      map[string]*SessionIndex
	// contains filtered or unexported fields
}

SearchEngine provides full-text search across hawk sessions/conversations.

func NewSearchEngine

func NewSearchEngine(sessionDir string) *SearchEngine

NewSearchEngine creates a new SearchEngine for the given session directory.

func (*SearchEngine) IndexSession

func (se *SearchEngine) IndexSession(sessionID string, messages []Message) error

IndexSession tokenizes messages and builds an inverted index for the session.

func (*SearchEngine) RebuildIndex

func (se *SearchEngine) RebuildIndex() error

RebuildIndex walks the session directory and re-indexes all sessions from their JSONL files.

func (*SearchEngine) Search

func (se *SearchEngine) Search(query string, opts SearchOptions) []FTSResult

Search performs a full-text search using BM25 scoring across indexed sessions.

func (*SearchEngine) SearchRegex

func (se *SearchEngine) SearchRegex(pattern string, opts SearchOptions) []FTSResult

SearchRegex performs a regex-based search for exact pattern matching.

type SearchOptions

type SearchOptions struct {
	MaxResults    int
	SessionFilter string
	RoleFilter    string
	DateAfter     time.Time
	DateBefore    time.Time
}

SearchOptions configures a search query.

type SearchResult

type SearchResult struct {
	SessionID string
	MsgIndex  int
	Role      string
	Preview   string
}

SearchResult represents a match found in session search.

func SearchSessions

func SearchSessions(query string, maxResults int) ([]SearchResult, error)

SearchSessions searches across all sessions for content.

type Session

type Session struct {
	ID        string    `json:"id"`
	Model     string    `json:"model"`
	Provider  string    `json:"provider"`
	CWD       string    `json:"cwd,omitempty"`
	Name      string    `json:"name,omitempty"`
	Messages  []Message `json:"messages"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Session is a persisted conversation.

func DecompressSession

func DecompressSession(id string) (*Session, error)

DecompressSession decompresses a .jsonl.gz file for loading.

func Fork

func Fork(sessionID string, atIndex int) (*Session, error)

Fork creates a new session branched from the given session at the given message index. All messages up to and including atIndex are copied to the new session.

func Load

func Load(id string) (*Session, error)

Load reads a session from disk, supporting both JSONL and legacy JSON formats.

func LoadLatest

func LoadLatest() (*Session, error)

LoadLatest returns the newest saved session regardless of CWD.

func LoadLatestForCWD

func LoadLatestForCWD(cwd string) (*Session, error)

LoadLatestForCWD returns the newest saved session for cwd.

func RecoverFromWAL

func RecoverFromWAL(sessionID string) (*Session, error)

RecoverFromWAL rebuilds a session from a WAL file if one exists. Returns nil if no WAL exists.

func ResumeSession

func ResumeSession(sessionID string) (*Session, string, error)

ResumeSession loads a session for resumption, cleaning up any orphaned state. Returns the session, a summary of what was recovered, and any errors.

type SessionCheckpoint

type SessionCheckpoint struct {
	ID           string            `json:"id"`
	Name         string            `json:"name"`
	MessageCount int               `json:"message_count"`
	TokenCount   int               `json:"token_count"`
	FilesState   map[string]string `json:"files_state"` // file path → content hash
	Timestamp    time.Time         `json:"timestamp"`
	Description  string            `json:"description"`
	Auto         bool              `json:"auto"`
}

SessionCheckpoint represents a saved point-in-time state of a conversation, enabling rollback to any previously saved checkpoint.

type SessionExportStats

type SessionExportStats struct {
	TotalMessages     int           `json:"total_messages"`
	UserMessages      int           `json:"user_messages"`
	AssistantMessages int           `json:"assistant_messages"`
	ToolCalls         int           `json:"tool_calls"`
	TotalTokens       int           `json:"total_tokens"`
	Duration          time.Duration `json:"duration"`
}

SessionExportStats summarizes session metrics.

func CalculateStats

func CalculateStats(messages []ExportedMessage) SessionExportStats

CalculateStats computes session statistics from a slice of messages.

type SessionExporter

type SessionExporter struct {
	IncludeToolResults  bool
	IncludeSystemPrompt bool
	MaxMessages         int // 0 = all
	RedactSecrets       bool
}

SessionExporter configures how sessions are exported.

func NewSessionExporter

func NewSessionExporter() *SessionExporter

NewSessionExporter creates a SessionExporter with default settings.

func (*SessionExporter) Export

func (e *SessionExporter) Export(session *ExportedSession, format ExportFormat) (string, error)

Export dispatches to the format-specific renderer and returns the result.

type SessionIndex

type SessionIndex struct {
	ID        string
	Terms     map[string][]int // term → message indices containing it
	Messages  []IndexedMessage
	CreatedAt time.Time
	Model     string
	Provider  string
}

SessionIndex holds the inverted index for a single session.

type SessionLockedError

type SessionLockedError struct {
	ID string
}

SessionLockedError indicates a session is already open.

func (*SessionLockedError) Error

func (e *SessionLockedError) Error() string

type SessionMeta

type SessionMeta struct {
	ID         string    `json:"id"`
	Name       string    `json:"name,omitempty"`
	CWD        string    `json:"cwd,omitempty"`
	Model      string    `json:"model,omitempty"`
	Provider   string    `json:"provider,omitempty"`
	GitBranch  string    `json:"git_branch,omitempty"`
	MsgCount   int       `json:"message_count"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	Tags       []string  `json:"tags,omitempty"`
	TokenCount int       `json:"token_count,omitempty"`
}

SessionMeta holds lightweight metadata for listing without full parse.

type SessionRecord

type SessionRecord struct {
	ID           string
	ProjectDir   string
	Provider     string
	Model        string
	CreatedAt    time.Time
	UpdatedAt    time.Time
	ParentID     string
	Status       string
	Title        string
	TotalTokens  int
	TotalCostUSD float64
}

SessionRecord represents a persisted session in the SQLite store.

type SessionStats

type SessionStats struct {
	MessageCount int
	TotalTokens  int
	TotalCostUSD float64
	Duration     time.Duration
	ToolCalls    int
}

SessionStats contains aggregated statistics for a session.

type SessionThread

type SessionThread struct {
	ID                string   `json:"id"`
	Topic             string   `json:"topic"`
	Status            string   `json:"status"`
	StartedAtTurn     int      `json:"started_at_turn"`
	LastMentionedTurn int      `json:"last_mentioned_turn"`
	Decisions         []string `json:"decisions"`
	OpenQuestions     []string `json:"open_questions"`
}

type SmartCheckpointer

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

SmartCheckpointer takes snapshots only when meaningful state changes occur, filtering out redundant checkpoints.

func NewSmartCheckpointer

func NewSmartCheckpointer(store *SnapshotStore) *SmartCheckpointer

NewSmartCheckpointer creates a checkpointer that wraps a SnapshotStore. All trigger types are enabled by default.

func (*SmartCheckpointer) CheckpointsTaken

func (sc *SmartCheckpointer) CheckpointsTaken() int

CheckpointsTaken returns the number of checkpoints actually created.

func (*SmartCheckpointer) EventsSeen

func (sc *SmartCheckpointer) EventsSeen() int

EventsSeen returns the total number of events processed.

func (*SmartCheckpointer) FormatTriggers

func (sc *SmartCheckpointer) FormatTriggers() string

FormatTriggers returns a summary of which triggers are enabled.

func (*SmartCheckpointer) OnEvent

func (sc *SmartCheckpointer) OnEvent(event CheckpointTrigger, session *Session, action string)

OnEvent processes a checkpoint event. If meaningful state change is detected, it takes a snapshot with the provided action label.

func (*SmartCheckpointer) SetTrigger

func (sc *SmartCheckpointer) SetTrigger(trigger CheckpointTrigger, enabled bool)

SetTrigger enables or disables a specific trigger type.

func (*SmartCheckpointer) ShouldCheckpoint

func (sc *SmartCheckpointer) ShouldCheckpoint(event CheckpointTrigger, session *Session) bool

ShouldCheckpoint returns true only if the state has meaningfully changed since the last checkpoint.

func (*SmartCheckpointer) Stats

func (sc *SmartCheckpointer) Stats() string

Stats returns a human-readable summary of checkpoint activity.

type Snapshot

type Snapshot struct {
	ID        int       `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	MsgIndex  int       `json:"msg_index"`
	Action    string    `json:"action"`
	Label     string    `json:"label,omitempty"`
}

Snapshot records a point-in-time copy of a session.

type SnapshotStore

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

SnapshotStore manages snapshots for a session.

func NewSnapshotStore

func NewSnapshotStore(sessionID string) *SnapshotStore

NewSnapshotStore creates a new snapshot store for the given session.

func (*SnapshotStore) Cleanup

func (ss *SnapshotStore) Cleanup()

Cleanup removes old snapshots, keeping only the most recent maxSnaps.

func (*SnapshotStore) Format

func (ss *SnapshotStore) Format() string

Format returns a human-readable list of snapshots.

func (*SnapshotStore) List

func (ss *SnapshotStore) List() []Snapshot

List returns all snapshots, oldest first.

func (*SnapshotStore) Load

func (ss *SnapshotStore) Load() error

Load reads the snapshot index from disk.

func (*SnapshotStore) Rewind

func (ss *SnapshotStore) Rewind(id int) (*Session, error)

Rewind restores the session to the state at the given snapshot ID.

func (*SnapshotStore) Take

func (ss *SnapshotStore) Take(action string, sess *Session) error

Take saves a snapshot of the current session state.

type ThreadFork

type ThreadFork struct {
	OriginalThreadID string    `json:"original_thread_id"`
	NewThreadID      string    `json:"new_thread_id"`
	ForkPointStepID  string    `json:"fork_point_step_id"`
	CreatedAt        time.Time `json:"created_at"`
}

func ForkThread

func ForkThread(store ForkableStore, opts ForkOptions) (*ThreadFork, error)

type ToolCall

type ToolCall = types.ToolCall

ToolCall is an alias to the shared ToolCall type for persistence.

type ToolResult

type ToolResult = types.ToolResult

ToolResult is an alias to the shared ToolResult type for persistence.

type WAL

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

WAL (Write-Ahead Log) appends messages incrementally for crash recovery. Each message is appended immediately — if hawk crashes, the WAL has everything.

func NewWAL

func NewWAL(sessionID string) (*WAL, error)

NewWAL creates or opens a write-ahead log for a session.

func (*WAL) Append

func (w *WAL) Append(msg Message) error

Append writes a message to the WAL immediately. This is crash-safe: even if the process dies right after, the message is on disk.

func (*WAL) AppendMeta

func (w *WAL) AppendMeta(model, provider, cwd string) error

AppendMeta writes session metadata to the WAL.

func (*WAL) Close

func (w *WAL) Close() error

Close closes the WAL file.

func (*WAL) Remove

func (w *WAL) Remove() error

Remove deletes the WAL file (called after successful Save).

Jump to

Keyboard shortcuts

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