session

package
v0.56.7 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package session implements Prism's per-session state: an O(1) LRU file tracker (for delivery deduplication) and a token ledger (for savings reporting). Both are concurrency-safe and live for the lifetime of one MCP session or one CLI/agent session.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithFileLock added in v0.5.0

func WithFileLock(path string, timeout time.Duration, fn func() error) error

WithFileLock runs fn while holding an exclusive lock file. It is intended for short critical sections around cross-process cache/ledger updates.

Types

type Confidence

type Confidence string

Confidence is the qualitative judgement of whether previously-delivered content is still likely visible in the model's context window.

const (
	High   Confidence = "high"
	Medium Confidence = "medium"
	Low    Confidence = "low"
)

func EstimateConfidence

func EstimateConfidence(tokensSince int64, contextWindow int) Confidence

EstimateConfidence returns the confidence that a previously-sent item is still in the model's window, given how many tokens were delivered since it was sent and the total context window size.

type Entry

type Entry struct {
	FilePath            string
	ContentHash         string // SHA-256 of source content
	TokenDistanceAtSend int64  // cumulative tokens delivered when this was sent
	ContextUsedAtSend   int64  // agent-reported context size at send time (0 = not reported)
	DisclosureLevel     string
	AccessCount         int
	SymbolSHAs          map[string]string // symbol key → sha(RawText); used for semantic delta encoding
}

Entry records what was delivered for one file.

type Ledger

type Ledger struct {
	SessionID      string
	TotalOriginal  int64
	TotalDelivered int64
	ByTool         map[string]*ToolStats
	StartTime      time.Time
	// contains filtered or unexported fields
}

Ledger tracks per-session token savings.

func LoadLedger

func LoadLedger(path string) (*Ledger, error)

LoadLedger loads a persisted ledger from disk.

func NewLedger

func NewLedger(sessionID string) *Ledger

NewLedger constructs a new ledger.

func (*Ledger) Record

func (l *Ledger) Record(tool string, originalTokens, deliveredTokens int)

Record adds tokens to the ledger for the given tool.

func (*Ledger) RecordCall added in v0.19.6

func (l *Ledger) RecordCall(tool string)

RecordCall counts an invocation of a tool that has no token-savings baseline (e.g. a deterministic task op like change-impact, where the value is completeness, not cheaper delivery of the same context). Unlike Record, it leaves Original/Delivered and the ledger totals untouched, so it cannot dilute SavingsPercent — it only makes the tool's call count visible in ByTool.

func (*Ledger) Save

func (l *Ledger) Save(path string) error

Save writes the current ledger snapshot to disk as JSON.

func (*Ledger) SavingsPercent

func (l *Ledger) SavingsPercent() float64

SavingsPercent returns 1 - delivered/original.

func (*Ledger) Snapshot

func (l *Ledger) Snapshot() Summary

Snapshot returns an immutable view of the ledger.

func (*Ledger) TotalDeliveredTokens

func (l *Ledger) TotalDeliveredTokens() int64

TotalDeliveredTokens returns running total of delivered tokens.

type Summary

type Summary struct {
	SessionID      string               `json:"sessionId"`
	StartTime      string               `json:"startTime"`
	TotalOriginal  int64                `json:"totalOriginalTokens"`
	TotalDelivered int64                `json:"totalDeliveredTokens"`
	SavingsPercent float64              `json:"savingsPercent"`
	ByTool         map[string]ToolStats `json:"byTool"`
}

Summary returns a snapshot of ledger state suitable for JSON encoding.

type ToolStats

type ToolStats struct {
	Calls     int   `json:"calls"`
	Original  int64 `json:"original"`
	Delivered int64 `json:"delivered"`
}

ToolStats records token accounting for one MCP tool.

type Tracker

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

Tracker is an O(1) LRU cache keyed by file path.

func NewTracker

func NewTracker(maxFiles int) *Tracker

NewTracker creates a tracker with the given capacity.

func (*Tracker) Len

func (t *Tracker) Len() int

Len returns the number of tracked files.

func (*Tracker) Lookup

func (t *Tracker) Lookup(filePath, contentHash string) (*Entry, bool, bool)

Lookup returns a COPY of the entry for filePath if it exists. The second return value reports presence; the third whether the stored contentHash matches the supplied one.

A copy, not the live pointer: five call sites read entry fields after this mutex is released, and under `prism serve` requests run concurrently on one shared Handler — a concurrent Record mutated the same struct mid-read (this exact aliasing already produced the graphcache seen-count bug, single- threaded). SymbolSHAs is deep-copied for the same reason RecentEntries does it: the compressor reads that map while the indexer may replace it.

func (*Tracker) RecentEntries added in v0.7.0

func (t *Tracker) RecentEntries(n int) []Entry

RecentEntries returns copies of up to n entries, most recently used first. Used by drift checks to bound work to the hot working set.

func (*Tracker) Record

func (t *Tracker) Record(filePath, contentHash string, tokensDelivered int64, level string)

Record marks filePath as delivered with the given metadata. If the file is already tracked, AccessCount is incremented and metadata is updated.

func (*Tracker) RecordContextUsed added in v0.7.0

func (t *Tracker) RecordContextUsed(filePath string, v int64)

RecordContextUsed stores the agent-reported context size for a file that has already been tracked, so the next read can estimate confidence from the agent's own token count rather than Prism's ledger alone. No-op if the file isn't tracked or v is not positive.

func (*Tracker) Reset

func (t *Tracker) Reset()

Reset clears all entries.

func (*Tracker) UpdateSymbolSHAs added in v0.5.0

func (t *Tracker) UpdateSymbolSHAs(filePath string, shas map[string]string)

UpdateSymbolSHAs stores a symbol-key→sha map for a file that has already been tracked. Called after delivering a semantic delta so future re-reads can diff at symbol granularity. No-op if the file isn't tracked.

Jump to

Keyboard shortcuts

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