sessions

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	GoalObjectiveMaxLength          = 4_000
	GoalMaxConsecutiveContinuations = 20
)
View Source
const (
	PruneKeptOpen    = "open in another Zero process"
	PruneKeptParent  = "parent of a session that is kept"
	PruneKeptUpdated = "updated while pruning"
	PruneKeptUndated = "its last update time could not be read"
)

The reasons Prune keeps a session that is old enough to remove.

View Source
const (
	MetadataFile = "metadata.json"
	EventsFile   = "events.jsonl"
)
View Source
const CheckpointsDir = "checkpoints"

CheckpointsDir is the per-session subdirectory holding content-addressed blobs.

View Source
const MinimumPruneAge = 24 * time.Hour

MinimumPruneAge is the shortest cutoff Prune accepts.

A floor under the lease, not a substitute for it. An older Zero, or anything else that writes a session without taking the lease, is invisible to prune, and a day is long enough that a session such a writer is actively using has been written since.

Variables

View Source
var ErrPruning = errors.New("locked by zero sessions prune")

ErrPruning is matched, through errors.Is, by the error a process gets when it tries to continue a session, or to create a session under it, while zero sessions prune holds that session or once it has removed it.

Functions

func CheckpointsEnabled

func CheckpointsEnabled() bool

CheckpointsEnabled reports whether checkpoint capture is enabled (default on; disabled with ZERO_CHECKPOINTS=off).

func CompactionMessages

func CompactionMessages(events []Event) []zeroruntime.Message

CompactionMessages converts durable session events into the same normalized message shape used by the running agent's compaction pipeline. Provider usage and checkpoint blobs are omitted. Message/tool fields rely on the session writer's invariant that tool output is scrubbed before persistence; ask_user answers and generic event previews are redacted here.

func DefaultRoot

func DefaultRoot(env map[string]string) string

func FormatExecPrompt

func FormatExecPrompt(prompt string, prepared PreparedExec) string

func IsResumableKind

func IsResumableKind(kind SessionKind) bool

IsResumableKind reports whether a session kind represents a standalone, user-resumable conversation rather than a transient or agent-owned sub-run. Regular ("") and user fork sessions are resumable; side, child, and spec sessions are not, so they do not flood the resume picker.

func ValidSessionID

func ValidSessionID(sessionID string) bool

Types

type AppendEventInput

type AppendEventInput struct {
	Type    EventType
	Payload any
}

type CheckpointFile

type CheckpointFile struct {
	Path    string `json:"path"`
	Blob    string `json:"blob,omitempty"`    // sha256 of prior content, "" if absent/skipped
	Absent  bool   `json:"absent,omitempty"`  // file did not exist before (restore -> delete)
	Skipped bool   `json:"skipped,omitempty"` // exceeded size cap; not recoverable
	Bytes   int    `json:"bytes,omitempty"`
	Mode    uint32 `json:"mode,omitempty"` // unix permission bits of the prior file; 0 if unknown (restore preserves existing mode)
}

CheckpointFile records the before-mutation state of one workspace file.

type CheckpointPayload

type CheckpointPayload struct {
	Tool  string           `json:"tool"`
	Files []CheckpointFile `json:"files"`
}

CheckpointPayload is the payload of an EventSessionCheckpoint event. It indexes the before-state blobs captured for one mutating tool call.

type ChildInput

type ChildInput struct {
	SessionID string
	Title     string
	Cwd       string
	ModelID   string
	Provider  string
	Tag       string
	Depth     int
	AgentName string
	TaskID    string
	Prompt    string
}

type CompactionOptions

type CompactionOptions struct {
	PreserveLast   int
	MaxPromptChars int
	SkipPrompt     bool
}

type CompactionPayload

type CompactionPayload struct {
	Summary                  string     `json:"summary"`
	PreserveLast             int        `json:"preserveLast"`
	CompactableCount         int        `json:"compactableCount"`
	PreservedCount           int        `json:"preservedCount"`
	CompactedThroughEventID  string     `json:"compactedThroughEventId,omitempty"`
	CompactedThroughSequence int        `json:"compactedThroughSequence,omitempty"`
	CompactableEvents        []EventRef `json:"compactableEvents,omitempty"`
	PreservedEvents          []EventRef `json:"preservedEvents,omitempty"`
	PromptChars              int        `json:"promptChars,omitempty"`
	Truncated                bool       `json:"truncated,omitempty"`
}

CompactionPayload is the payload of an EventCompaction event. It records the summary that should replace compacted-away events during replay.

func CompactionPayloadFromPlan

func CompactionPayloadFromPlan(summary string, plan CompactionPlan) (CompactionPayload, error)

type CompactionPlan

type CompactionPlan struct {
	SessionID         string     `json:"sessionId"`
	PreserveLast      int        `json:"preserveLast"`
	CompactableCount  int        `json:"compactableCount"`
	PreservedCount    int        `json:"preservedCount"`
	CompactableEvents []EventRef `json:"compactableEvents"`
	PreservedEvents   []EventRef `json:"preservedEvents"`
	SummaryPrompt     string     `json:"summaryPrompt"`
	// PromptChars counts prompt text content and excludes provider protocol framing.
	PromptChars int  `json:"promptChars"`
	Truncated   bool `json:"truncated,omitempty"`
}

type CreateInput

type CreateInput struct {
	SessionID           string
	SessionKind         SessionKind
	Title               string
	Cwd                 string
	ModelID             string
	Provider            string
	Tag                 string
	Depth               int
	ParentSessionID     string
	RootSessionID       string
	AgentName           string
	TaskID              string
	ForkedFromEventID   string
	ForkedFromSequence  int
	SpawnedFromEventID  string
	SpawnedFromSequence int
	SpecID              string
	SpecFilePath        string
	SpecStatus          SpecStatus
	SpecDraftModelID    string
	SpecDraftReasoning  string
	SpecUserComment     string
	SpecRejectReason    string
	SpecSourceSessionID string
	SpecImplSessionID   string
	Goal                *Goal
}

type EnsureSpecImplementationInput

type EnsureSpecImplementationInput struct {
	Title               string
	Cwd                 string
	ModelID             string
	Provider            string
	SpecID              string
	SpecFilePath        string
	SpecDraftModelID    string
	SpecDraftReasoning  string
	SpecUserComment     string
	SpecSourceSessionID string
	RootSessionID       string
	Prompt              string
}

type Event

type Event struct {
	ID        string          `json:"id"`
	SessionID string          `json:"sessionId"`
	Sequence  int             `json:"sequence"`
	Type      EventType       `json:"type"`
	CreatedAt string          `json:"createdAt"`
	Payload   json.RawMessage `json:"payload,omitempty"`
}

func RehydrateEvents

func RehydrateEvents(events []Event) ([]Event, error)

type EventRef

type EventRef struct {
	ID        string    `json:"id"`
	Sequence  int       `json:"sequence"`
	Type      EventType `json:"type"`
	CreatedAt string    `json:"createdAt,omitempty"`
}

type EventType

type EventType string
const (
	EventMessage            EventType = "message"
	EventToolCall           EventType = "tool_call"
	EventPermission         EventType = "permission"
	EventPermissionRequest  EventType = "permission_request"
	EventPermissionDecision EventType = "permission_decision"
	EventToolResult         EventType = "tool_result"
	EventProviderUsage      EventType = "provider_usage"
	EventUsage              EventType = EventProviderUsage
	EventError              EventType = "error"
	EventSessionCheckpoint  EventType = "session_checkpoint"
	EventSessionRewind      EventType = "session_rewind"
	EventCompaction         EventType = "session_compaction"
	EventSessionFork        EventType = "session_fork"
	EventSessionChild       EventType = "session_child"
	EventSpecialistStart    EventType = "specialist_start"
	EventSpecialistStop     EventType = "specialist_stop"
	EventSpecDraft          EventType = "spec_draft"
	EventSpecApproved       EventType = "spec_approved"
	EventSpecRejected       EventType = "spec_rejected"
	EventGoalCreated        EventType = "goal_created"
	EventGoalUpdated        EventType = "goal_updated"
	EventGoalCleared        EventType = "goal_cleared"
)

type ExecError

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

func (ExecError) Error

func (err ExecError) Error() string

type ExecMode

type ExecMode string
const (
	ModeNew    ExecMode = "new"
	ModeResume ExecMode = "resume"
	ModeFork   ExecMode = "fork"
)

type ForkInput

type ForkInput struct {
	SessionID   string
	SessionKind SessionKind
	Title       string
	Cwd         string
	ModelID     string
	Provider    string
	Tag         string
}

type Goal

type Goal struct {
	Objective         string     `json:"objective"`
	Status            GoalStatus `json:"status"`
	StatusReason      string     `json:"statusReason,omitempty"`
	TokenBudget       int        `json:"tokenBudget,omitempty"`
	TokensUsed        int        `json:"tokensUsed,omitempty"`
	ContinuationCount int        `json:"continuationCount,omitempty"`
	ContinuationLimit int        `json:"continuationLimit,omitempty"`
	CreatedAt         string     `json:"createdAt"`
	UpdatedAt         string     `json:"updatedAt"`
}

type GoalStatus

type GoalStatus string
const (
	GoalStatusActive        GoalStatus = "active"
	GoalStatusPaused        GoalStatus = "paused"
	GoalStatusBlocked       GoalStatus = "blocked"
	GoalStatusBudgetLimited GoalStatus = "budget_limited"
	GoalStatusUsageLimited  GoalStatus = "usage_limited"
	GoalStatusComplete      GoalStatus = "complete"
)

type MessageAttachments

type MessageAttachments struct {
	Images    int `json:"images"`
	Documents int `json:"documents"`
}

MessageAttachments is the count-only summary stored on user message events. It matches the TUI's attachments payload; image data is never persisted here.

func (*MessageAttachments) UnmarshalJSON

func (a *MessageAttachments) UnmarshalJSON(data []byte) error

UnmarshalJSON ignores malformed counts without dropping the message's text.

func (MessageAttachments) WithContent

func (a MessageAttachments) WithContent(content string) string

WithContent renders an attachment marker beside the original message text for history and replay. The stored content itself stays unchanged.

type Metadata

type Metadata struct {
	SessionID           string      `json:"sessionId"`
	SessionKind         SessionKind `json:"sessionKind,omitempty"`
	Title               string      `json:"title,omitempty"`
	Cwd                 string      `json:"cwd,omitempty"`
	ModelID             string      `json:"modelId,omitempty"`
	PermissionMode      string      `json:"permissionMode,omitempty"`
	Provider            string      `json:"provider,omitempty"`
	Tag                 string      `json:"tag,omitempty"`
	Depth               int         `json:"depth,omitempty"`
	ParentSessionID     string      `json:"parentSessionId,omitempty"`
	RootSessionID       string      `json:"rootSessionId,omitempty"`
	AgentName           string      `json:"agentName,omitempty"`
	TaskID              string      `json:"taskId,omitempty"`
	ForkedFromEventID   string      `json:"forkedFromEventId,omitempty"`
	ForkedFromSequence  int         `json:"forkedFromSequence,omitempty"`
	SpawnedFromEventID  string      `json:"spawnedFromEventId,omitempty"`
	SpawnedFromSequence int         `json:"spawnedFromSequence,omitempty"`
	SpecID              string      `json:"specId,omitempty"`
	SpecFilePath        string      `json:"specFilePath,omitempty"`
	SpecStatus          SpecStatus  `json:"specStatus,omitempty"`
	SpecDraftModelID    string      `json:"specDraftModelId,omitempty"`
	SpecDraftReasoning  string      `json:"specDraftReasoning,omitempty"`
	SpecUserComment     string      `json:"specUserComment,omitempty"`
	SpecRejectReason    string      `json:"specRejectReason,omitempty"`
	SpecSourceSessionID string      `json:"specSourceSessionId,omitempty"`
	SpecImplSessionID   string      `json:"specImplSessionId,omitempty"`
	Goal                *Goal       `json:"goal,omitempty"`
	CreatedAt           string      `json:"createdAt"`
	UpdatedAt           string      `json:"updatedAt"`
	EventCount          int         `json:"eventCount"`
	LastEventType       EventType   `json:"lastEventType,omitempty"`
}

type PrepareExecOptions

type PrepareExecOptions struct {
	Store            *Store
	SessionID        string
	Title            string
	Cwd              string
	ModelID          string
	Provider         string
	Tag              string
	Depth            int
	CallingSessionID string
	CallingToolUseID string
	AgentName        string
	TaskID           string
	Resume           string
	ResumeLatest     bool
	Fork             string
}

type PreparedExec

type PreparedExec struct {
	Mode          ExecMode
	Session       Metadata
	ContextEvents []Event
	Store         *Store
}

func PrepareExec

func PrepareExec(options PrepareExecOptions) (PreparedExec, error)

type PruneEntry

type PruneEntry struct {
	SessionID string      `json:"sessionId"`
	Title     string      `json:"title,omitempty"`
	Kind      SessionKind `json:"kind,omitempty"`
	UpdatedAt string      `json:"updatedAt"`
	Bytes     int64       `json:"bytes"`
	Reason    string      `json:"reason,omitempty"`
}

PruneEntry is one session Prune removed (or in a dry run would remove), kept although it was old enough, or failed to remove.

type PruneOptions

type PruneOptions struct {
	// OlderThan makes a session a candidate when it was last updated at least
	// this long ago. It must be at least MinimumPruneAge.
	OlderThan time.Duration
	// DryRun decides everything a real run would and removes nothing. It takes
	// the same locks to decide, so a Zero opening a session at the moment it is
	// being checked is told to try again, as it would be during a real run.
	DryRun bool
}

PruneOptions chooses what Prune removes.

type PruneReport

type PruneReport struct {
	Cutoff string `json:"cutoff"`
	DryRun bool   `json:"dryRun"`
	// Removed are the sessions removed, or in a dry run the ones a real run
	// would remove.
	Removed []PruneEntry `json:"removed"`
	// Kept are sessions Prune left for a reason other than being recent.
	Kept []PruneEntry `json:"kept"`
	// Failed are sessions whose removal went wrong, or in a dry run could not be
	// checked; Reason says how. A failure after the metadata was removed leaves
	// a directory List no longer shows.
	Failed []PruneEntry `json:"failed"`
}

PruneReport says what Prune did, or in a dry run what it would do. Sessions newer than the cutoff are not listed.

type RecordCompactionInput

type RecordCompactionInput struct {
	Plan    CompactionPlan
	Summary string
}

type RecordSpecInput

type RecordSpecInput struct {
	SpecID              string
	SpecFilePath        string
	SpecStatus          SpecStatus
	SpecDraftModelID    string
	SpecDraftReasoning  string
	SpecUserComment     string
	SpecRejectReason    string
	SpecSourceSessionID string
	SpecImplSessionID   string
}

type RestoreReport

type RestoreReport struct {
	TargetSequence int      `json:"targetSequence"`
	FilesRestored  int      `json:"filesRestored"`
	FilesDeleted   int      `json:"filesDeleted"`
	Skipped        []string `json:"skipped,omitempty"` // paths whose before-state was not recoverable
}

RestoreReport summarizes a workspace restore.

type RewindMarker

type RewindMarker struct {
	TargetSequence int           `json:"targetSequence"`
	Report         RestoreReport `json:"report"`
}

RewindMarker is the payload of the EventSessionRewind event appended after a rewind.

type RewindOptions

type RewindOptions struct {
	TargetSequence int
	TargetEventID  string
	KeepTarget     bool
}

type RewindPlan

type RewindPlan struct {
	SessionID       string     `json:"sessionId"`
	TargetSequence  int        `json:"targetSequence"`
	TargetEventID   string     `json:"targetEventId"`
	KeepTarget      bool       `json:"keepTarget"`
	KeptCount       int        `json:"keptCount"`
	DroppedCount    int        `json:"droppedCount"`
	LastKeptEventID string     `json:"lastKeptEventId,omitempty"`
	KeptEvents      []EventRef `json:"keptEvents"`
	DroppedEvents   []EventRef `json:"droppedEvents"`
}

type SessionKind

type SessionKind string
const (
	SessionKindFork      SessionKind = "fork"
	SessionKindChild     SessionKind = "child"
	SessionKindSide      SessionKind = "side"
	SessionKindSpecDraft SessionKind = "spec-draft"
	SessionKindSpecImpl  SessionKind = "spec-impl"
)

type SpecStatus

type SpecStatus string
const (
	SpecStatusDraft    SpecStatus = "draft"
	SpecStatusApproved SpecStatus = "approved"
	SpecStatusRejected SpecStatus = "rejected"
)

type Store

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

func NewStore

func NewStore(options StoreOptions) *Store

func (*Store) AddGoalUsage

func (store *Store) AddGoalUsage(sessionID string, tokens int) (Metadata, *Event, error)

AddGoalUsage accounts tokens consumed while a goal is active. Reaching the optional budget pauses the goal before another autonomous turn can start.

func (*Store) AppendEvent

func (store *Store) AppendEvent(sessionID string, input AppendEventInput) (Event, error)

func (*Store) AppendEventUnlessExists

func (store *Store) AppendEventUnlessExists(sessionID string, input AppendEventInput, exists func([]Event) bool) (Event, bool, error)

AppendEventUnlessExists appends input only when exists(currentEvents) is false, performing the existence check and the append atomically under the session lock (in-process mutex + cross-process file lock). It is the safe primitive for "record once" accounting: a plain ReadEvents-then-AppendEvent has a check-then-act race where two callers — even in separate processes — both see the event absent and each append a duplicate. Returns appended=false when the predicate already matched. A nil predicate always appends.

func (*Store) AppendEvents

func (store *Store) AppendEvents(sessionID string, inputs []AppendEventInput) ([]Event, error)

AppendEvents appends a batch of events atomically under one session lock and durability pass. The returned events have contiguous sequences in input order. An empty batch is a no-op and does not rewrite metadata.

func (*Store) ApplyRewind

func (store *Store) ApplyRewind(sessionID, workspaceRoot string, targetSeq int) (RestoreReport, error)

ApplyRewind performs a full safe rewind: restore workspace files to targetSeq, truncate the event log, prune now-orphaned blobs, and append an EventSessionRewind marker. Returns the restore report.

func (*Store) CaptureToolCheckpoint

func (store *Store) CaptureToolCheckpoint(sessionID, workspaceRoot, tool string, paths []string) (Event, error)

CaptureToolCheckpoint snapshots the current (before-mutation) content of each path and records an EventSessionCheckpoint indexing the blobs. Capture is best-effort: an unreadable file is recorded as skipped rather than failing the caller. Returns the appended event (or a zero Event if there was nothing to do).

func (*Store) ClearGoal

func (store *Store) ClearGoal(sessionID string) (Metadata, Event, error)

ClearGoal removes the current goal while preserving an audit event.

func (*Store) Create

func (store *Store) Create(input CreateInput) (Metadata, error)

func (*Store) CreateChild

func (store *Store) CreateChild(parentSessionID string, input ChildInput) (Metadata, error)

func (*Store) CreateGoal

func (store *Store) CreateGoal(sessionID, objective string, tokenBudget int) (Metadata, Event, error)

CreateGoal persists a new active goal for a session. It refuses to replace an existing goal so callers must make replacement an explicit user decision.

func (*Store) EditGoal

func (store *Store) EditGoal(sessionID, objective string, tokenBudget int) (Metadata, Event, error)

EditGoal replaces the objective and optional budget without resetting usage or lifecycle timestamps. User-facing command handling owns confirmation.

func (*Store) EnsureSpecImplementation

func (store *Store) EnsureSpecImplementation(input EnsureSpecImplementationInput) (Metadata, []Event, error)

func (*Store) FindSpecImplementation

func (store *Store) FindSpecImplementation(specID string, sourceSessionID string) (*Metadata, error)

func (*Store) Fork

func (store *Store) Fork(parentSessionID string, input ForkInput) (Metadata, error)

func (*Store) Get

func (store *Store) Get(sessionID string) (*Metadata, error)

func (*Store) Hold

func (store *Store) Hold(sessionID string)

Hold marks sessionID as open in this process until the process exits.

A SESSION HOLDS NO LOCK BETWEEN WRITES. session.lock is taken around each write and released straight after, so nothing told `zero sessions prune` in another terminal that a TUI, an exec run or an editor still had the session open, and an idle open session looked exactly like an abandoned one. Hold takes a shared lock on the session's lease file and keeps it for the life of the process; prune takes the same lock exclusively and leaves alone any session it cannot get. Every write holds its session this way (lockSession).

Hold never waits and never fails its caller. A lease that cannot be taken, because the session directory is gone or prune holds it at this moment, only means prune cannot see this process, and that is enough for a write: it lands under session.lock, where prune checks the session again, so either prune sees the write and keeps the session or the write finds the session gone. A read changes nothing prune checks, so the reads that continue a session, and the creations that read a parent, use holdOrRefuse instead.

func (*Store) HoldExclusive

func (store *Store) HoldExclusive(sessionID string) (release func(), locked bool, err error)

HoldExclusive takes sessionID's lease exclusively without waiting, which is how prune keeps every other process out of a session while it checks or removes it. It reports false, holding nothing, when any process holds the lease. While it is held, Hold takes nothing and holdOrRefuse refuses. release lets it go, and does nothing after the first call.

func (*Store) HoldToContinue

func (store *Store) HoldToContinue(sessionID string) error

HoldToContinue holds a session the caller has already picked, having read its metadata, and is about to continue: the TUI's resume, exec --resume and --fork, and ACP's session/load and session/resume. It refuses, with an error matching ErrPruning, a session prune holds and one that is gone by the time it is held, whether prune is part way through removing it or has finished. Callers must not fall back to reading the session another way on that error. ReadRehydratedEvents on its own still reads a session that does not exist as an empty one, for callers that picked nothing.

func (*Store) Latest

func (store *Store) Latest() (*Metadata, error)

func (*Store) LatestResumable

func (store *Store) LatestResumable() (*Metadata, error)

LatestResumable returns the most-recently-updated resumable session, or nil when none exist. Used by `/resume latest` so it lands on a real conversation instead of the newest child/spec sub-run.

func (*Store) Lineage

func (store *Store) Lineage(sessionID string) ([]Metadata, error)

func (*Store) List

func (store *Store) List() ([]Metadata, error)

func (*Store) ListChildren

func (store *Store) ListChildren(parentSessionID string) ([]Metadata, error)

func (*Store) ListResumable

func (store *Store) ListResumable() ([]Metadata, error)

ListResumable returns only the sessions a user can resume as standalone conversations (see IsResumableKind), newest-first like List.

func (*Store) PauseGoalIfActive

func (store *Store) PauseGoalIfActive(sessionID, reason string) (Metadata, *Event, error)

PauseGoalIfActive pauses a goal only while it is still active. It is used by cancellation paths where an in-flight agent may have completed or blocked the goal immediately before the cancellation reached the runtime.

func (*Store) PlanCompaction

func (store *Store) PlanCompaction(sessionID string, options CompactionOptions) (CompactionPlan, error)

func (*Store) PlanRewind

func (store *Store) PlanRewind(sessionID string, options RewindOptions) (RewindPlan, error)

func (*Store) Prune

func (store *Store) Prune(options PruneOptions) (PruneReport, error)

Prune removes sessions last updated before the cutoff that OlderThan sets.

Only on request: nothing in Zero calls it by itself (#971). It never removes:

  • a session another process has open, which holds its lease (see Hold);
  • a session with a descendant that is kept, including one created after the plan was made, because Lineage and Tree fail on a missing ancestor;
  • a session written between the plan and its removal;
  • a session whose last update time cannot be read.

Descendants are removed before their ancestors, so a descendant that turns out to be open part way through still keeps every ancestor above it. Within a session the metadata goes first, under both the lease and the write lock: from then on List and Get do not show it, so a removal that fails part way leaves nothing that looks like a session.

func (*Store) ReadEvents

func (store *Store) ReadEvents(sessionID string) ([]Event, error)

func (*Store) ReadEventsWithPresence

func (store *Store) ReadEventsWithPresence(sessionID string) ([]Event, bool, error)

ReadEventsWithPresence preserves the distinction between an intentionally empty event log and a missing one. Most readers accept both as empty history, but activation protocols that promise to restore previously populated context need the stronger signal.

func (*Store) ReadRehydratedEvents

func (store *Store) ReadRehydratedEvents(sessionID string) ([]Event, error)

func (*Store) ReadRehydratedEventsWithPresence

func (store *Store) ReadRehydratedEventsWithPresence(sessionID string) ([]Event, bool, error)

ReadRehydratedEventsWithPresence carries the underlying event-log presence through compaction projection without changing ReadRehydratedEvents' existing empty-on-missing contract.

It is how a session is loaded to be continued (the TUI's resume, `exec --resume` and --fork, ACP's session/load and session/resume), so it holds the session open, and it fails with ErrPruning while prune holds it. Callers that fall back to ReadEvents when rehydration fails must not fall back on that error. See holdOrRefuse.

func (*Store) ReadReplayEvents

func (store *Store) ReadReplayEvents(sessionID string) ([]Event, error)

func (*Store) RecordCompaction

func (store *Store) RecordCompaction(sessionID string, input RecordCompactionInput) (Event, error)

func (*Store) RecordSpec

func (store *Store) RecordSpec(sessionID string, input RecordSpecInput) (Metadata, Event, error)

func (*Store) Release

func (store *Store) Release(sessionID string)

Release gives up this Store's lease on sessionID. Nothing in Zero calls it yet: a process holds every session it has touched until it exits, which releases every lease with it, and tests use Release to stand in for that exit. A long-lived process that switches sessions, like the TUI on /new, could call it for the session it leaves. The lease itself goes once no other Store in the process holds it either.

func (*Store) ReserveGoalContinuation

func (store *Store) ReserveGoalContinuation(sessionID string) (Metadata, *Event, bool, error)

ReserveGoalContinuation atomically reserves one automatic continuation. Once the persisted consecutive-run limit is exhausted it pauses the goal before another provider request can start, even when the provider reports no usage.

func (*Store) ResetGoalContinuations

func (store *Store) ResetGoalContinuations(sessionID string) (Metadata, error)

ResetGoalContinuations starts a fresh autonomous-run allowance after explicit user input. It makes the safety bound consecutive rather than lifetime-wide.

func (*Store) RestoreToSequence

func (store *Store) RestoreToSequence(sessionID, workspaceRoot string, targetSeq int) (RestoreReport, error)

RestoreToSequence reverts workspace files to their state at targetSeq by applying the before-snapshots of every checkpoint after the target, newest-first (so the snapshot closest to the target wins). It does not modify the event log.

func (*Store) SnapshotForCheckpoint

func (store *Store) SnapshotForCheckpoint(sessionID, workspaceRoot, tool string, paths []string) (CheckpointPayload, bool)

SnapshotForCheckpoint reads and stores the before-mutation blobs for paths and returns the checkpoint payload WITHOUT appending an event.

CONTRACT: the returned payload references blobs that are ORPHAN-VULNERABLE — a concurrent pruneOrphanBlobs/ApplyRewind can delete them — until the caller appends an EventSessionCheckpoint carrying this payload. The caller therefore MUST record that event promptly, including on cancellation paths. Prefer CaptureToolCheckpoint, which writes the blobs AND appends the event atomically under one session lock; use SnapshotForCheckpoint only when the event must be batched IN ORDER with other session events (the TUI captures before each mutating tool, batches the checkpoint with the run's other events to preserve recorded ordering, and flushes them at end-of-run and on cancel).

Returns ok=false when there is nothing to record (disabled, no paths, or no capturable files).

func (*Store) Tree

func (store *Store) Tree(rootSessionID string) (TreeNode, error)

func (*Store) TruncateEvents

func (store *Store) TruncateEvents(sessionID string, keepThroughSequence int) error

TruncateEvents atomically rewrites events.jsonl keeping only events with Sequence <= keepThroughSequence, and updates metadata EventCount.

func (*Store) UpdateGoal

func (store *Store) UpdateGoal(sessionID string, status GoalStatus, reason string) (Metadata, Event, error)

UpdateGoal changes a goal's lifecycle state. Terminal goals remain available for status/history until the user explicitly clears them.

func (*Store) UpdateMode

func (store *Store) UpdateMode(sessionID string, mode string) (Metadata, error)

UpdateMode replaces a session's permission mode without changing its activity timestamp or event counters. An empty mode clears the session override; the stored value is not validated here because the reader that turns it back into a live mode is the boundary that decides what a stored string may become.

func (*Store) UpdateModel

func (store *Store) UpdateModel(sessionID string, modelID string) (Metadata, error)

UpdateModel replaces a session's selected model without changing its activity timestamp or event counters. An empty model clears the session override.

func (*Store) UpdateTitle

func (store *Store) UpdateTitle(sessionID string, title string) (Metadata, error)

UpdateTitle replaces a session's Title and returns the updated metadata. It is serialized under the same per-session lock as AppendEvent and re-reads the latest metadata under that lock before rewriting, so a concurrent append can't clobber the new title (nor the title clobber a concurrent append's event count/timestamp). UpdatedAt is deliberately left untouched: a rename is not activity, so it must not reorder the session in the resumable list. A blank title is rejected so a failed model generation can never erase a useful first-message title, and an unchanged title is a no-op (no rewrite/fsync).

func (*Store) UpdateTitleIfCurrent

func (store *Store) UpdateTitleIfCurrent(sessionID string, expected string, title string) (Metadata, bool, error)

UpdateTitleIfCurrent replaces a session title only when it still matches expected. It lets background automatic naming avoid overwriting a newer manual rename while keeping the check and write under the same per-session lock.

type StoreOptions

type StoreOptions struct {
	RootDir string
	Now     func() time.Time
	Env     map[string]string
}

type TreeNode

type TreeNode struct {
	Session  Metadata   `json:"session"`
	Children []TreeNode `json:"children"`
}

Jump to

Keyboard shortcuts

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