storage

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareTaskIDs added in v0.1.1

func CompareTaskIDs(a, b string) int

CompareTaskIDs compares two task ID strings numerically.

func GenerateName

func GenerateName() string

GenerateName returns a random name in adjective-gerund-noun format.

func SortTasksByID added in v0.1.1

func SortTasksByID(tasks []Task)

SortTasksByID sorts tasks by numeric ID ascending.

Types

type AllowedCommandEntry added in v0.1.0

type AllowedCommandEntry struct {
	CommandPrefix string `json:"command_prefix"`
	Description   string `json:"description,omitempty"`
}

type CacheBreakInfo added in v0.1.1

type CacheBreakInfo struct {
	PrevCacheReadTokens int     `json:"prev_cache_read_tokens"`
	CurrCacheReadTokens int     `json:"curr_cache_read_tokens"`
	DropAbsolute        int     `json:"drop_absolute"`
	DropFraction        float64 `json:"drop_fraction"`
	SystemChanged       bool    `json:"system_changed,omitempty"`
	ToolsChanged        bool    `json:"tools_changed,omitempty"`
	Note                string  `json:"note,omitempty"`
}

CacheBreakInfo is attached to an LLMCallEntry when the prompt cache hit rate unexpectedly dropped relative to the previous turn. It captures why the cache likely invalidated so the session can be diagnosed after-the- fact without replaying the full request.

type Compaction

type Compaction struct {
	Summary  string            `json:"summary"`
	Messages []json.RawMessage `json:"messages,omitempty"`
}

Compaction stores a compaction summary and optionally kept messages.

type ContextSnapshot

type ContextSnapshot struct {
	Messages            []agentcore.AgentMessage
	Provider            string
	Model               string
	Thinking            string
	PlanSlug            string
	PlanTitle           string
	PlanPhase           string
	PlanPreMode         string
	PlanAllowedCommands []AllowedCommandEntry
}

ContextSnapshot is the projected runtime state from a session log.

type Entry

type Entry struct {
	Kind      EntryKind       `json:"kind"`
	ID        string          `json:"id"`
	ParentID  string          `json:"parent_id,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
	Data      json.RawMessage `json:"data"`
}

Entry is a single JSONL line in the session file.

type EntryKind

type EntryKind string

EntryKind identifies the type of a JSONL entry.

const (
	EntryHeader         EntryKind = "header"
	EntryMessage        EntryKind = "message"
	EntryModelChange    EntryKind = "model_change"
	EntryCompaction     EntryKind = "compaction"
	EntryThinkingChange EntryKind = "thinking_change"
	EntrySessionInfo    EntryKind = "session_info"
	EntryPlanSlug       EntryKind = "plan_slug"
	EntryPlanState      EntryKind = "plan_state"
	EntryLLMCall        EntryKind = "llm_call"
)
type Header struct {
	Version   int       `json:"version"`
	SessionID string    `json:"session_id"`
	Name      string    `json:"name,omitempty"`
	Cwd       string    `json:"cwd"`
	Created   time.Time `json:"created"`
}

Header is the first line of a session file.

type History

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

History provides append-only input history with per-project filtering. The backing file (~/.codebot/history.jsonl) is shared across all projects; only entries matching the current project are surfaced.

func NewHistory

func NewHistory(path, project, sessionID string) *History

NewHistory loads history from path, filtering by project.

func (*History) Add

func (h *History) Add(text string)

Add appends text to history. Duplicates are moved to the front.

func (*History) Get

func (h *History) Get(index int) string

Get returns the history entry at index (0 = most recent).

func (*History) Len

func (h *History) Len() int

Len returns the number of history entries for the current project.

func (*History) SetSessionID

func (h *History) SetSessionID(id string)

SetSessionID updates the session ID for subsequent entries (e.g. after session switch).

type HistoryEntry

type HistoryEntry struct {
	Display        string         `json:"display"`
	PastedContents map[string]any `json:"pastedContents"`
	Timestamp      int64          `json:"timestamp"`
	Project        string         `json:"project"`
	SessionID      string         `json:"sessionId,omitempty"`
}

HistoryEntry is one line in the JSONL history file.

type LLMCallEntry added in v0.1.1

type LLMCallEntry struct {
	Provider            string          `json:"provider"`
	Model               string          `json:"model"`
	InputTokens         int             `json:"input_tokens"`
	OutputTokens        int             `json:"output_tokens"`
	CacheReadTokens     int             `json:"cache_read_tokens,omitempty"`
	CacheCreationTokens int             `json:"cache_creation_tokens,omitempty"`
	TotalTokens         int             `json:"total_tokens,omitempty"`
	LatencyMs           int64           `json:"latency_ms,omitempty"`
	StopReason          string          `json:"stop_reason,omitempty"`
	ThinkingLevel       string          `json:"thinking_level,omitempty"`
	CacheBreak          *CacheBreakInfo `json:"cache_break,omitempty"`
}

LLMCallEntry is a per-turn observability record for a single LLM response. Emitted once per assistant message_end, independent of the message itself so that downstream can diagnose cache hits, latency, and provider without re-parsing the message payload.

type Manager

type Manager struct {
	Dir string
}

Manager manages session files in a directory.

func NewManager

func NewManager(dir string) *Manager

NewManager creates a Manager for the given sessions directory.

func (*Manager) Create

func (m *Manager) Create(cwd string) (*Store, error)

Create creates a new session.

func (*Manager) List

func (m *Manager) List() ([]SessionInfo, error)

List returns all sessions sorted by updated time (newest first).

func (*Manager) MostRecent

func (m *Manager) MostRecent() (*SessionInfo, error)

MostRecent returns the most recently updated session.

func (*Manager) Open

func (m *Manager) Open(id string) (*Store, error)

Open opens an existing session by ID.

func (*Manager) OpenPath

func (m *Manager) OpenPath(path string) (*Store, error)

OpenPath opens a session by file path.

type ModelChange

type ModelChange struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

ModelChange records a model switch event.

type PlanFile

type PlanFile struct {
	Name    string // filename without .md
	ModTime int64  // unix timestamp
}

PlanFile represents a plan file entry for listing.

type PlanSlugEntry added in v0.1.0

type PlanSlugEntry struct {
	Slug  string `json:"slug"`
	Title string `json:"title"`
}

PlanSlugEntry records which plan file belongs to this session.

type PlanStateEntry added in v0.1.0

type PlanStateEntry struct {
	Phase           string                `json:"phase"`
	Slug            string                `json:"slug,omitempty"`
	Title           string                `json:"title,omitempty"`
	PreMode         string                `json:"pre_mode,omitempty"`
	AllowedCommands []AllowedCommandEntry `json:"allowed_commands,omitempty"`
}

type PlanStore

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

PlanStore manages plan markdown files in a single directory.

func NewPlanStore

func NewPlanStore(dir string) *PlanStore

NewPlanStore creates a PlanStore and ensures the directory exists.

func (*PlanStore) Delete

func (s *PlanStore) Delete(name string) error

Delete removes a plan file.

func (*PlanStore) List

func (s *PlanStore) List() ([]PlanFile, error)

List returns all plan files sorted by modification time (newest first).

func (*PlanStore) Load

func (s *PlanStore) Load(name string) (string, error)

Load reads a plan file by name. Returns "", nil if not found.

func (*PlanStore) Path added in v0.1.0

func (s *PlanStore) Path(name string) string

func (*PlanStore) Save

func (s *PlanStore) Save(name, content string) error

Save writes plan content as a markdown file.

type SessionInfo

type SessionInfo struct {
	ID           string
	Name         string
	Path         string
	Cwd          string
	Created      time.Time
	Updated      time.Time
	MessageCount int
	FirstMessage string // first user message, truncated to 80 chars
}

SessionInfo is a summary of a session for listing.

type Store

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

Store manages a single session JSONL file.

func (*Store) AppendCompaction

func (s *Store) AppendCompaction(summary string, keptMessages []json.RawMessage) error

AppendCompaction records a compaction event with summary and optional kept messages.

func (*Store) AppendLLMCall added in v0.1.1

func (s *Store) AppendLLMCall(entry LLMCallEntry) error

AppendLLMCall records a single LLM response's observability metadata. This is written alongside the assistant message itself, so the message payload stays minimal while diagnostics (cache/latency/provider) stay queryable without replaying the whole message.

func (*Store) AppendMessage

func (s *Store) AppendMessage(msg agentcore.Message) error

AppendMessage serializes and appends an agentcore.Message.

Thinking blocks are truncated to maxStoredThinkingRunes before write to keep session files compact. Truncation is storage-only — the in-memory message retains full thinking for this turn, since agentcore may still need it during the same agent_end lifecycle.

func (*Store) AppendModelChange

func (s *Store) AppendModelChange(provider, model string) error

AppendModelChange records a model switch.

func (*Store) AppendPlanSlug added in v0.1.0

func (s *Store) AppendPlanSlug(slug, title string) error

AppendPlanSlug records the plan file slug associated with this session.

func (*Store) AppendPlanState added in v0.1.0

func (s *Store) AppendPlanState(phase, slug, title, preMode string, allowedCommands []AllowedCommandEntry) error

func (*Store) AppendThinkingLevelChange

func (s *Store) AppendThinkingLevelChange(level string) error

AppendThinkingLevelChange records a thinking level switch.

func (*Store) BuildSnapshot

func (s *Store) BuildSnapshot() (ContextSnapshot, error)

BuildSnapshot reconstructs runtime state by walking the tree from the current leaf.

func (*Store) Close

func (s *Store) Close() error

Close closes the session file.

func (*Store) Header

func (s *Store) Header() Header

Header returns the session header.

func (*Store) Path

func (s *Store) Path() string

Path returns the session file path.

func (*Store) SetName

func (s *Store) SetName(name string) error

SetName updates the session display name by appending a session_info entry.

type Task added in v0.1.1

type Task struct {
	ID          string         `json:"id"`
	Subject     string         `json:"subject"`
	Description string         `json:"description,omitempty"`
	ActiveForm  string         `json:"activeForm,omitempty"`
	Status      TaskStatus     `json:"status"`
	Owner       string         `json:"owner,omitempty"`
	Blocks      []string       `json:"blocks"`
	BlockedBy   []string       `json:"blockedBy"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

Task is a single tracked work item.

type TaskNotifyFn added in v0.1.1

type TaskNotifyFn func(TaskSnapshot)

TaskNotifyFn is called after each store mutation with the latest snapshot.

type TaskSnapshot added in v0.1.1

type TaskSnapshot struct {
	Items      []Task
	Pending    int
	InProgress int
	Completed  int
	Total      int
}

TaskSnapshot is a read-only snapshot of all tasks sent to the TUI.

type TaskStatus added in v0.1.1

type TaskStatus string

TaskStatus represents the lifecycle state of a task.

const (
	TaskPending    TaskStatus = "pending"
	TaskInProgress TaskStatus = "in_progress"
	TaskCompleted  TaskStatus = "completed"
)

type TaskStore added in v0.1.1

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

TaskStore is a thread-safe task store with optional file persistence.

func NewTaskStore added in v0.1.1

func NewTaskStore() *TaskStore

NewTaskStore creates an empty store.

func (*TaskStore) Create added in v0.1.1

func (s *TaskStore) Create(subject, description, activeForm string, metadata map[string]any) *Task

Create adds a new task and returns a copy.

func (*TaskStore) Delete added in v0.1.1

func (s *TaskStore) Delete(id string) bool

Delete removes a task and any persisted file.

func (*TaskStore) Get added in v0.1.1

func (s *TaskStore) Get(id string) (*Task, bool)

Get returns a copy of the task or false if not found.

func (*TaskStore) List added in v0.1.1

func (s *TaskStore) List() []Task

List returns copies of all tasks sorted by ID.

func (*TaskStore) Reset added in v0.1.1

func (s *TaskStore) Reset() error

Reset clears all tasks from memory and persistence while preserving the monotonic task ID sequence for future task creation.

func (*TaskStore) SetDir added in v0.1.1

func (s *TaskStore) SetDir(dir string) error

SetDir enables file persistence. The directory is created lazily on the first write (persistLocked / writeHighWaterMarkLocked) — sessions that never create a task leave nothing behind on disk.

func (*TaskStore) SetNotifyFn added in v0.1.1

func (s *TaskStore) SetNotifyFn(fn TaskNotifyFn)

SetNotifyFn registers a callback invoked after every mutation.

func (*TaskStore) Snapshot added in v0.1.1

func (s *TaskStore) Snapshot() TaskSnapshot

Snapshot returns the current read-only snapshot.

func (*TaskStore) Update added in v0.1.1

func (s *TaskStore) Update(id string, opts TaskUpdateOpts) (*Task, error)

Update modifies a task and returns the updated copy.

type TaskUpdateOpts added in v0.1.1

type TaskUpdateOpts struct {
	Status       *TaskStatus
	Subject      *string
	Description  *string
	ActiveForm   *string
	Owner        *string
	Metadata     map[string]any // merged; nil-valued keys are deleted
	AddBlocks    []string
	AddBlockedBy []string
}

TaskUpdateOpts describes optional fields to update.

type ThinkingLevelChange

type ThinkingLevelChange struct {
	Level string `json:"level"`
}

ThinkingLevelChange records a thinking level switch event.

Jump to

Keyboard shortcuts

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