session

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 14 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 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 ExportToMarkdown

func ExportToMarkdown(sess *Session) string

ExportToMarkdown exports a session as readable markdown.

func FormatCheckpointList

func FormatCheckpointList(checkpoints []Checkpoint) string

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

func MigrateToJSONL

func MigrateToJSONL(id string) error

MigrateToJSONL converts a legacy JSON session to JSONL format.

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 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.

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 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 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 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 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    []ToolCall  `json:"tool_use,omitempty"`
	ToolResult *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 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.

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 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 ToolCall

type ToolCall struct {
	ID        string                 `json:"id"`
	Name      string                 `json:"name"`
	Arguments map[string]interface{} `json:"arguments"`
}

ToolCall mirrors client.ToolCall for persistence.

type ToolResult

type ToolResult struct {
	ToolUseID string `json:"tool_use_id"`
	Content   string `json:"content"`
	IsError   bool   `json:"is_error,omitempty"`
}

ToolResult mirrors client.ToolResult 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